ngram
listlengths
0
67.8k
[ "trees: stage_subtree = trees[0] stage_order = root_last_traversal(target_stage, lambda n: stage_subtree[n][1]) pipeline = [(stage_subtree[stage][0],", "in required_stages: required_stages.append(suppliers[0]) required_stages_set.append(required_stages) return required_stages_set def validator(stage: str, subtree: Dict[str, List[str]]): stage_program_arguments", "stage_program_arguments = get_stage_program_arguments(stage_name, program_arguments) if stage.cacheable: with Cache(file_system, cache_path) as cache: cache[stage_name] =", "'{stage_name}' cannot be satisfied because no stage supplies resource '{requirement}'\") elif len(suppliers) >", "stage.invoker(file_system, stage_resources, stage_cache, stage_program_arguments, configuration, remote_proxy) else: stage.invoker(file_system, stage_resources, None, stage_program_arguments, configuration, remote_proxy)", "ResourceNotSuppliedError(Exception): pass def get_stage_program_arguments(stage: str, program_arguments: Dict[str, Any]): arguments = { 'global': program_arguments['global'],", "requirement in requirements: suppliers = [stage.name for stage in stages.values() if requirement in", "import Any, Dict, List class MultipleSuppliersError(Exception): pass class CyclicStagesError(Exception): pass class UnsatisfiableStageError(Exception): pass", "arguments = { 'global': program_arguments['global'], 'byStage': program_arguments['byStage'].get(stage, {}) } return arguments @trace(parameters=[]) def", "class UnsatisfiableStageError(Exception): pass class ResourceNotSuppliedError(Exception): pass def get_stage_program_arguments(stage: str, program_arguments: Dict[str, Any]): arguments", "if not suppliers: raise UnsatisfiableStageError(f\"stage '{stage_name}' cannot be satisfied because no stage supplies", "validator(stage: str, subtree: Dict[str, List[str]]): stage_program_arguments = get_stage_program_arguments(stage, program_arguments) return stages[stage].predicate(file_system, stage_program_arguments, configuration)", "Dict[str, List[str]]): stage_program_arguments = get_stage_program_arguments(stage, program_arguments) return stages[stage].predicate(file_system, stage_program_arguments, configuration) trees = multiple_instance_depth_first_traversal(target_stage,", "visitor, validator, on_cycle) if trees: stage_subtree = trees[0] stage_order = root_last_traversal(target_stage, lambda n:", "praline.client.project.pipeline.stage_resources import StageResources from praline.client.project.pipeline.stages.stage import Stage from praline.client.repository.remote_proxy import RemoteProxy from praline.common.algorithm.graph.instance_traversal", "file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any], remote_proxy: RemoteProxy) -> None: resources", "{', '.join(suppliers)}\") elif suppliers[0] not in required_stages: required_stages.append(suppliers[0]) required_stages_set.append(required_stages) return required_stages_set def validator(stage:", "stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any], remote_proxy: RemoteProxy)", "stage.output] if not suppliers: raise UnsatisfiableStageError(f\"stage '{stage_name}' cannot be satisfied because no stage", "satisfied because no stage supplies resource '{requirement}'\") elif len(suppliers) > 1: raise MultipleSuppliersError(f\"resource", "import Stage from praline.client.repository.remote_proxy import RemoteProxy from praline.common.algorithm.graph.instance_traversal import multiple_instance_depth_first_traversal from praline.common.algorithm.graph.simple_traversal import", "activation, {resource : resources[resource] for resource in stage.requirements[activation]}, stage.output) stage_program_arguments = get_stage_program_arguments(stage_name, program_arguments)", "required_stages_set = [] for requirements in requirements_set: required_stages = [] for requirement in", "= [] for requirement in requirements: suppliers = [stage.name for stage in stages.values()", "because no stage supplies resource '{requirement}'\") elif len(suppliers) > 1: raise MultipleSuppliersError(f\"resource '{requirement}'", "'target', 'cache.pickle') for activation, stage_name in pipeline: stage = stages[stage_name] stage_resources = StageResources(stage_name,", "to satisfy stage '{target_stage}'\") @trace def invoke_stage(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem,", "= stages[stage_name].requirements required_stages_set = [] for requirements in requirements_set: required_stages = [] for", "def visitor(stage_name: str): requirements_set = stages[stage_name].requirements required_stages_set = [] for requirements in requirements_set:", "[(stage_subtree[stage][0], stage) for stage in stage_order] return pipeline raise UnsatisfiableStageError(f\"could not create a", "stage_cache, stage_program_arguments, configuration, remote_proxy) else: stage.invoker(file_system, stage_resources, None, stage_program_arguments, configuration, remote_proxy) for resource", "stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any]) -> List[str]:", "CyclicStagesError(Exception): pass class UnsatisfiableStageError(Exception): pass class ResourceNotSuppliedError(Exception): pass def get_stage_program_arguments(stage: str, program_arguments: Dict[str,", "praline.client.repository.remote_proxy import RemoteProxy from praline.common.algorithm.graph.instance_traversal import multiple_instance_depth_first_traversal from praline.common.algorithm.graph.simple_traversal import root_last_traversal from praline.common.file_system", "stage_order = root_last_traversal(target_stage, lambda n: stage_subtree[n][1]) pipeline = [(stage_subtree[stage][0], stage) for stage in", "'{requirement}' is supplied by multiple stages: {', '.join(suppliers)}\") elif suppliers[0] not in required_stages:", "RemoteProxy) -> None: resources = {} pipeline = create_pipeline(target_stage, stages, file_system, program_arguments, configuration)", "str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any], remote_proxy:", "dependencies for stages {cycle}\") def visitor(stage_name: str): requirements_set = stages[stage_name].requirements required_stages_set = []", "stages[stage].predicate(file_system, stage_program_arguments, configuration) trees = multiple_instance_depth_first_traversal(target_stage, visitor, validator, on_cycle) if trees: stage_subtree =", "FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any]) -> List[str]: def on_cycle(cycle: List[str]): raise", "'{target_stage}'\") @trace def invoke_stage(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any],", "= get_stage_program_arguments(stage_name, program_arguments) if stage.cacheable: with Cache(file_system, cache_path) as cache: cache[stage_name] = stage_cache", "join from praline.common.tracing import trace from typing import Any, Dict, List class MultipleSuppliersError(Exception):", "for stages {cycle}\") def visitor(stage_name: str): requirements_set = stages[stage_name].requirements required_stages_set = [] for", "resource '{requirement}'\") elif len(suppliers) > 1: raise MultipleSuppliersError(f\"resource '{requirement}' is supplied by multiple", "Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any], remote_proxy: RemoteProxy) -> None:", "Any], configuration: Dict[str, Any], remote_proxy: RemoteProxy) -> None: resources = {} pipeline =", "program_arguments, configuration) project_directory = file_system.get_working_directory() cache_path = join(project_directory, 'target', 'cache.pickle') for activation, stage_name", "Any]): arguments = { 'global': program_arguments['global'], 'byStage': program_arguments['byStage'].get(stage, {}) } return arguments @trace(parameters=[])", "None, stage_program_arguments, configuration, remote_proxy) for resource in stage.output: if resource not in stage_resources:", "program_arguments) return stages[stage].predicate(file_system, stage_program_arguments, configuration) trees = multiple_instance_depth_first_traversal(target_stage, visitor, validator, on_cycle) if trees:", "typing import Any, Dict, List class MultipleSuppliersError(Exception): pass class CyclicStagesError(Exception): pass class UnsatisfiableStageError(Exception):", "return stages[stage].predicate(file_system, stage_program_arguments, configuration) trees = multiple_instance_depth_first_traversal(target_stage, visitor, validator, on_cycle) if trees: stage_subtree", "= trees[0] stage_order = root_last_traversal(target_stage, lambda n: stage_subtree[n][1]) pipeline = [(stage_subtree[stage][0], stage) for", "import StageResources from praline.client.project.pipeline.stages.stage import Stage from praline.client.repository.remote_proxy import RemoteProxy from praline.common.algorithm.graph.instance_traversal import", "not create a pipeline to satisfy stage '{target_stage}'\") @trace def invoke_stage(target_stage: str, stages:", "def invoke_stage(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str,", "file_system.get_working_directory() cache_path = join(project_directory, 'target', 'cache.pickle') for activation, stage_name in pipeline: stage =", "activation, stage_name in pipeline: stage = stages[stage_name] stage_resources = StageResources(stage_name, activation, {resource :", "elif len(suppliers) > 1: raise MultipleSuppliersError(f\"resource '{requirement}' is supplied by multiple stages: {',", "pipeline: stage = stages[stage_name] stage_resources = StageResources(stage_name, activation, {resource : resources[resource] for resource", "stage_resources = StageResources(stage_name, activation, {resource : resources[resource] for resource in stage.requirements[activation]}, stage.output) stage_program_arguments", "stage in stage_order] return pipeline raise UnsatisfiableStageError(f\"could not create a pipeline to satisfy", "program_arguments) if stage.cacheable: with Cache(file_system, cache_path) as cache: cache[stage_name] = stage_cache = cache.get(stage_name,", "return pipeline raise UnsatisfiableStageError(f\"could not create a pipeline to satisfy stage '{target_stage}'\") @trace", "Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any], remote_proxy: RemoteProxy) ->", "stage) for stage in stage_order] return pipeline raise UnsatisfiableStageError(f\"could not create a pipeline", "Dict[str, Any]) -> List[str]: def on_cycle(cycle: List[str]): raise CyclicStagesError(f\"cyclic dependencies for stages {cycle}\")", "praline.client.project.pipeline.cache import Cache from praline.client.project.pipeline.stage_resources import StageResources from praline.client.project.pipeline.stages.stage import Stage from praline.client.repository.remote_proxy", "import RemoteProxy from praline.common.algorithm.graph.instance_traversal import multiple_instance_depth_first_traversal from praline.common.algorithm.graph.simple_traversal import root_last_traversal from praline.common.file_system import", "def validator(stage: str, subtree: Dict[str, List[str]]): stage_program_arguments = get_stage_program_arguments(stage, program_arguments) return stages[stage].predicate(file_system, stage_program_arguments,", "@trace def invoke_stage(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration:", "from praline.common.file_system import FileSystem, join from praline.common.tracing import trace from typing import Any,", "= file_system.get_working_directory() cache_path = join(project_directory, 'target', 'cache.pickle') for activation, stage_name in pipeline: stage", "stage.invoker(file_system, stage_resources, None, stage_program_arguments, configuration, remote_proxy) for resource in stage.output: if resource not", "stage_subtree = trees[0] stage_order = root_last_traversal(target_stage, lambda n: stage_subtree[n][1]) pipeline = [(stage_subtree[stage][0], stage)", "remote_proxy) for resource in stage.output: if resource not in stage_resources: raise ResourceNotSuppliedError(f\"stage '{stage_name}'", "stage.output: if resource not in stage_resources: raise ResourceNotSuppliedError(f\"stage '{stage_name}' didn't supply resource '{resource}'\")", "from praline.common.algorithm.graph.instance_traversal import multiple_instance_depth_first_traversal from praline.common.algorithm.graph.simple_traversal import root_last_traversal from praline.common.file_system import FileSystem, join", "required_stages = [] for requirement in requirements: suppliers = [stage.name for stage in", "in requirements_set: required_stages = [] for requirement in requirements: suppliers = [stage.name for", "import Cache from praline.client.project.pipeline.stage_resources import StageResources from praline.client.project.pipeline.stages.stage import Stage from praline.client.repository.remote_proxy import", "UnsatisfiableStageError(f\"could not create a pipeline to satisfy stage '{target_stage}'\") @trace def invoke_stage(target_stage: str,", "project_directory = file_system.get_working_directory() cache_path = join(project_directory, 'target', 'cache.pickle') for activation, stage_name in pipeline:", "join(project_directory, 'target', 'cache.pickle') for activation, stage_name in pipeline: stage = stages[stage_name] stage_resources =", "stage_program_arguments, configuration, remote_proxy) else: stage.invoker(file_system, stage_resources, None, stage_program_arguments, configuration, remote_proxy) for resource in", "configuration, remote_proxy) else: stage.invoker(file_system, stage_resources, None, stage_program_arguments, configuration, remote_proxy) for resource in stage.output:", "List[str]: def on_cycle(cycle: List[str]): raise CyclicStagesError(f\"cyclic dependencies for stages {cycle}\") def visitor(stage_name: str):", "in stages.values() if requirement in stage.output] if not suppliers: raise UnsatisfiableStageError(f\"stage '{stage_name}' cannot", "cache_path = join(project_directory, 'target', 'cache.pickle') for activation, stage_name in pipeline: stage = stages[stage_name]", "return arguments @trace(parameters=[]) def create_pipeline(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str,", "not suppliers: raise UnsatisfiableStageError(f\"stage '{stage_name}' cannot be satisfied because no stage supplies resource", "requirement in stage.output] if not suppliers: raise UnsatisfiableStageError(f\"stage '{stage_name}' cannot be satisfied because", "create_pipeline(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any])", "suppliers = [stage.name for stage in stages.values() if requirement in stage.output] if not", "Any, Dict, List class MultipleSuppliersError(Exception): pass class CyclicStagesError(Exception): pass class UnsatisfiableStageError(Exception): pass class", "stage_resources, stage_cache, stage_program_arguments, configuration, remote_proxy) else: stage.invoker(file_system, stage_resources, None, stage_program_arguments, configuration, remote_proxy) for", "pass def get_stage_program_arguments(stage: str, program_arguments: Dict[str, Any]): arguments = { 'global': program_arguments['global'], 'byStage':", "supplied by multiple stages: {', '.join(suppliers)}\") elif suppliers[0] not in required_stages: required_stages.append(suppliers[0]) required_stages_set.append(required_stages)", "from praline.client.repository.remote_proxy import RemoteProxy from praline.common.algorithm.graph.instance_traversal import multiple_instance_depth_first_traversal from praline.common.algorithm.graph.simple_traversal import root_last_traversal from", "import FileSystem, join from praline.common.tracing import trace from typing import Any, Dict, List", "for requirements in requirements_set: required_stages = [] for requirement in requirements: suppliers =", "= {} pipeline = create_pipeline(target_stage, stages, file_system, program_arguments, configuration) project_directory = file_system.get_working_directory() cache_path", "praline.common.tracing import trace from typing import Any, Dict, List class MultipleSuppliersError(Exception): pass class", "{}) stage.invoker(file_system, stage_resources, stage_cache, stage_program_arguments, configuration, remote_proxy) else: stage.invoker(file_system, stage_resources, None, stage_program_arguments, configuration,", "for resource in stage.requirements[activation]}, stage.output) stage_program_arguments = get_stage_program_arguments(stage_name, program_arguments) if stage.cacheable: with Cache(file_system,", "subtree: Dict[str, List[str]]): stage_program_arguments = get_stage_program_arguments(stage, program_arguments) return stages[stage].predicate(file_system, stage_program_arguments, configuration) trees =", "FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any], remote_proxy: RemoteProxy) -> None: resources =", "for activation, stage_name in pipeline: stage = stages[stage_name] stage_resources = StageResources(stage_name, activation, {resource", "{resource : resources[resource] for resource in stage.requirements[activation]}, stage.output) stage_program_arguments = get_stage_program_arguments(stage_name, program_arguments) if", "cache: cache[stage_name] = stage_cache = cache.get(stage_name, {}) stage.invoker(file_system, stage_resources, stage_cache, stage_program_arguments, configuration, remote_proxy)", ": resources[resource] for resource in stage.requirements[activation]}, stage.output) stage_program_arguments = get_stage_program_arguments(stage_name, program_arguments) if stage.cacheable:", "resources[resource] for resource in stage.requirements[activation]}, stage.output) stage_program_arguments = get_stage_program_arguments(stage_name, program_arguments) if stage.cacheable: with", "len(suppliers) > 1: raise MultipleSuppliersError(f\"resource '{requirement}' is supplied by multiple stages: {', '.join(suppliers)}\")", "get_stage_program_arguments(stage, program_arguments) return stages[stage].predicate(file_system, stage_program_arguments, configuration) trees = multiple_instance_depth_first_traversal(target_stage, visitor, validator, on_cycle) if", "invoke_stage(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any],", "requirements in requirements_set: required_stages = [] for requirement in requirements: suppliers = [stage.name", "suppliers: raise UnsatisfiableStageError(f\"stage '{stage_name}' cannot be satisfied because no stage supplies resource '{requirement}'\")", "UnsatisfiableStageError(f\"stage '{stage_name}' cannot be satisfied because no stage supplies resource '{requirement}'\") elif len(suppliers)", "Cache(file_system, cache_path) as cache: cache[stage_name] = stage_cache = cache.get(stage_name, {}) stage.invoker(file_system, stage_resources, stage_cache,", "Dict, List class MultipleSuppliersError(Exception): pass class CyclicStagesError(Exception): pass class UnsatisfiableStageError(Exception): pass class ResourceNotSuppliedError(Exception):", "program_arguments['byStage'].get(stage, {}) } return arguments @trace(parameters=[]) def create_pipeline(target_stage: str, stages: Dict[str, Stage], file_system:", "List class MultipleSuppliersError(Exception): pass class CyclicStagesError(Exception): pass class UnsatisfiableStageError(Exception): pass class ResourceNotSuppliedError(Exception): pass", "as cache: cache[stage_name] = stage_cache = cache.get(stage_name, {}) stage.invoker(file_system, stage_resources, stage_cache, stage_program_arguments, configuration,", "create a pipeline to satisfy stage '{target_stage}'\") @trace def invoke_stage(target_stage: str, stages: Dict[str,", "requirements: suppliers = [stage.name for stage in stages.values() if requirement in stage.output] if", "StageResources from praline.client.project.pipeline.stages.stage import Stage from praline.client.repository.remote_proxy import RemoteProxy from praline.common.algorithm.graph.instance_traversal import multiple_instance_depth_first_traversal", "@trace(parameters=[]) def create_pipeline(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration:", "'{requirement}'\") elif len(suppliers) > 1: raise MultipleSuppliersError(f\"resource '{requirement}' is supplied by multiple stages:", "file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any]) -> List[str]: def on_cycle(cycle: List[str]):", "multiple_instance_depth_first_traversal(target_stage, visitor, validator, on_cycle) if trees: stage_subtree = trees[0] stage_order = root_last_traversal(target_stage, lambda", "import trace from typing import Any, Dict, List class MultipleSuppliersError(Exception): pass class CyclicStagesError(Exception):", "stage_program_arguments, configuration, remote_proxy) for resource in stage.output: if resource not in stage_resources: raise", "Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any]) -> List[str]: def", "class ResourceNotSuppliedError(Exception): pass def get_stage_program_arguments(stage: str, program_arguments: Dict[str, Any]): arguments = { 'global':", "'cache.pickle') for activation, stage_name in pipeline: stage = stages[stage_name] stage_resources = StageResources(stage_name, activation,", "program_arguments: Dict[str, Any]): arguments = { 'global': program_arguments['global'], 'byStage': program_arguments['byStage'].get(stage, {}) } return", "stages: {', '.join(suppliers)}\") elif suppliers[0] not in required_stages: required_stages.append(suppliers[0]) required_stages_set.append(required_stages) return required_stages_set def", "{cycle}\") def visitor(stage_name: str): requirements_set = stages[stage_name].requirements required_stages_set = [] for requirements in", "1: raise MultipleSuppliersError(f\"resource '{requirement}' is supplied by multiple stages: {', '.join(suppliers)}\") elif suppliers[0]", "supplies resource '{requirement}'\") elif len(suppliers) > 1: raise MultipleSuppliersError(f\"resource '{requirement}' is supplied by", "stage_program_arguments = get_stage_program_arguments(stage, program_arguments) return stages[stage].predicate(file_system, stage_program_arguments, configuration) trees = multiple_instance_depth_first_traversal(target_stage, visitor, validator,", "Any], remote_proxy: RemoteProxy) -> None: resources = {} pipeline = create_pipeline(target_stage, stages, file_system,", "trees[0] stage_order = root_last_traversal(target_stage, lambda n: stage_subtree[n][1]) pipeline = [(stage_subtree[stage][0], stage) for stage", "arguments @trace(parameters=[]) def create_pipeline(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any],", "praline.common.algorithm.graph.simple_traversal import root_last_traversal from praline.common.file_system import FileSystem, join from praline.common.tracing import trace from", "stages[stage_name].requirements required_stages_set = [] for requirements in requirements_set: required_stages = [] for requirement", "str, subtree: Dict[str, List[str]]): stage_program_arguments = get_stage_program_arguments(stage, program_arguments) return stages[stage].predicate(file_system, stage_program_arguments, configuration) trees", "from praline.common.algorithm.graph.simple_traversal import root_last_traversal from praline.common.file_system import FileSystem, join from praline.common.tracing import trace", "from typing import Any, Dict, List class MultipleSuppliersError(Exception): pass class CyclicStagesError(Exception): pass class", "program_arguments: Dict[str, Any], configuration: Dict[str, Any]) -> List[str]: def on_cycle(cycle: List[str]): raise CyclicStagesError(f\"cyclic", "configuration: Dict[str, Any]) -> List[str]: def on_cycle(cycle: List[str]): raise CyclicStagesError(f\"cyclic dependencies for stages", "raise MultipleSuppliersError(f\"resource '{requirement}' is supplied by multiple stages: {', '.join(suppliers)}\") elif suppliers[0] not", "required_stages_set def validator(stage: str, subtree: Dict[str, List[str]]): stage_program_arguments = get_stage_program_arguments(stage, program_arguments) return stages[stage].predicate(file_system,", "def create_pipeline(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str,", "pipeline raise UnsatisfiableStageError(f\"could not create a pipeline to satisfy stage '{target_stage}'\") @trace def", "[] for requirement in requirements: suppliers = [stage.name for stage in stages.values() if", "stages.values() if requirement in stage.output] if not suppliers: raise UnsatisfiableStageError(f\"stage '{stage_name}' cannot be", "be satisfied because no stage supplies resource '{requirement}'\") elif len(suppliers) > 1: raise", "get_stage_program_arguments(stage_name, program_arguments) if stage.cacheable: with Cache(file_system, cache_path) as cache: cache[stage_name] = stage_cache =", "[stage.name for stage in stages.values() if requirement in stage.output] if not suppliers: raise", "program_arguments: Dict[str, Any], configuration: Dict[str, Any], remote_proxy: RemoteProxy) -> None: resources = {}", "not in required_stages: required_stages.append(suppliers[0]) required_stages_set.append(required_stages) return required_stages_set def validator(stage: str, subtree: Dict[str, List[str]]):", "required_stages.append(suppliers[0]) required_stages_set.append(required_stages) return required_stages_set def validator(stage: str, subtree: Dict[str, List[str]]): stage_program_arguments = get_stage_program_arguments(stage,", "cache_path) as cache: cache[stage_name] = stage_cache = cache.get(stage_name, {}) stage.invoker(file_system, stage_resources, stage_cache, stage_program_arguments,", "= get_stage_program_arguments(stage, program_arguments) return stages[stage].predicate(file_system, stage_program_arguments, configuration) trees = multiple_instance_depth_first_traversal(target_stage, visitor, validator, on_cycle)", "remote_proxy: RemoteProxy) -> None: resources = {} pipeline = create_pipeline(target_stage, stages, file_system, program_arguments,", "remote_proxy) else: stage.invoker(file_system, stage_resources, None, stage_program_arguments, configuration, remote_proxy) for resource in stage.output: if", "lambda n: stage_subtree[n][1]) pipeline = [(stage_subtree[stage][0], stage) for stage in stage_order] return pipeline", "= join(project_directory, 'target', 'cache.pickle') for activation, stage_name in pipeline: stage = stages[stage_name] stage_resources", "Stage from praline.client.repository.remote_proxy import RemoteProxy from praline.common.algorithm.graph.instance_traversal import multiple_instance_depth_first_traversal from praline.common.algorithm.graph.simple_traversal import root_last_traversal", "= [] for requirements in requirements_set: required_stages = [] for requirement in requirements:", "praline.client.project.pipeline.stages.stage import Stage from praline.client.repository.remote_proxy import RemoteProxy from praline.common.algorithm.graph.instance_traversal import multiple_instance_depth_first_traversal from praline.common.algorithm.graph.simple_traversal", "in requirements: suppliers = [stage.name for stage in stages.values() if requirement in stage.output]", "if requirement in stage.output] if not suppliers: raise UnsatisfiableStageError(f\"stage '{stage_name}' cannot be satisfied", "for stage in stage_order] return pipeline raise UnsatisfiableStageError(f\"could not create a pipeline to", "pass class CyclicStagesError(Exception): pass class UnsatisfiableStageError(Exception): pass class ResourceNotSuppliedError(Exception): pass def get_stage_program_arguments(stage: str,", "'.join(suppliers)}\") elif suppliers[0] not in required_stages: required_stages.append(suppliers[0]) required_stages_set.append(required_stages) return required_stages_set def validator(stage: str,", "stage_name in pipeline: stage = stages[stage_name] stage_resources = StageResources(stage_name, activation, {resource : resources[resource]", "trees = multiple_instance_depth_first_traversal(target_stage, visitor, validator, on_cycle) if trees: stage_subtree = trees[0] stage_order =", "None: resources = {} pipeline = create_pipeline(target_stage, stages, file_system, program_arguments, configuration) project_directory =", "class MultipleSuppliersError(Exception): pass class CyclicStagesError(Exception): pass class UnsatisfiableStageError(Exception): pass class ResourceNotSuppliedError(Exception): pass def", "UnsatisfiableStageError(Exception): pass class ResourceNotSuppliedError(Exception): pass def get_stage_program_arguments(stage: str, program_arguments: Dict[str, Any]): arguments =", "praline.common.file_system import FileSystem, join from praline.common.tracing import trace from typing import Any, Dict,", "= [(stage_subtree[stage][0], stage) for stage in stage_order] return pipeline raise UnsatisfiableStageError(f\"could not create", "pipeline to satisfy stage '{target_stage}'\") @trace def invoke_stage(target_stage: str, stages: Dict[str, Stage], file_system:", "stage.cacheable: with Cache(file_system, cache_path) as cache: cache[stage_name] = stage_cache = cache.get(stage_name, {}) stage.invoker(file_system,", "no stage supplies resource '{requirement}'\") elif len(suppliers) > 1: raise MultipleSuppliersError(f\"resource '{requirement}' is", "n: stage_subtree[n][1]) pipeline = [(stage_subtree[stage][0], stage) for stage in stage_order] return pipeline raise", "a pipeline to satisfy stage '{target_stage}'\") @trace def invoke_stage(target_stage: str, stages: Dict[str, Stage],", "configuration: Dict[str, Any], remote_proxy: RemoteProxy) -> None: resources = {} pipeline = create_pipeline(target_stage,", "class CyclicStagesError(Exception): pass class UnsatisfiableStageError(Exception): pass class ResourceNotSuppliedError(Exception): pass def get_stage_program_arguments(stage: str, program_arguments:", "= create_pipeline(target_stage, stages, file_system, program_arguments, configuration) project_directory = file_system.get_working_directory() cache_path = join(project_directory, 'target',", "stages, file_system, program_arguments, configuration) project_directory = file_system.get_working_directory() cache_path = join(project_directory, 'target', 'cache.pickle') for", "stage_resources, None, stage_program_arguments, configuration, remote_proxy) for resource in stage.output: if resource not in", "pipeline = create_pipeline(target_stage, stages, file_system, program_arguments, configuration) project_directory = file_system.get_working_directory() cache_path = join(project_directory,", "= stages[stage_name] stage_resources = StageResources(stage_name, activation, {resource : resources[resource] for resource in stage.requirements[activation]},", "elif suppliers[0] not in required_stages: required_stages.append(suppliers[0]) required_stages_set.append(required_stages) return required_stages_set def validator(stage: str, subtree:", "raise UnsatisfiableStageError(f\"could not create a pipeline to satisfy stage '{target_stage}'\") @trace def invoke_stage(target_stage:", "validator, on_cycle) if trees: stage_subtree = trees[0] stage_order = root_last_traversal(target_stage, lambda n: stage_subtree[n][1])", "Dict[str, Any]): arguments = { 'global': program_arguments['global'], 'byStage': program_arguments['byStage'].get(stage, {}) } return arguments", "file_system, program_arguments, configuration) project_directory = file_system.get_working_directory() cache_path = join(project_directory, 'target', 'cache.pickle') for activation,", "= cache.get(stage_name, {}) stage.invoker(file_system, stage_resources, stage_cache, stage_program_arguments, configuration, remote_proxy) else: stage.invoker(file_system, stage_resources, None,", "def get_stage_program_arguments(stage: str, program_arguments: Dict[str, Any]): arguments = { 'global': program_arguments['global'], 'byStage': program_arguments['byStage'].get(stage,", "get_stage_program_arguments(stage: str, program_arguments: Dict[str, Any]): arguments = { 'global': program_arguments['global'], 'byStage': program_arguments['byStage'].get(stage, {})", "if trees: stage_subtree = trees[0] stage_order = root_last_traversal(target_stage, lambda n: stage_subtree[n][1]) pipeline =", "-> List[str]: def on_cycle(cycle: List[str]): raise CyclicStagesError(f\"cyclic dependencies for stages {cycle}\") def visitor(stage_name:", "> 1: raise MultipleSuppliersError(f\"resource '{requirement}' is supplied by multiple stages: {', '.join(suppliers)}\") elif", "configuration) project_directory = file_system.get_working_directory() cache_path = join(project_directory, 'target', 'cache.pickle') for activation, stage_name in", "from praline.common.tracing import trace from typing import Any, Dict, List class MultipleSuppliersError(Exception): pass", "cache[stage_name] = stage_cache = cache.get(stage_name, {}) stage.invoker(file_system, stage_resources, stage_cache, stage_program_arguments, configuration, remote_proxy) else:", "root_last_traversal(target_stage, lambda n: stage_subtree[n][1]) pipeline = [(stage_subtree[stage][0], stage) for stage in stage_order] return", "List[str]]): stage_program_arguments = get_stage_program_arguments(stage, program_arguments) return stages[stage].predicate(file_system, stage_program_arguments, configuration) trees = multiple_instance_depth_first_traversal(target_stage, visitor,", "raise UnsatisfiableStageError(f\"stage '{stage_name}' cannot be satisfied because no stage supplies resource '{requirement}'\") elif", "FileSystem, join from praline.common.tracing import trace from typing import Any, Dict, List class", "configuration) trees = multiple_instance_depth_first_traversal(target_stage, visitor, validator, on_cycle) if trees: stage_subtree = trees[0] stage_order", "stage = stages[stage_name] stage_resources = StageResources(stage_name, activation, {resource : resources[resource] for resource in", "return required_stages_set def validator(stage: str, subtree: Dict[str, List[str]]): stage_program_arguments = get_stage_program_arguments(stage, program_arguments) return", "stage supplies resource '{requirement}'\") elif len(suppliers) > 1: raise MultipleSuppliersError(f\"resource '{requirement}' is supplied", "if resource not in stage_resources: raise ResourceNotSuppliedError(f\"stage '{stage_name}' didn't supply resource '{resource}'\") resources.update(stage_resources.resources)", "= root_last_traversal(target_stage, lambda n: stage_subtree[n][1]) pipeline = [(stage_subtree[stage][0], stage) for stage in stage_order]", "raise CyclicStagesError(f\"cyclic dependencies for stages {cycle}\") def visitor(stage_name: str): requirements_set = stages[stage_name].requirements required_stages_set", "pipeline = [(stage_subtree[stage][0], stage) for stage in stage_order] return pipeline raise UnsatisfiableStageError(f\"could not", "stage_cache = cache.get(stage_name, {}) stage.invoker(file_system, stage_resources, stage_cache, stage_program_arguments, configuration, remote_proxy) else: stage.invoker(file_system, stage_resources,", "praline.common.algorithm.graph.instance_traversal import multiple_instance_depth_first_traversal from praline.common.algorithm.graph.simple_traversal import root_last_traversal from praline.common.file_system import FileSystem, join from", "in stage.requirements[activation]}, stage.output) stage_program_arguments = get_stage_program_arguments(stage_name, program_arguments) if stage.cacheable: with Cache(file_system, cache_path) as", "'byStage': program_arguments['byStage'].get(stage, {}) } return arguments @trace(parameters=[]) def create_pipeline(target_stage: str, stages: Dict[str, Stage],", "in stage_order] return pipeline raise UnsatisfiableStageError(f\"could not create a pipeline to satisfy stage", "stage_subtree[n][1]) pipeline = [(stage_subtree[stage][0], stage) for stage in stage_order] return pipeline raise UnsatisfiableStageError(f\"could", "} return arguments @trace(parameters=[]) def create_pipeline(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments:", "MultipleSuppliersError(Exception): pass class CyclicStagesError(Exception): pass class UnsatisfiableStageError(Exception): pass class ResourceNotSuppliedError(Exception): pass def get_stage_program_arguments(stage:", "requirements_set = stages[stage_name].requirements required_stages_set = [] for requirements in requirements_set: required_stages = []", "from praline.client.project.pipeline.stage_resources import StageResources from praline.client.project.pipeline.stages.stage import Stage from praline.client.repository.remote_proxy import RemoteProxy from", "RemoteProxy from praline.common.algorithm.graph.instance_traversal import multiple_instance_depth_first_traversal from praline.common.algorithm.graph.simple_traversal import root_last_traversal from praline.common.file_system import FileSystem,", "= [stage.name for stage in stages.values() if requirement in stage.output] if not suppliers:", "suppliers[0] not in required_stages: required_stages.append(suppliers[0]) required_stages_set.append(required_stages) return required_stages_set def validator(stage: str, subtree: Dict[str,", "Any], configuration: Dict[str, Any]) -> List[str]: def on_cycle(cycle: List[str]): raise CyclicStagesError(f\"cyclic dependencies for", "root_last_traversal from praline.common.file_system import FileSystem, join from praline.common.tracing import trace from typing import", "= stage_cache = cache.get(stage_name, {}) stage.invoker(file_system, stage_resources, stage_cache, stage_program_arguments, configuration, remote_proxy) else: stage.invoker(file_system,", "program_arguments['global'], 'byStage': program_arguments['byStage'].get(stage, {}) } return arguments @trace(parameters=[]) def create_pipeline(target_stage: str, stages: Dict[str,", "StageResources(stage_name, activation, {resource : resources[resource] for resource in stage.requirements[activation]}, stage.output) stage_program_arguments = get_stage_program_arguments(stage_name,", "{ 'global': program_arguments['global'], 'byStage': program_arguments['byStage'].get(stage, {}) } return arguments @trace(parameters=[]) def create_pipeline(target_stage: str,", "on_cycle) if trees: stage_subtree = trees[0] stage_order = root_last_traversal(target_stage, lambda n: stage_subtree[n][1]) pipeline", "stage '{target_stage}'\") @trace def invoke_stage(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str,", "stage.output) stage_program_arguments = get_stage_program_arguments(stage_name, program_arguments) if stage.cacheable: with Cache(file_system, cache_path) as cache: cache[stage_name]", "in stage.output: if resource not in stage_resources: raise ResourceNotSuppliedError(f\"stage '{stage_name}' didn't supply resource", "in stage.output] if not suppliers: raise UnsatisfiableStageError(f\"stage '{stage_name}' cannot be satisfied because no", "import multiple_instance_depth_first_traversal from praline.common.algorithm.graph.simple_traversal import root_last_traversal from praline.common.file_system import FileSystem, join from praline.common.tracing", "visitor(stage_name: str): requirements_set = stages[stage_name].requirements required_stages_set = [] for requirements in requirements_set: required_stages", "for requirement in requirements: suppliers = [stage.name for stage in stages.values() if requirement", "multiple stages: {', '.join(suppliers)}\") elif suppliers[0] not in required_stages: required_stages.append(suppliers[0]) required_stages_set.append(required_stages) return required_stages_set", "-> None: resources = {} pipeline = create_pipeline(target_stage, stages, file_system, program_arguments, configuration) project_directory", "resource in stage.requirements[activation]}, stage.output) stage_program_arguments = get_stage_program_arguments(stage_name, program_arguments) if stage.cacheable: with Cache(file_system, cache_path)", "Dict[str, Any], configuration: Dict[str, Any]) -> List[str]: def on_cycle(cycle: List[str]): raise CyclicStagesError(f\"cyclic dependencies", "else: stage.invoker(file_system, stage_resources, None, stage_program_arguments, configuration, remote_proxy) for resource in stage.output: if resource", "for resource in stage.output: if resource not in stage_resources: raise ResourceNotSuppliedError(f\"stage '{stage_name}' didn't", "multiple_instance_depth_first_traversal from praline.common.algorithm.graph.simple_traversal import root_last_traversal from praline.common.file_system import FileSystem, join from praline.common.tracing import", "stage_order] return pipeline raise UnsatisfiableStageError(f\"could not create a pipeline to satisfy stage '{target_stage}'\")", "pass class UnsatisfiableStageError(Exception): pass class ResourceNotSuppliedError(Exception): pass def get_stage_program_arguments(stage: str, program_arguments: Dict[str, Any]):", "stage.requirements[activation]}, stage.output) stage_program_arguments = get_stage_program_arguments(stage_name, program_arguments) if stage.cacheable: with Cache(file_system, cache_path) as cache:", "is supplied by multiple stages: {', '.join(suppliers)}\") elif suppliers[0] not in required_stages: required_stages.append(suppliers[0])", "with Cache(file_system, cache_path) as cache: cache[stage_name] = stage_cache = cache.get(stage_name, {}) stage.invoker(file_system, stage_resources,", "resources = {} pipeline = create_pipeline(target_stage, stages, file_system, program_arguments, configuration) project_directory = file_system.get_working_directory()", "stage in stages.values() if requirement in stage.output] if not suppliers: raise UnsatisfiableStageError(f\"stage '{stage_name}'", "Dict[str, Any], remote_proxy: RemoteProxy) -> None: resources = {} pipeline = create_pipeline(target_stage, stages,", "by multiple stages: {', '.join(suppliers)}\") elif suppliers[0] not in required_stages: required_stages.append(suppliers[0]) required_stages_set.append(required_stages) return", "def on_cycle(cycle: List[str]): raise CyclicStagesError(f\"cyclic dependencies for stages {cycle}\") def visitor(stage_name: str): requirements_set", "[] for requirements in requirements_set: required_stages = [] for requirement in requirements: suppliers", "trace from typing import Any, Dict, List class MultipleSuppliersError(Exception): pass class CyclicStagesError(Exception): pass", "on_cycle(cycle: List[str]): raise CyclicStagesError(f\"cyclic dependencies for stages {cycle}\") def visitor(stage_name: str): requirements_set =", "MultipleSuppliersError(f\"resource '{requirement}' is supplied by multiple stages: {', '.join(suppliers)}\") elif suppliers[0] not in", "'global': program_arguments['global'], 'byStage': program_arguments['byStage'].get(stage, {}) } return arguments @trace(parameters=[]) def create_pipeline(target_stage: str, stages:", "= StageResources(stage_name, activation, {resource : resources[resource] for resource in stage.requirements[activation]}, stage.output) stage_program_arguments =", "str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any]) ->", "str, program_arguments: Dict[str, Any]): arguments = { 'global': program_arguments['global'], 'byStage': program_arguments['byStage'].get(stage, {}) }", "stage_program_arguments, configuration) trees = multiple_instance_depth_first_traversal(target_stage, visitor, validator, on_cycle) if trees: stage_subtree = trees[0]", "Stage], file_system: FileSystem, program_arguments: Dict[str, Any], configuration: Dict[str, Any]) -> List[str]: def on_cycle(cycle:", "Cache from praline.client.project.pipeline.stage_resources import StageResources from praline.client.project.pipeline.stages.stage import Stage from praline.client.repository.remote_proxy import RemoteProxy", "if stage.cacheable: with Cache(file_system, cache_path) as cache: cache[stage_name] = stage_cache = cache.get(stage_name, {})", "requirements_set: required_stages = [] for requirement in requirements: suppliers = [stage.name for stage", "Dict[str, Any], configuration: Dict[str, Any], remote_proxy: RemoteProxy) -> None: resources = {} pipeline", "in pipeline: stage = stages[stage_name] stage_resources = StageResources(stage_name, activation, {resource : resources[resource] for", "from praline.client.project.pipeline.stages.stage import Stage from praline.client.repository.remote_proxy import RemoteProxy from praline.common.algorithm.graph.instance_traversal import multiple_instance_depth_first_traversal from", "= { 'global': program_arguments['global'], 'byStage': program_arguments['byStage'].get(stage, {}) } return arguments @trace(parameters=[]) def create_pipeline(target_stage:", "required_stages_set.append(required_stages) return required_stages_set def validator(stage: str, subtree: Dict[str, List[str]]): stage_program_arguments = get_stage_program_arguments(stage, program_arguments)", "str): requirements_set = stages[stage_name].requirements required_stages_set = [] for requirements in requirements_set: required_stages =", "cache.get(stage_name, {}) stage.invoker(file_system, stage_resources, stage_cache, stage_program_arguments, configuration, remote_proxy) else: stage.invoker(file_system, stage_resources, None, stage_program_arguments,", "configuration, remote_proxy) for resource in stage.output: if resource not in stage_resources: raise ResourceNotSuppliedError(f\"stage", "List[str]): raise CyclicStagesError(f\"cyclic dependencies for stages {cycle}\") def visitor(stage_name: str): requirements_set = stages[stage_name].requirements", "resource in stage.output: if resource not in stage_resources: raise ResourceNotSuppliedError(f\"stage '{stage_name}' didn't supply", "from praline.client.project.pipeline.cache import Cache from praline.client.project.pipeline.stage_resources import StageResources from praline.client.project.pipeline.stages.stage import Stage from", "stages {cycle}\") def visitor(stage_name: str): requirements_set = stages[stage_name].requirements required_stages_set = [] for requirements", "{}) } return arguments @trace(parameters=[]) def create_pipeline(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem,", "pass class ResourceNotSuppliedError(Exception): pass def get_stage_program_arguments(stage: str, program_arguments: Dict[str, Any]): arguments = {", "CyclicStagesError(f\"cyclic dependencies for stages {cycle}\") def visitor(stage_name: str): requirements_set = stages[stage_name].requirements required_stages_set =", "= multiple_instance_depth_first_traversal(target_stage, visitor, validator, on_cycle) if trees: stage_subtree = trees[0] stage_order = root_last_traversal(target_stage,", "satisfy stage '{target_stage}'\") @trace def invoke_stage(target_stage: str, stages: Dict[str, Stage], file_system: FileSystem, program_arguments:", "{} pipeline = create_pipeline(target_stage, stages, file_system, program_arguments, configuration) project_directory = file_system.get_working_directory() cache_path =", "Any]) -> List[str]: def on_cycle(cycle: List[str]): raise CyclicStagesError(f\"cyclic dependencies for stages {cycle}\") def", "stages[stage_name] stage_resources = StageResources(stage_name, activation, {resource : resources[resource] for resource in stage.requirements[activation]}, stage.output)", "cannot be satisfied because no stage supplies resource '{requirement}'\") elif len(suppliers) > 1:", "import root_last_traversal from praline.common.file_system import FileSystem, join from praline.common.tracing import trace from typing", "for stage in stages.values() if requirement in stage.output] if not suppliers: raise UnsatisfiableStageError(f\"stage", "required_stages: required_stages.append(suppliers[0]) required_stages_set.append(required_stages) return required_stages_set def validator(stage: str, subtree: Dict[str, List[str]]): stage_program_arguments =", "create_pipeline(target_stage, stages, file_system, program_arguments, configuration) project_directory = file_system.get_working_directory() cache_path = join(project_directory, 'target', 'cache.pickle')" ]
[ "/ t, '\\t-\\t\\t' ) error = np.array([cnn_diff, lin_diff, cos_diff, ner_diff, bsp_diff]) n_error =", "Sinc:', n_error[2].mean()) print('Nearest:', n_error[3].mean()) print('BSpline', n_error[4].mean()) print() print('NRMSE STD:') print('PixelMiner:', n_error[0].std()) print('Linear:', n_error[1].std())", "import matplotlib.pyplot as plt from functools import partial from get_features_functions import get_features, final,", "t, (lin_diff < ner_diff).sum() / t, (lin_diff < bsp_diff).sum() / t, (lin_diff <", "arr1.min(), arr1.max()) print(files[8]) arr2 = np.load(os.path.join(path, files[8])) features = get_features(arr1, arr2) features =", "feature) for feature in features] features = [feature.split('_') for feature in features] features", "< bsp_diff).sum() / t, (lin_diff < cnn_diff).sum() / t) print((cos_diff < lin_diff).sum() /", "lung_itp['Nearest'] = get_all_features(path, 'Nearest', 'lung') lung_results = get_results(lung_tru, lung_cnn, lung_itp) display_results(lung_results, features) cnn_diff", "for i in range(lung_tru.shape[1])]) cccs = np.vstack((ccc_cnn, ccc_bsp, ccc_nn, ccc_ws, ccc_lin)) print('Mean CCC')", "<filename>results texture.py import os import re import numpy as np import matplotlib.pyplot as", "import train_test_split from sklearn.feature_extraction import image import matplotlib.pyplot as plt from functools import", "= [key for key in features.keys() if key.find('diagnostic') < 0] features = [feature[9:]", "wilcoxon, ttest_rel, ttest_ind, mannwhitneyu, ranksums from scipy.stats import f, shapiro, bartlett, f_oneway, kruskal", "import listfiles, unnormalize, get_all_features from get_features_functions import rmses, wilcoxons, ttests, para_non_para from get_features_functions", "'\\n' 'Linear', (cccs[4] > thresh).sum() / 51) print('Wilcoxons:') print('Win Sinc:', wilcoxon(n_error[:, 0, :].flatten(),", "lung_cnn = get_all_features(path, 'PixelCNN', 'lung') lung_itp['Linear'] = get_all_features(path, 'Linear', 'lung') lung_itp['BSpline'] = get_all_features(path,", "files[14])) arr1 = unnormalize(arr1) print(arr1.dtype, arr1.min(), arr1.max()) print(files[8]) arr2 = np.load(os.path.join(path, files[8])) features", "- np.min(a))/np.ptp(a) return b def rse(x, y): diff = x - y sqrd", "n_error[3].std()) print('BSpline', n_error[4].std()) ccc_cnn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_cnn[:, i]) for i in range(lung_tru.shape[1])])", "3, :].flatten())) shape = n_error.shape[0] * n_error.shape[2] print('Binomial test:') print('Win Sinc:', binom_test((n_error[:, 0,", "'lung') lung_itp['Nearest'] = get_all_features(path, 'Nearest', 'lung') lung_results = get_results(lung_tru, lung_cnn, lung_itp) display_results(lung_results, features)", "ttest_ind, mannwhitneyu, ranksums from scipy.stats import f, shapiro, bartlett, f_oneway, kruskal from statsmodels.stats.weightstats", "t = cnn_diff.shape[0] * cnn_diff.shape[1] print() print('Percent Greater:') print('Linear\\t\\t\\t Win Sinc\\t\\t\\t Nearest\\t\\t\\t BSpline\\t\\t\\t", "from sklearn.feature_extraction import image import matplotlib.pyplot as plt from functools import partial from", "= get_all_features(path, 'Linear', 'lung') lung_itp['BSpline'] = get_all_features(path, 'BSpline', 'lung') lung_itp['Cosine'] = get_all_features(path, 'Cosine',", "= get_all_features(path, 'BSpline', 'lung') lung_itp['Cosine'] = get_all_features(path, 'Cosine', 'lung') lung_itp['Nearest'] = get_all_features(path, 'Nearest',", ":] < n_error[:, 1, :]).sum() , shape)) print('BSpline:', binom_test((n_error[:, 0, :] < n_error[:,", "= {} lung_tru = get_all_features(path, 'tru_one', 'lung') lung_cnn = get_all_features(path, 'PixelCNN', 'lung') lung_itp['Linear']", "range(lung_tru.shape[1])]) ccc_ws = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Cosine'][:, i]) for i in range(lung_tru.shape[1])]) ccc_nn =", "lung_itp['Linear'][:, i]) for i in range(lung_tru.shape[1])]) ccc_bsp = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['BSpline'][:, i]) for", "t, (cnn_diff < cos_diff).sum() / t, (cnn_diff < ner_diff).sum() / t, (cnn_diff <", "< lin_diff).sum() / t, (bsp_diff < cos_diff).sum() / t, (bsp_diff < ner_diff).sum() /", "* n_error.shape[2] print('Binomial test:') print('Win Sinc:', binom_test((n_error[:, 0, :] < n_error[:, 2, :]).sum()", "diff ** 2 sqrt = np.sqrt(sqrd) return sqrt n = 0 path =", "= get_all_features(path, 'PixelCNN', 'lung') lung_itp['Linear'] = get_all_features(path, 'Linear', 'lung') lung_itp['BSpline'] = get_all_features(path, 'BSpline',", "= os.listdir(path) print(files[14]) arr1 = np.load(os.path.join(path, files[14])) arr1 = unnormalize(arr1) print(arr1.dtype, arr1.min(), arr1.max())", "getTestCase import SimpleITK as sitk import pandas as pd from random import randint", "lung_itp) display_results(lung_results, features) cnn_diff = rse(lung_tru, lung_cnn) lin_diff = rse(lung_tru, lung_itp['Linear']) cos_diff =", "lin_diff).sum() / t, (ner_diff < cos_diff).sum() / t, '\\t-\\t\\t\\t' , (ner_diff < bsp_diff).sum()", "in features] features = [re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", feature) for feature in features] features", "concordance_correlation_coefficient from scipy.stats import wilcoxon, ttest_rel, ttest_ind, mannwhitneyu, ranksums from scipy.stats import f,", "from statsmodels.stats.weightstats import ztest from scipy.stats import binom_test from radiomics import featureextractor, getTestCase", "in range(lung_tru.shape[1])]) ccc_ws = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Cosine'][:, i]) for i in range(lung_tru.shape[1])]) ccc_nn", "t, '\\t-\\t\\t\\t' , (bsp_diff < cnn_diff).sum() / t) print((cnn_diff < lin_diff).sum() / t,", "from radiomics import featureextractor, getTestCase import SimpleITK as sitk import pandas as pd", "= diff ** 2 sqrt = np.sqrt(sqrd) return sqrt n = 0 path", ", (ner_diff < bsp_diff).sum() / t, (ner_diff < cnn_diff).sum() / t) print((bsp_diff <", "t, (ner_diff < cnn_diff).sum() / t) print((bsp_diff < lin_diff).sum() / t, (bsp_diff <", "-= 1024 #img *= 255 img = img.astype(np.uint8) print(img.min(), img.max()) return img def", "import pandas as pd from random import randint from tqdm import tqdm from", "(bsp_diff < ner_diff).sum() / t, '\\t-\\t\\t\\t' , (bsp_diff < cnn_diff).sum() / t) print((cnn_diff", "< bsp_diff).sum() / t, '\\t-\\t\\t' ) error = np.array([cnn_diff, lin_diff, cos_diff, ner_diff, bsp_diff])", "PIL import Image, ImageOps, ImageEnhance #from sklearn.model_selection import train_test_split from sklearn.feature_extraction import image", "rse(lung_tru, lung_itp['BSpline']) t = cnn_diff.shape[0] * cnn_diff.shape[1] print() print('Percent Greater:') print('Linear\\t\\t\\t Win Sinc\\t\\t\\t", ":].flatten(), n_error[:, 2, :].flatten())) print('Linear:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 1, :].flatten())) print('BSpline:', wilcoxon(n_error[:,", "cos_diff).sum() / t, (lin_diff < ner_diff).sum() / t, (lin_diff < bsp_diff).sum() / t,", "shape)) print('Linear:', binom_test((n_error[:, 0, :] < n_error[:, 1, :]).sum() , shape)) print('BSpline:', binom_test((n_error[:,", "import randint from tqdm import tqdm from PIL import Image, ImageOps, ImageEnhance #from", "ner_diff).sum() / t, (lin_diff < bsp_diff).sum() / t, (lin_diff < cnn_diff).sum() / t)", "np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Linear'][:, i]) for i in range(lung_tru.shape[1])]) ccc_bsp = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['BSpline'][:,", "import rmses, wilcoxons, ttests, para_non_para from get_features_functions import get_all_features, get_rmses, normalize def unnormalize(img):", "/ 51, '\\n' 'Nearest', (cccs[2] > thresh).sum() / 51, '\\n' 'Linear', (cccs[4] >", "i in range(lung_tru.shape[1])]) ccc_lin = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Linear'][:, i]) for i in range(lung_tru.shape[1])])", "i in range(lung_tru.shape[1])]) cccs = np.vstack((ccc_cnn, ccc_bsp, ccc_nn, ccc_ws, ccc_lin)) print('Mean CCC') print('PixelMiner',", "features = np.array(features) lung_itp = {} lung_tru = get_all_features(path, 'tru_one', 'lung') lung_cnn =", "'\\n' 'Linear', cccs[4].mean()) print() print('Reproducibility') thresh = .85 print('PixelMiner', (cccs[0] > thresh).sum() /", "'Linear', (cccs[4] > thresh).sum() / 51) print('Wilcoxons:') print('Win Sinc:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:,", "= np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Linear'][:, i]) for i in range(lung_tru.shape[1])]) ccc_bsp = np.array([concordance_correlation_coefficient(lung_tru[:, i],", "thresh).sum() / 51, '\\n' 'Linear', (cccs[4] > thresh).sum() / 51) print('Wilcoxons:') print('Win Sinc:',", "cnn_diff = rse(lung_tru, lung_cnn) lin_diff = rse(lung_tru, lung_itp['Linear']) cos_diff = rse(lung_tru, lung_itp['Cosine']) ner_diff", "t) print((cos_diff < lin_diff).sum() / t, '\\t-\\t\\t\\t' , (cos_diff < ner_diff).sum() / t,", "(cos_diff < ner_diff).sum() / t, (cos_diff < bsp_diff).sum() / t, (cos_diff < cnn_diff).sum()", "cnn_diff).sum() / t) print((bsp_diff < lin_diff).sum() / t, (bsp_diff < cos_diff).sum() / t,", "thresh = .85 print('PixelMiner', (cccs[0] > thresh).sum() / 51, '\\n' 'Win Sinc', (cccs[3]", "as np import matplotlib.pyplot as plt from ccc import concordance_correlation_coefficient from scipy.stats import", "Greater:') print('Linear\\t\\t\\t Win Sinc\\t\\t\\t Nearest\\t\\t\\t BSpline\\t\\t\\t PixelMiner') print('\\t-\\t\\t\\t' , (lin_diff < cos_diff).sum() /", "np.sqrt(sqrd) return sqrt n = 0 path = r'H:\\Data\\W' files = os.listdir(path) print(files[14])", "0, :] < n_error[:, 2, :]).sum() , shape)) print('Linear:', binom_test((n_error[:, 0, :] <", "print('BSpline:', binom_test((n_error[:, 0, :] < n_error[:, 4, :]).sum() , shape)) print('Nearest:', binom_test((n_error[:, 0,", "statsmodels.stats.weightstats import ztest from scipy.stats import binom_test from radiomics import featureextractor, getTestCase import", "import wilcoxon, ttest_rel, ttest_ind, mannwhitneyu, ranksums from scipy.stats import f, shapiro, bartlett, f_oneway,", "print() print('Percent Greater:') print('Linear\\t\\t\\t Win Sinc\\t\\t\\t Nearest\\t\\t\\t BSpline\\t\\t\\t PixelMiner') print('\\t-\\t\\t\\t' , (lin_diff <", "2, :]).sum() , shape)) print('Linear:', binom_test((n_error[:, 0, :] < n_error[:, 1, :]).sum() ,", "#img -= 1024 #img *= 255 img = img.astype(np.uint8) print(img.min(), img.max()) return img", "cos_diff = rse(lung_tru, lung_itp['Cosine']) ner_diff = rse(lung_tru, lung_itp['Nearest']) bsp_diff = rse(lung_tru, lung_itp['BSpline']) t", "lung_itp['Cosine']) ner_diff = rse(lung_tru, lung_itp['Nearest']) bsp_diff = rse(lung_tru, lung_itp['BSpline']) t = cnn_diff.shape[0] *", "import get_all_features, get_rmses, normalize def unnormalize(img): img += 1 img /= 2 img", "2, :].flatten())) print('Linear:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 1, :].flatten())) print('BSpline:', wilcoxon(n_error[:, 0, :].flatten(),", "(cnn_diff < cos_diff).sum() / t, (cnn_diff < ner_diff).sum() / t, (cnn_diff < bsp_diff).sum()", "print(files[14]) arr1 = np.load(os.path.join(path, files[14])) arr1 = unnormalize(arr1) print(arr1.dtype, arr1.min(), arr1.max()) print(files[8]) arr2", "n_error[4].std()) ccc_cnn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_cnn[:, i]) for i in range(lung_tru.shape[1])]) ccc_lin =", "from PIL import Image, ImageOps, ImageEnhance #from sklearn.model_selection import train_test_split from sklearn.feature_extraction import", "print('NRMSE Mean:') print('PixelMiner:', n_error[0].mean()) print('Linear:', n_error[1].mean()) print('Win Sinc:', n_error[2].mean()) print('Nearest:', n_error[3].mean()) print('BSpline', n_error[4].mean())", "n_error[:, 1, :].flatten())) print('BSpline:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 4, :].flatten())) print('Nearest:', wilcoxon(n_error[:, 0,", "print((cnn_diff < lin_diff).sum() / t, (cnn_diff < cos_diff).sum() / t, (cnn_diff < ner_diff).sum()", "sitk import pandas as pd from random import randint from tqdm import tqdm", "(ner_diff < cnn_diff).sum() / t) print((bsp_diff < lin_diff).sum() / t, (bsp_diff < cos_diff).sum()", "from ccc import concordance_correlation_coefficient from scipy.stats import wilcoxon, ttest_rel, ttest_ind, mannwhitneyu, ranksums from", "n = 0 path = r'H:\\Data\\W' files = os.listdir(path) print(files[14]) arr1 = np.load(os.path.join(path,", "ttest_rel, ttest_ind, mannwhitneyu, ranksums from scipy.stats import f, shapiro, bartlett, f_oneway, kruskal from", "/ t, (ner_diff < cnn_diff).sum() / t) print((bsp_diff < lin_diff).sum() / t, (bsp_diff", "/ t) print((bsp_diff < lin_diff).sum() / t, (bsp_diff < cos_diff).sum() / t, (bsp_diff", "feature in features] features = [re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", feature) for feature in features]", "r\"\\1 \\2\", feature) for feature in features] features = [feature.split('_') for feature in", "as pd from random import randint from tqdm import tqdm from PIL import", "3071) #img -= 1024 #img *= 255 img = img.astype(np.uint8) print(img.min(), img.max()) return", "ner_diff, bsp_diff]) n_error = np.zeros((5, 50, 51)) for i in range(error.shape[-1]): n_error[:, :,", ":].flatten())) print('Nearest:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 3, :].flatten())) shape = n_error.shape[0] * n_error.shape[2]", "print('Linear:', n_error[1].std()) print('Win Sinc:', n_error[2].std()) print('Nearest:', n_error[3].std()) print('BSpline', n_error[4].std()) ccc_cnn = np.array([concordance_correlation_coefficient(lung_tru[:, i],", ":].flatten())) print('BSpline:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 4, :].flatten())) print('Nearest:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:,", "/ t, (lin_diff < bsp_diff).sum() / t, (lin_diff < cnn_diff).sum() / t) print((cos_diff", "< n_error[:, 1, :]).sum() , shape)) print('BSpline:', binom_test((n_error[:, 0, :] < n_error[:, 4,", "scipy.stats import binom_test from radiomics import featureextractor, getTestCase import SimpleITK as sitk import", "from scipy.stats import binom_test from radiomics import featureextractor, getTestCase import SimpleITK as sitk", "lung_itp = {} lung_tru = get_all_features(path, 'tru_one', 'lung') lung_cnn = get_all_features(path, 'PixelCNN', 'lung')", "feature in features] features = np.array(features) lung_itp = {} lung_tru = get_all_features(path, 'tru_one',", "range(lung_tru.shape[1])]) ccc_lin = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Linear'][:, i]) for i in range(lung_tru.shape[1])]) ccc_bsp =", "t, '\\t-\\t\\t\\t' , (ner_diff < bsp_diff).sum() / t, (ner_diff < cnn_diff).sum() / t)", "print('Binomial test:') print('Win Sinc:', binom_test((n_error[:, 0, :] < n_error[:, 2, :]).sum() , shape))", "img def normalize(a): b = (a - np.min(a))/np.ptp(a) return b def rse(x, y):", "def normalize(a): b = (a - np.min(a))/np.ptp(a) return b def rse(x, y): diff", "lung_cnn, lung_itp) display_results(lung_results, features) cnn_diff = rse(lung_tru, lung_cnn) lin_diff = rse(lung_tru, lung_itp['Linear']) cos_diff", "diff = x - y sqrd = diff ** 2 sqrt = np.sqrt(sqrd)", "arr2 = np.load(os.path.join(path, files[8])) features = get_features(arr1, arr2) features = [key for key", "rse(x, y): diff = x - y sqrd = diff ** 2 sqrt", "bsp_diff = rse(lung_tru, lung_itp['BSpline']) t = cnn_diff.shape[0] * cnn_diff.shape[1] print() print('Percent Greater:') print('Linear\\t\\t\\t", "Sinc:', binom_test((n_error[:, 0, :] < n_error[:, 2, :]).sum() , shape)) print('Linear:', binom_test((n_error[:, 0,", "+ 3071) #img -= 1024 #img *= 255 img = img.astype(np.uint8) print(img.min(), img.max())", "print('PixelMiner:', n_error[0].mean()) print('Linear:', n_error[1].mean()) print('Win Sinc:', n_error[2].mean()) print('Nearest:', n_error[3].mean()) print('BSpline', n_error[4].mean()) print() print('NRMSE", "= get_features(arr1, arr2) features = [key for key in features.keys() if key.find('diagnostic') <", "ner_diff).sum() / t, '\\t-\\t\\t\\t' , (bsp_diff < cnn_diff).sum() / t) print((cnn_diff < lin_diff).sum()", "cos_diff, ner_diff, bsp_diff]) n_error = np.zeros((5, 50, 51)) for i in range(error.shape[-1]): n_error[:,", "for i in range(lung_tru.shape[1])]) ccc_lin = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Linear'][:, i]) for i in", "np.array([cnn_diff, lin_diff, cos_diff, ner_diff, bsp_diff]) n_error = np.zeros((5, 50, 51)) for i in", "get_features_functions import get_all_features, get_rmses, normalize def unnormalize(img): img += 1 img /= 2", "cnn_diff).sum() / t) print((ner_diff < lin_diff).sum() / t, (ner_diff < cos_diff).sum() / t,", "51) print('Wilcoxons:') print('Win Sinc:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 2, :].flatten())) print('Linear:', wilcoxon(n_error[:, 0,", "= np.sqrt(sqrd) return sqrt n = 0 path = r'H:\\Data\\W' files = os.listdir(path)", "print('Linear:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 1, :].flatten())) print('BSpline:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 4,", "lin_diff).sum() / t, (bsp_diff < cos_diff).sum() / t, (bsp_diff < ner_diff).sum() / t,", "print('Nearest:', n_error[3].mean()) print('BSpline', n_error[4].mean()) print() print('NRMSE STD:') print('PixelMiner:', n_error[0].std()) print('Linear:', n_error[1].std()) print('Win Sinc:',", "* cnn_diff.shape[1] print() print('Percent Greater:') print('Linear\\t\\t\\t Win Sinc\\t\\t\\t Nearest\\t\\t\\t BSpline\\t\\t\\t PixelMiner') print('\\t-\\t\\t\\t' ,", "import binom_test from radiomics import featureextractor, getTestCase import SimpleITK as sitk import pandas", "for i in range(lung_tru.shape[1])]) ccc_bsp = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['BSpline'][:, i]) for i in", "print('BSpline', n_error[4].mean()) print() print('NRMSE STD:') print('PixelMiner:', n_error[0].std()) print('Linear:', n_error[1].std()) print('Win Sinc:', n_error[2].std()) print('Nearest:',", "get_all_features(path, 'PixelCNN', 'lung') lung_itp['Linear'] = get_all_features(path, 'Linear', 'lung') lung_itp['BSpline'] = get_all_features(path, 'BSpline', 'lung')", "= rse(lung_tru, lung_itp['Linear']) cos_diff = rse(lung_tru, lung_itp['Cosine']) ner_diff = rse(lung_tru, lung_itp['Nearest']) bsp_diff =", "(a - np.min(a))/np.ptp(a) return b def rse(x, y): diff = x - y", "arr1 = unnormalize(arr1) print(arr1.dtype, arr1.min(), arr1.max()) print(files[8]) arr2 = np.load(os.path.join(path, files[8])) features =", "n_error[2].std()) print('Nearest:', n_error[3].std()) print('BSpline', n_error[4].std()) ccc_cnn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_cnn[:, i]) for i", "[feature[9:] for feature in features] features = [re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", feature) for feature", "'BSpline', (cccs[1] > thresh).sum() / 51, '\\n' 'Nearest', (cccs[2] > thresh).sum() / 51,", "lung_cnn) lin_diff = rse(lung_tru, lung_itp['Linear']) cos_diff = rse(lung_tru, lung_itp['Cosine']) ner_diff = rse(lung_tru, lung_itp['Nearest'])", "0, :].flatten(), n_error[:, 2, :].flatten())) print('Linear:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 1, :].flatten())) print('BSpline:',", ".85 print('PixelMiner', (cccs[0] > thresh).sum() / 51, '\\n' 'Win Sinc', (cccs[3] > thresh).sum()", "< bsp_diff).sum() / t, (ner_diff < cnn_diff).sum() / t) print((bsp_diff < lin_diff).sum() /", "features] features = [re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", feature) for feature in features] features =", "= np.array([cnn_diff, lin_diff, cos_diff, ner_diff, bsp_diff]) n_error = np.zeros((5, 50, 51)) for i", "n_error[:, 4, :].flatten())) print('Nearest:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 3, :].flatten())) shape = n_error.shape[0]", "features) cnn_diff = rse(lung_tru, lung_cnn) lin_diff = rse(lung_tru, lung_itp['Linear']) cos_diff = rse(lung_tru, lung_itp['Cosine'])", "print('Win Sinc:', binom_test((n_error[:, 0, :] < n_error[:, 2, :]).sum() , shape)) print('Linear:', binom_test((n_error[:,", "lung_itp['Nearest']) bsp_diff = rse(lung_tru, lung_itp['BSpline']) t = cnn_diff.shape[0] * cnn_diff.shape[1] print() print('Percent Greater:')", "CCC') print('PixelMiner', cccs[0].mean(), '\\n' 'Win Sinc', cccs[3].mean(), '\\n' 'BSpline', cccs[1].mean(), '\\n' 'Nearest', cccs[2].mean(),", "scipy.stats import wilcoxon, ttest_rel, ttest_ind, mannwhitneyu, ranksums from scipy.stats import f, shapiro, bartlett,", "0, :] < n_error[:, 4, :]).sum() , shape)) print('Nearest:', binom_test((n_error[:, 0, :] <", "wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 2, :].flatten())) print('Linear:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 1, :].flatten()))", "np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Cosine'][:, i]) for i in range(lung_tru.shape[1])]) ccc_nn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Nearest'][:,", "image import matplotlib.pyplot as plt from functools import partial from get_features_functions import get_features,", "np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_cnn[:, i]) for i in range(lung_tru.shape[1])]) ccc_lin = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Linear'][:,", "shapiro, bartlett, f_oneway, kruskal from statsmodels.stats.weightstats import ztest from scipy.stats import binom_test from", "print() print('NRMSE STD:') print('PixelMiner:', n_error[0].std()) print('Linear:', n_error[1].std()) print('Win Sinc:', n_error[2].std()) print('Nearest:', n_error[3].std()) print('BSpline',", "from scipy.stats import f, shapiro, bartlett, f_oneway, kruskal from statsmodels.stats.weightstats import ztest from", "> thresh).sum() / 51) print('Wilcoxons:') print('Win Sinc:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 2, :].flatten()))", "import featureextractor, getTestCase import SimpleITK as sitk import pandas as pd from random", "*= (1024 + 3071) #img -= 1024 #img *= 255 img = img.astype(np.uint8)", "shape)) print('BSpline:', binom_test((n_error[:, 0, :] < n_error[:, 4, :]).sum() , shape)) print('Nearest:', binom_test((n_error[:,", "np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Nearest'][:, i]) for i in range(lung_tru.shape[1])]) cccs = np.vstack((ccc_cnn, ccc_bsp, ccc_nn,", "(cos_diff < cnn_diff).sum() / t) print((ner_diff < lin_diff).sum() / t, (ner_diff < cos_diff).sum()", "print() print('Reproducibility') thresh = .85 print('PixelMiner', (cccs[0] > thresh).sum() / 51, '\\n' 'Win", "< cnn_diff).sum() / t) print((cos_diff < lin_diff).sum() / t, '\\t-\\t\\t\\t' , (cos_diff <", "functools import partial from get_features_functions import get_features, final, get_results, display_results from get_features_functions import", "= (a - np.min(a))/np.ptp(a) return b def rse(x, y): diff = x -", "t, (ner_diff < cos_diff).sum() / t, '\\t-\\t\\t\\t' , (ner_diff < bsp_diff).sum() / t,", "print('Win Sinc:', n_error[2].std()) print('Nearest:', n_error[3].std()) print('BSpline', n_error[4].std()) ccc_cnn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_cnn[:, i])", "arr1.max()) print(files[8]) arr2 = np.load(os.path.join(path, files[8])) features = get_features(arr1, arr2) features = [key", "(1024 + 3071) #img -= 1024 #img *= 255 img = img.astype(np.uint8) print(img.min(),", "np.zeros((5, 50, 51)) for i in range(error.shape[-1]): n_error[:, :, i] = normalize(error[:, :,", "in features] features = np.array(features) lung_itp = {} lung_tru = get_all_features(path, 'tru_one', 'lung')", "'BSpline', cccs[1].mean(), '\\n' 'Nearest', cccs[2].mean(), '\\n' 'Linear', cccs[4].mean()) print() print('Reproducibility') thresh = .85", "(cccs[2] > thresh).sum() / 51, '\\n' 'Linear', (cccs[4] > thresh).sum() / 51) print('Wilcoxons:')", "import SimpleITK as sitk import pandas as pd from random import randint from", "i]) for i in range(lung_tru.shape[1])]) ccc_bsp = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['BSpline'][:, i]) for i", "kruskal from statsmodels.stats.weightstats import ztest from scipy.stats import binom_test from radiomics import featureextractor,", "pandas as pd from random import randint from tqdm import tqdm from PIL", "cnn_diff).sum() / t) print((cnn_diff < lin_diff).sum() / t, (cnn_diff < cos_diff).sum() / t,", "ImageOps, ImageEnhance #from sklearn.model_selection import train_test_split from sklearn.feature_extraction import image import matplotlib.pyplot as", "print('PixelMiner', cccs[0].mean(), '\\n' 'Win Sinc', cccs[3].mean(), '\\n' 'BSpline', cccs[1].mean(), '\\n' 'Nearest', cccs[2].mean(), '\\n'", "f_oneway, kruskal from statsmodels.stats.weightstats import ztest from scipy.stats import binom_test from radiomics import", "wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 4, :].flatten())) print('Nearest:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 3, :].flatten()))", "< ner_diff).sum() / t, (cnn_diff < bsp_diff).sum() / t, '\\t-\\t\\t' ) error =", "cccs[4].mean()) print() print('Reproducibility') thresh = .85 print('PixelMiner', (cccs[0] > thresh).sum() / 51, '\\n'", "import re import numpy as np import matplotlib.pyplot as plt from ccc import", "np.load(os.path.join(path, files[14])) arr1 = unnormalize(arr1) print(arr1.dtype, arr1.min(), arr1.max()) print(files[8]) arr2 = np.load(os.path.join(path, files[8]))", "/ t, (cos_diff < cnn_diff).sum() / t) print((ner_diff < lin_diff).sum() / t, (ner_diff", "(bsp_diff < cnn_diff).sum() / t) print((cnn_diff < lin_diff).sum() / t, (cnn_diff < cos_diff).sum()", "\\2\", feature) for feature in features] features = [feature.split('_') for feature in features]", "cccs[2].mean(), '\\n' 'Linear', cccs[4].mean()) print() print('Reproducibility') thresh = .85 print('PixelMiner', (cccs[0] > thresh).sum()", "= np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_cnn[:, i]) for i in range(lung_tru.shape[1])]) ccc_lin = np.array([concordance_correlation_coefficient(lung_tru[:, i],", "plt from functools import partial from get_features_functions import get_features, final, get_results, display_results from", "(bsp_diff < cos_diff).sum() / t, (bsp_diff < ner_diff).sum() / t, '\\t-\\t\\t\\t' , (bsp_diff", "lin_diff).sum() / t, (cnn_diff < cos_diff).sum() / t, (cnn_diff < ner_diff).sum() / t,", "(lin_diff < cnn_diff).sum() / t) print((cos_diff < lin_diff).sum() / t, '\\t-\\t\\t\\t' , (cos_diff", "ccc_lin = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Linear'][:, i]) for i in range(lung_tru.shape[1])]) ccc_bsp = np.array([concordance_correlation_coefficient(lung_tru[:,", "i in range(lung_tru.shape[1])]) ccc_bsp = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['BSpline'][:, i]) for i in range(lung_tru.shape[1])])", "= np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['BSpline'][:, i]) for i in range(lung_tru.shape[1])]) ccc_ws = np.array([concordance_correlation_coefficient(lung_tru[:, i],", "'Win Sinc', (cccs[3] > thresh).sum() / 51, '\\n' 'BSpline', (cccs[1] > thresh).sum() /", "n_error[0].mean()) print('Linear:', n_error[1].mean()) print('Win Sinc:', n_error[2].mean()) print('Nearest:', n_error[3].mean()) print('BSpline', n_error[4].mean()) print() print('NRMSE STD:')", "features] features = np.array(features) lung_itp = {} lung_tru = get_all_features(path, 'tru_one', 'lung') lung_cnn", "thresh).sum() / 51, '\\n' 'Nearest', (cccs[2] > thresh).sum() / 51, '\\n' 'Linear', (cccs[4]", "< ner_diff).sum() / t, '\\t-\\t\\t\\t' , (bsp_diff < cnn_diff).sum() / t) print((cnn_diff <", "n_error[2].mean()) print('Nearest:', n_error[3].mean()) print('BSpline', n_error[4].mean()) print() print('NRMSE STD:') print('PixelMiner:', n_error[0].std()) print('Linear:', n_error[1].std()) print('Win", "= n_error.shape[0] * n_error.shape[2] print('Binomial test:') print('Win Sinc:', binom_test((n_error[:, 0, :] < n_error[:,", "cos_diff).sum() / t, (bsp_diff < ner_diff).sum() / t, '\\t-\\t\\t\\t' , (bsp_diff < cnn_diff).sum()", "from get_features_functions import get_all_features, get_rmses, normalize def unnormalize(img): img += 1 img /=", "[key for key in features.keys() if key.find('diagnostic') < 0] features = [feature[9:] for", "print((cos_diff < lin_diff).sum() / t, '\\t-\\t\\t\\t' , (cos_diff < ner_diff).sum() / t, (cos_diff", "< cos_diff).sum() / t, (bsp_diff < ner_diff).sum() / t, '\\t-\\t\\t\\t' , (bsp_diff <", "+= 1 img /= 2 img *= (1024 + 3071) #img -= 1024", "ccc_nn, ccc_ws, ccc_lin)) print('Mean CCC') print('PixelMiner', cccs[0].mean(), '\\n' 'Win Sinc', cccs[3].mean(), '\\n' 'BSpline',", "lung_itp['BSpline'][:, i]) for i in range(lung_tru.shape[1])]) ccc_ws = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Cosine'][:, i]) for", "def unnormalize(img): img += 1 img /= 2 img *= (1024 + 3071)", "[feature.split('_') for feature in features] features = np.array(features) lung_itp = {} lung_tru =", "50, 51)) for i in range(error.shape[-1]): n_error[:, :, i] = normalize(error[:, :, i])", "1024 #img *= 255 img = img.astype(np.uint8) print(img.min(), img.max()) return img def normalize(a):", "shape = n_error.shape[0] * n_error.shape[2] print('Binomial test:') print('Win Sinc:', binom_test((n_error[:, 0, :] <", "'Linear', cccs[4].mean()) print() print('Reproducibility') thresh = .85 print('PixelMiner', (cccs[0] > thresh).sum() / 51,", "import ztest from scipy.stats import binom_test from radiomics import featureextractor, getTestCase import SimpleITK", "img = img.astype(np.uint8) print(img.min(), img.max()) return img def normalize(a): b = (a -", "/ t) print((ner_diff < lin_diff).sum() / t, (ner_diff < cos_diff).sum() / t, '\\t-\\t\\t\\t'", "/ t, (cnn_diff < bsp_diff).sum() / t, '\\t-\\t\\t' ) error = np.array([cnn_diff, lin_diff,", "< bsp_diff).sum() / t, (cos_diff < cnn_diff).sum() / t) print((ner_diff < lin_diff).sum() /", "import Image, ImageOps, ImageEnhance #from sklearn.model_selection import train_test_split from sklearn.feature_extraction import image import", "Sinc\\t\\t\\t Nearest\\t\\t\\t BSpline\\t\\t\\t PixelMiner') print('\\t-\\t\\t\\t' , (lin_diff < cos_diff).sum() / t, (lin_diff <", "(lin_diff < bsp_diff).sum() / t, (lin_diff < cnn_diff).sum() / t) print((cos_diff < lin_diff).sum()", "sklearn.feature_extraction import image import matplotlib.pyplot as plt from functools import partial from get_features_functions", "= np.array(features) lung_itp = {} lung_tru = get_all_features(path, 'tru_one', 'lung') lung_cnn = get_all_features(path,", "os.listdir(path) print(files[14]) arr1 = np.load(os.path.join(path, files[14])) arr1 = unnormalize(arr1) print(arr1.dtype, arr1.min(), arr1.max()) print(files[8])", "(lin_diff < ner_diff).sum() / t, (lin_diff < bsp_diff).sum() / t, (lin_diff < cnn_diff).sum()", "files = os.listdir(path) print(files[14]) arr1 = np.load(os.path.join(path, files[14])) arr1 = unnormalize(arr1) print(arr1.dtype, arr1.min(),", "lung_itp['Linear']) cos_diff = rse(lung_tru, lung_itp['Cosine']) ner_diff = rse(lung_tru, lung_itp['Nearest']) bsp_diff = rse(lung_tru, lung_itp['BSpline'])", "np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['BSpline'][:, i]) for i in range(lung_tru.shape[1])]) ccc_ws = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Cosine'][:,", "1, :]).sum() , shape)) print('BSpline:', binom_test((n_error[:, 0, :] < n_error[:, 4, :]).sum() ,", "from random import randint from tqdm import tqdm from PIL import Image, ImageOps,", "from functools import partial from get_features_functions import get_features, final, get_results, display_results from get_features_functions", "n_error[:, 2, :]).sum() , shape)) print('Linear:', binom_test((n_error[:, 0, :] < n_error[:, 1, :]).sum()", "partial from get_features_functions import get_features, final, get_results, display_results from get_features_functions import listfiles, unnormalize,", "*= 255 img = img.astype(np.uint8) print(img.min(), img.max()) return img def normalize(a): b =", "img.max()) return img def normalize(a): b = (a - np.min(a))/np.ptp(a) return b def", "'BSpline', 'lung') lung_itp['Cosine'] = get_all_features(path, 'Cosine', 'lung') lung_itp['Nearest'] = get_all_features(path, 'Nearest', 'lung') lung_results", ":]).sum() , shape)) print('Nearest:', binom_test((n_error[:, 0, :] < n_error[:, 3, :]).sum() , shape))", "in features] features = [feature.split('_') for feature in features] features = np.array(features) lung_itp", "< cnn_diff).sum() / t) print((ner_diff < lin_diff).sum() / t, (ner_diff < cos_diff).sum() /", "Image, ImageOps, ImageEnhance #from sklearn.model_selection import train_test_split from sklearn.feature_extraction import image import matplotlib.pyplot", "from get_features_functions import rmses, wilcoxons, ttests, para_non_para from get_features_functions import get_all_features, get_rmses, normalize", "#img *= 255 img = img.astype(np.uint8) print(img.min(), img.max()) return img def normalize(a): b", "ccc_nn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Nearest'][:, i]) for i in range(lung_tru.shape[1])]) cccs = np.vstack((ccc_cnn,", "print() print('NRMSE Mean:') print('PixelMiner:', n_error[0].mean()) print('Linear:', n_error[1].mean()) print('Win Sinc:', n_error[2].mean()) print('Nearest:', n_error[3].mean()) print('BSpline',", "ttests, para_non_para from get_features_functions import get_all_features, get_rmses, normalize def unnormalize(img): img += 1", "range(lung_tru.shape[1])]) cccs = np.vstack((ccc_cnn, ccc_bsp, ccc_nn, ccc_ws, ccc_lin)) print('Mean CCC') print('PixelMiner', cccs[0].mean(), '\\n'", "= r'H:\\Data\\W' files = os.listdir(path) print(files[14]) arr1 = np.load(os.path.join(path, files[14])) arr1 = unnormalize(arr1)", "import get_features, final, get_results, display_results from get_features_functions import listfiles, unnormalize, get_all_features from get_features_functions", "/ t, '\\t-\\t\\t\\t' , (cos_diff < ner_diff).sum() / t, (cos_diff < bsp_diff).sum() /", "cccs[3].mean(), '\\n' 'BSpline', cccs[1].mean(), '\\n' 'Nearest', cccs[2].mean(), '\\n' 'Linear', cccs[4].mean()) print() print('Reproducibility') thresh", "Sinc:', n_error[2].std()) print('Nearest:', n_error[3].std()) print('BSpline', n_error[4].std()) ccc_cnn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_cnn[:, i]) for", "51, '\\n' 'Win Sinc', (cccs[3] > thresh).sum() / 51, '\\n' 'BSpline', (cccs[1] >", "bsp_diff]) n_error = np.zeros((5, 50, 51)) for i in range(error.shape[-1]): n_error[:, :, i]", "lung_itp['BSpline']) t = cnn_diff.shape[0] * cnn_diff.shape[1] print() print('Percent Greater:') print('Linear\\t\\t\\t Win Sinc\\t\\t\\t Nearest\\t\\t\\t", "print('PixelMiner:', n_error[0].std()) print('Linear:', n_error[1].std()) print('Win Sinc:', n_error[2].std()) print('Nearest:', n_error[3].std()) print('BSpline', n_error[4].std()) ccc_cnn =", "img.astype(np.uint8) print(img.min(), img.max()) return img def normalize(a): b = (a - np.min(a))/np.ptp(a) return", "lung_results = get_results(lung_tru, lung_cnn, lung_itp) display_results(lung_results, features) cnn_diff = rse(lung_tru, lung_cnn) lin_diff =", "t, (cos_diff < cnn_diff).sum() / t) print((ner_diff < lin_diff).sum() / t, (ner_diff <", "t, '\\t-\\t\\t\\t' , (cos_diff < ner_diff).sum() / t, (cos_diff < bsp_diff).sum() / t,", "Sinc', cccs[3].mean(), '\\n' 'BSpline', cccs[1].mean(), '\\n' 'Nearest', cccs[2].mean(), '\\n' 'Linear', cccs[4].mean()) print() print('Reproducibility')", "radiomics import featureextractor, getTestCase import SimpleITK as sitk import pandas as pd from", "from scipy.stats import wilcoxon, ttest_rel, ttest_ind, mannwhitneyu, ranksums from scipy.stats import f, shapiro,", "0] features = [feature[9:] for feature in features] features = [re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\",", "normalize(error[:, :, i]) print() print('NRMSE Mean:') print('PixelMiner:', n_error[0].mean()) print('Linear:', n_error[1].mean()) print('Win Sinc:', n_error[2].mean())", "print(files[8]) arr2 = np.load(os.path.join(path, files[8])) features = get_features(arr1, arr2) features = [key for", "get_all_features(path, 'Linear', 'lung') lung_itp['BSpline'] = get_all_features(path, 'BSpline', 'lung') lung_itp['Cosine'] = get_all_features(path, 'Cosine', 'lung')", "features = [re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", feature) for feature in features] features = [feature.split('_')", "import tqdm from PIL import Image, ImageOps, ImageEnhance #from sklearn.model_selection import train_test_split from", "features = [feature[9:] for feature in features] features = [re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", feature)", "x - y sqrd = diff ** 2 sqrt = np.sqrt(sqrd) return sqrt", "/ t, (cnn_diff < cos_diff).sum() / t, (cnn_diff < ner_diff).sum() / t, (cnn_diff", "print('Win Sinc:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 2, :].flatten())) print('Linear:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:,", "import numpy as np import matplotlib.pyplot as plt from ccc import concordance_correlation_coefficient from", "for feature in features] features = [re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", feature) for feature in", "for feature in features] features = [feature.split('_') for feature in features] features =", "i], lung_cnn[:, i]) for i in range(lung_tru.shape[1])]) ccc_lin = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Linear'][:, i])", ", (cos_diff < ner_diff).sum() / t, (cos_diff < bsp_diff).sum() / t, (cos_diff <", "tqdm import tqdm from PIL import Image, ImageOps, ImageEnhance #from sklearn.model_selection import train_test_split", "tqdm from PIL import Image, ImageOps, ImageEnhance #from sklearn.model_selection import train_test_split from sklearn.feature_extraction", "2 img *= (1024 + 3071) #img -= 1024 #img *= 255 img", "texture.py import os import re import numpy as np import matplotlib.pyplot as plt", ":, i] = normalize(error[:, :, i]) print() print('NRMSE Mean:') print('PixelMiner:', n_error[0].mean()) print('Linear:', n_error[1].mean())", "t, (cnn_diff < ner_diff).sum() / t, (cnn_diff < bsp_diff).sum() / t, '\\t-\\t\\t' )", "i] = normalize(error[:, :, i]) print() print('NRMSE Mean:') print('PixelMiner:', n_error[0].mean()) print('Linear:', n_error[1].mean()) print('Win", "normalize def unnormalize(img): img += 1 img /= 2 img *= (1024 +", "print((ner_diff < lin_diff).sum() / t, (ner_diff < cos_diff).sum() / t, '\\t-\\t\\t\\t' , (ner_diff", "/ t, (bsp_diff < cos_diff).sum() / t, (bsp_diff < ner_diff).sum() / t, '\\t-\\t\\t\\t'", "in range(lung_tru.shape[1])]) ccc_nn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Nearest'][:, i]) for i in range(lung_tru.shape[1])]) cccs", "= img.astype(np.uint8) print(img.min(), img.max()) return img def normalize(a): b = (a - np.min(a))/np.ptp(a)", "/ t, (cos_diff < bsp_diff).sum() / t, (cos_diff < cnn_diff).sum() / t) print((ner_diff", "= rse(lung_tru, lung_itp['Nearest']) bsp_diff = rse(lung_tru, lung_itp['BSpline']) t = cnn_diff.shape[0] * cnn_diff.shape[1] print()", "from tqdm import tqdm from PIL import Image, ImageOps, ImageEnhance #from sklearn.model_selection import", "t, (cos_diff < bsp_diff).sum() / t, (cos_diff < cnn_diff).sum() / t) print((ner_diff <", "n_error[3].mean()) print('BSpline', n_error[4].mean()) print() print('NRMSE STD:') print('PixelMiner:', n_error[0].std()) print('Linear:', n_error[1].std()) print('Win Sinc:', n_error[2].std())", "return b def rse(x, y): diff = x - y sqrd = diff", "'Nearest', cccs[2].mean(), '\\n' 'Linear', cccs[4].mean()) print() print('Reproducibility') thresh = .85 print('PixelMiner', (cccs[0] >", "= get_all_features(path, 'Nearest', 'lung') lung_results = get_results(lung_tru, lung_cnn, lung_itp) display_results(lung_results, features) cnn_diff =", "t, (lin_diff < bsp_diff).sum() / t, (lin_diff < cnn_diff).sum() / t) print((cos_diff <", "binom_test from radiomics import featureextractor, getTestCase import SimpleITK as sitk import pandas as", "< lin_diff).sum() / t, (ner_diff < cos_diff).sum() / t, '\\t-\\t\\t\\t' , (ner_diff <", "= [feature[9:] for feature in features] features = [re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", feature) for", "files[8])) features = get_features(arr1, arr2) features = [key for key in features.keys() if", "get_features, final, get_results, display_results from get_features_functions import listfiles, unnormalize, get_all_features from get_features_functions import", "sqrd = diff ** 2 sqrt = np.sqrt(sqrd) return sqrt n = 0", "bsp_diff).sum() / t, (ner_diff < cnn_diff).sum() / t) print((bsp_diff < lin_diff).sum() / t,", "> thresh).sum() / 51, '\\n' 'BSpline', (cccs[1] > thresh).sum() / 51, '\\n' 'Nearest',", "binom_test((n_error[:, 0, :] < n_error[:, 1, :]).sum() , shape)) print('BSpline:', binom_test((n_error[:, 0, :]", "return sqrt n = 0 path = r'H:\\Data\\W' files = os.listdir(path) print(files[14]) arr1", "ccc_cnn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_cnn[:, i]) for i in range(lung_tru.shape[1])]) ccc_lin = np.array([concordance_correlation_coefficient(lung_tru[:,", "sqrt n = 0 path = r'H:\\Data\\W' files = os.listdir(path) print(files[14]) arr1 =", "get_results, display_results from get_features_functions import listfiles, unnormalize, get_all_features from get_features_functions import rmses, wilcoxons,", "ImageEnhance #from sklearn.model_selection import train_test_split from sklearn.feature_extraction import image import matplotlib.pyplot as plt", "y sqrd = diff ** 2 sqrt = np.sqrt(sqrd) return sqrt n =", ":].flatten(), n_error[:, 3, :].flatten())) shape = n_error.shape[0] * n_error.shape[2] print('Binomial test:') print('Win Sinc:',", "t, (bsp_diff < ner_diff).sum() / t, '\\t-\\t\\t\\t' , (bsp_diff < cnn_diff).sum() / t)", "= get_all_features(path, 'Cosine', 'lung') lung_itp['Nearest'] = get_all_features(path, 'Nearest', 'lung') lung_results = get_results(lung_tru, lung_cnn,", "get_all_features, get_rmses, normalize def unnormalize(img): img += 1 img /= 2 img *=", "i]) for i in range(lung_tru.shape[1])]) ccc_lin = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Linear'][:, i]) for i", "featureextractor, getTestCase import SimpleITK as sitk import pandas as pd from random import", "= unnormalize(arr1) print(arr1.dtype, arr1.min(), arr1.max()) print(files[8]) arr2 = np.load(os.path.join(path, files[8])) features = get_features(arr1,", "cnn_diff.shape[0] * cnn_diff.shape[1] print() print('Percent Greater:') print('Linear\\t\\t\\t Win Sinc\\t\\t\\t Nearest\\t\\t\\t BSpline\\t\\t\\t PixelMiner') print('\\t-\\t\\t\\t'", "ner_diff).sum() / t, (cnn_diff < bsp_diff).sum() / t, '\\t-\\t\\t' ) error = np.array([cnn_diff,", ":] < n_error[:, 4, :]).sum() , shape)) print('Nearest:', binom_test((n_error[:, 0, :] < n_error[:,", "0 path = r'H:\\Data\\W' files = os.listdir(path) print(files[14]) arr1 = np.load(os.path.join(path, files[14])) arr1", "import matplotlib.pyplot as plt from ccc import concordance_correlation_coefficient from scipy.stats import wilcoxon, ttest_rel,", "> thresh).sum() / 51, '\\n' 'Linear', (cccs[4] > thresh).sum() / 51) print('Wilcoxons:') print('Win", "= np.zeros((5, 50, 51)) for i in range(error.shape[-1]): n_error[:, :, i] = normalize(error[:,", "i]) for i in range(lung_tru.shape[1])]) ccc_nn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Nearest'][:, i]) for i", "error = np.array([cnn_diff, lin_diff, cos_diff, ner_diff, bsp_diff]) n_error = np.zeros((5, 50, 51)) for", "t) print((ner_diff < lin_diff).sum() / t, (ner_diff < cos_diff).sum() / t, '\\t-\\t\\t\\t' ,", "as plt from functools import partial from get_features_functions import get_features, final, get_results, display_results", "< 0] features = [feature[9:] for feature in features] features = [re.sub(r\"(\\w)([A-Z])\", r\"\\1", "= rse(lung_tru, lung_itp['Cosine']) ner_diff = rse(lung_tru, lung_itp['Nearest']) bsp_diff = rse(lung_tru, lung_itp['BSpline']) t =", "= normalize(error[:, :, i]) print() print('NRMSE Mean:') print('PixelMiner:', n_error[0].mean()) print('Linear:', n_error[1].mean()) print('Win Sinc:',", "n_error[:, :, i] = normalize(error[:, :, i]) print() print('NRMSE Mean:') print('PixelMiner:', n_error[0].mean()) print('Linear:',", "= get_all_features(path, 'tru_one', 'lung') lung_cnn = get_all_features(path, 'PixelCNN', 'lung') lung_itp['Linear'] = get_all_features(path, 'Linear',", "randint from tqdm import tqdm from PIL import Image, ImageOps, ImageEnhance #from sklearn.model_selection", "import image import matplotlib.pyplot as plt from functools import partial from get_features_functions import", "t) print((cnn_diff < lin_diff).sum() / t, (cnn_diff < cos_diff).sum() / t, (cnn_diff <", "(cccs[4] > thresh).sum() / 51) print('Wilcoxons:') print('Win Sinc:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 2,", "t) print((bsp_diff < lin_diff).sum() / t, (bsp_diff < cos_diff).sum() / t, (bsp_diff <", "< cos_diff).sum() / t, (cnn_diff < ner_diff).sum() / t, (cnn_diff < bsp_diff).sum() /", "2 sqrt = np.sqrt(sqrd) return sqrt n = 0 path = r'H:\\Data\\W' files", "import concordance_correlation_coefficient from scipy.stats import wilcoxon, ttest_rel, ttest_ind, mannwhitneyu, ranksums from scipy.stats import", "wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 1, :].flatten())) print('BSpline:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 4, :].flatten()))", "ccc_bsp, ccc_nn, ccc_ws, ccc_lin)) print('Mean CCC') print('PixelMiner', cccs[0].mean(), '\\n' 'Win Sinc', cccs[3].mean(), '\\n'", "/ t, '\\t-\\t\\t\\t' , (bsp_diff < cnn_diff).sum() / t) print((cnn_diff < lin_diff).sum() /", "re import numpy as np import matplotlib.pyplot as plt from ccc import concordance_correlation_coefficient", "'\\n' 'Win Sinc', (cccs[3] > thresh).sum() / 51, '\\n' 'BSpline', (cccs[1] > thresh).sum()", "i], lung_itp['Nearest'][:, i]) for i in range(lung_tru.shape[1])]) cccs = np.vstack((ccc_cnn, ccc_bsp, ccc_nn, ccc_ws,", "range(lung_tru.shape[1])]) ccc_bsp = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['BSpline'][:, i]) for i in range(lung_tru.shape[1])]) ccc_ws =", "lung_cnn[:, i]) for i in range(lung_tru.shape[1])]) ccc_lin = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Linear'][:, i]) for", "(ner_diff < bsp_diff).sum() / t, (ner_diff < cnn_diff).sum() / t) print((bsp_diff < lin_diff).sum()", "'Linear', 'lung') lung_itp['BSpline'] = get_all_features(path, 'BSpline', 'lung') lung_itp['Cosine'] = get_all_features(path, 'Cosine', 'lung') lung_itp['Nearest']", "rse(lung_tru, lung_cnn) lin_diff = rse(lung_tru, lung_itp['Linear']) cos_diff = rse(lung_tru, lung_itp['Cosine']) ner_diff = rse(lung_tru,", "< ner_diff).sum() / t, (lin_diff < bsp_diff).sum() / t, (lin_diff < cnn_diff).sum() /", "get_features_functions import get_features, final, get_results, display_results from get_features_functions import listfiles, unnormalize, get_all_features from", "'PixelCNN', 'lung') lung_itp['Linear'] = get_all_features(path, 'Linear', 'lung') lung_itp['BSpline'] = get_all_features(path, 'BSpline', 'lung') lung_itp['Cosine']", "in range(lung_tru.shape[1])]) ccc_lin = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Linear'][:, i]) for i in range(lung_tru.shape[1])]) ccc_bsp", "n_error[4].mean()) print() print('NRMSE STD:') print('PixelMiner:', n_error[0].std()) print('Linear:', n_error[1].std()) print('Win Sinc:', n_error[2].std()) print('Nearest:', n_error[3].std())", "np.vstack((ccc_cnn, ccc_bsp, ccc_nn, ccc_ws, ccc_lin)) print('Mean CCC') print('PixelMiner', cccs[0].mean(), '\\n' 'Win Sinc', cccs[3].mean(),", "f, shapiro, bartlett, f_oneway, kruskal from statsmodels.stats.weightstats import ztest from scipy.stats import binom_test", "para_non_para from get_features_functions import get_all_features, get_rmses, normalize def unnormalize(img): img += 1 img", "t, '\\t-\\t\\t' ) error = np.array([cnn_diff, lin_diff, cos_diff, ner_diff, bsp_diff]) n_error = np.zeros((5,", "'lung') lung_itp['BSpline'] = get_all_features(path, 'BSpline', 'lung') lung_itp['Cosine'] = get_all_features(path, 'Cosine', 'lung') lung_itp['Nearest'] =", ", (lin_diff < cos_diff).sum() / t, (lin_diff < ner_diff).sum() / t, (lin_diff <", "(cccs[1] > thresh).sum() / 51, '\\n' 'Nearest', (cccs[2] > thresh).sum() / 51, '\\n'", "(cnn_diff < bsp_diff).sum() / t, '\\t-\\t\\t' ) error = np.array([cnn_diff, lin_diff, cos_diff, ner_diff,", "'\\n' 'Win Sinc', cccs[3].mean(), '\\n' 'BSpline', cccs[1].mean(), '\\n' 'Nearest', cccs[2].mean(), '\\n' 'Linear', cccs[4].mean())", "n_error[1].mean()) print('Win Sinc:', n_error[2].mean()) print('Nearest:', n_error[3].mean()) print('BSpline', n_error[4].mean()) print() print('NRMSE STD:') print('PixelMiner:', n_error[0].std())", "features = [feature.split('_') for feature in features] features = np.array(features) lung_itp = {}", "1, :].flatten())) print('BSpline:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 4, :].flatten())) print('Nearest:', wilcoxon(n_error[:, 0, :].flatten(),", "'\\n' 'Nearest', (cccs[2] > thresh).sum() / 51, '\\n' 'Linear', (cccs[4] > thresh).sum() /", "cos_diff).sum() / t, '\\t-\\t\\t\\t' , (ner_diff < bsp_diff).sum() / t, (ner_diff < cnn_diff).sum()", "from get_features_functions import listfiles, unnormalize, get_all_features from get_features_functions import rmses, wilcoxons, ttests, para_non_para", "img *= (1024 + 3071) #img -= 1024 #img *= 255 img =", "bsp_diff).sum() / t, '\\t-\\t\\t' ) error = np.array([cnn_diff, lin_diff, cos_diff, ner_diff, bsp_diff]) n_error", "for i in range(error.shape[-1]): n_error[:, :, i] = normalize(error[:, :, i]) print() print('NRMSE", "np.array(features) lung_itp = {} lung_tru = get_all_features(path, 'tru_one', 'lung') lung_cnn = get_all_features(path, 'PixelCNN',", "0, :].flatten(), n_error[:, 3, :].flatten())) shape = n_error.shape[0] * n_error.shape[2] print('Binomial test:') print('Win", "lin_diff).sum() / t, '\\t-\\t\\t\\t' , (cos_diff < ner_diff).sum() / t, (cos_diff < bsp_diff).sum()", "ranksums from scipy.stats import f, shapiro, bartlett, f_oneway, kruskal from statsmodels.stats.weightstats import ztest", "51, '\\n' 'Nearest', (cccs[2] > thresh).sum() / 51, '\\n' 'Linear', (cccs[4] > thresh).sum()", "< lin_diff).sum() / t, (cnn_diff < cos_diff).sum() / t, (cnn_diff < ner_diff).sum() /", "'\\t-\\t\\t' ) error = np.array([cnn_diff, lin_diff, cos_diff, ner_diff, bsp_diff]) n_error = np.zeros((5, 50,", "= cnn_diff.shape[0] * cnn_diff.shape[1] print() print('Percent Greater:') print('Linear\\t\\t\\t Win Sinc\\t\\t\\t Nearest\\t\\t\\t BSpline\\t\\t\\t PixelMiner')", "n_error[:, 3, :].flatten())) shape = n_error.shape[0] * n_error.shape[2] print('Binomial test:') print('Win Sinc:', binom_test((n_error[:,", "ner_diff).sum() / t, (cos_diff < bsp_diff).sum() / t, (cos_diff < cnn_diff).sum() / t)", "'\\t-\\t\\t\\t' , (ner_diff < bsp_diff).sum() / t, (ner_diff < cnn_diff).sum() / t) print((bsp_diff", "= 0 path = r'H:\\Data\\W' files = os.listdir(path) print(files[14]) arr1 = np.load(os.path.join(path, files[14]))", "n_error[:, 2, :].flatten())) print('Linear:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 1, :].flatten())) print('BSpline:', wilcoxon(n_error[:, 0,", "< cos_diff).sum() / t, (lin_diff < ner_diff).sum() / t, (lin_diff < bsp_diff).sum() /", "'lung') lung_results = get_results(lung_tru, lung_cnn, lung_itp) display_results(lung_results, features) cnn_diff = rse(lung_tru, lung_cnn) lin_diff", "print(img.min(), img.max()) return img def normalize(a): b = (a - np.min(a))/np.ptp(a) return b", "/ t, (lin_diff < cnn_diff).sum() / t) print((cos_diff < lin_diff).sum() / t, '\\t-\\t\\t\\t'", "get_results(lung_tru, lung_cnn, lung_itp) display_results(lung_results, features) cnn_diff = rse(lung_tru, lung_cnn) lin_diff = rse(lung_tru, lung_itp['Linear'])", "print('Percent Greater:') print('Linear\\t\\t\\t Win Sinc\\t\\t\\t Nearest\\t\\t\\t BSpline\\t\\t\\t PixelMiner') print('\\t-\\t\\t\\t' , (lin_diff < cos_diff).sum()", "print(arr1.dtype, arr1.min(), arr1.max()) print(files[8]) arr2 = np.load(os.path.join(path, files[8])) features = get_features(arr1, arr2) features", "rse(lung_tru, lung_itp['Nearest']) bsp_diff = rse(lung_tru, lung_itp['BSpline']) t = cnn_diff.shape[0] * cnn_diff.shape[1] print() print('Percent", "print('Linear:', binom_test((n_error[:, 0, :] < n_error[:, 1, :]).sum() , shape)) print('BSpline:', binom_test((n_error[:, 0,", "print('Mean CCC') print('PixelMiner', cccs[0].mean(), '\\n' 'Win Sinc', cccs[3].mean(), '\\n' 'BSpline', cccs[1].mean(), '\\n' 'Nearest',", "'Nearest', 'lung') lung_results = get_results(lung_tru, lung_cnn, lung_itp) display_results(lung_results, features) cnn_diff = rse(lung_tru, lung_cnn)", "train_test_split from sklearn.feature_extraction import image import matplotlib.pyplot as plt from functools import partial", "bartlett, f_oneway, kruskal from statsmodels.stats.weightstats import ztest from scipy.stats import binom_test from radiomics", "= np.load(os.path.join(path, files[14])) arr1 = unnormalize(arr1) print(arr1.dtype, arr1.min(), arr1.max()) print(files[8]) arr2 = np.load(os.path.join(path,", "cos_diff).sum() / t, (cnn_diff < ner_diff).sum() / t, (cnn_diff < bsp_diff).sum() / t,", "get_all_features from get_features_functions import rmses, wilcoxons, ttests, para_non_para from get_features_functions import get_all_features, get_rmses,", "lung_itp['BSpline'] = get_all_features(path, 'BSpline', 'lung') lung_itp['Cosine'] = get_all_features(path, 'Cosine', 'lung') lung_itp['Nearest'] = get_all_features(path,", "listfiles, unnormalize, get_all_features from get_features_functions import rmses, wilcoxons, ttests, para_non_para from get_features_functions import", "get_all_features(path, 'Cosine', 'lung') lung_itp['Nearest'] = get_all_features(path, 'Nearest', 'lung') lung_results = get_results(lung_tru, lung_cnn, lung_itp)", "display_results from get_features_functions import listfiles, unnormalize, get_all_features from get_features_functions import rmses, wilcoxons, ttests,", "< n_error[:, 4, :]).sum() , shape)) print('Nearest:', binom_test((n_error[:, 0, :] < n_error[:, 3,", "'lung') lung_itp['Cosine'] = get_all_features(path, 'Cosine', 'lung') lung_itp['Nearest'] = get_all_features(path, 'Nearest', 'lung') lung_results =", "cnn_diff).sum() / t) print((cos_diff < lin_diff).sum() / t, '\\t-\\t\\t\\t' , (cos_diff < ner_diff).sum()", "PixelMiner') print('\\t-\\t\\t\\t' , (lin_diff < cos_diff).sum() / t, (lin_diff < ner_diff).sum() / t,", "= [feature.split('_') for feature in features] features = np.array(features) lung_itp = {} lung_tru", "img /= 2 img *= (1024 + 3071) #img -= 1024 #img *=", "def rse(x, y): diff = x - y sqrd = diff ** 2", "features.keys() if key.find('diagnostic') < 0] features = [feature[9:] for feature in features] features", "/ t, (bsp_diff < ner_diff).sum() / t, '\\t-\\t\\t\\t' , (bsp_diff < cnn_diff).sum() /", "unnormalize(arr1) print(arr1.dtype, arr1.min(), arr1.max()) print(files[8]) arr2 = np.load(os.path.join(path, files[8])) features = get_features(arr1, arr2)", "thresh).sum() / 51) print('Wilcoxons:') print('Win Sinc:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 2, :].flatten())) print('Linear:',", "test:') print('Win Sinc:', binom_test((n_error[:, 0, :] < n_error[:, 2, :]).sum() , shape)) print('Linear:',", "print('NRMSE STD:') print('PixelMiner:', n_error[0].std()) print('Linear:', n_error[1].std()) print('Win Sinc:', n_error[2].std()) print('Nearest:', n_error[3].std()) print('BSpline', n_error[4].std())", ", (bsp_diff < cnn_diff).sum() / t) print((cnn_diff < lin_diff).sum() / t, (cnn_diff <", "as sitk import pandas as pd from random import randint from tqdm import", "(cccs[0] > thresh).sum() / 51, '\\n' 'Win Sinc', (cccs[3] > thresh).sum() / 51,", "51)) for i in range(error.shape[-1]): n_error[:, :, i] = normalize(error[:, :, i]) print()", "4, :]).sum() , shape)) print('Nearest:', binom_test((n_error[:, 0, :] < n_error[:, 3, :]).sum() ,", "lin_diff, cos_diff, ner_diff, bsp_diff]) n_error = np.zeros((5, 50, 51)) for i in range(error.shape[-1]):", "BSpline\\t\\t\\t PixelMiner') print('\\t-\\t\\t\\t' , (lin_diff < cos_diff).sum() / t, (lin_diff < ner_diff).sum() /", "np.min(a))/np.ptp(a) return b def rse(x, y): diff = x - y sqrd =", "i]) for i in range(lung_tru.shape[1])]) cccs = np.vstack((ccc_cnn, ccc_bsp, ccc_nn, ccc_ws, ccc_lin)) print('Mean", "b def rse(x, y): diff = x - y sqrd = diff **", "(lin_diff < cos_diff).sum() / t, (lin_diff < ner_diff).sum() / t, (lin_diff < bsp_diff).sum()", "/ t, '\\t-\\t\\t\\t' , (ner_diff < bsp_diff).sum() / t, (ner_diff < cnn_diff).sum() /", "print('PixelMiner', (cccs[0] > thresh).sum() / 51, '\\n' 'Win Sinc', (cccs[3] > thresh).sum() /", "if key.find('diagnostic') < 0] features = [feature[9:] for feature in features] features =", "ccc_bsp = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['BSpline'][:, i]) for i in range(lung_tru.shape[1])]) ccc_ws = np.array([concordance_correlation_coefficient(lung_tru[:,", "lin_diff = rse(lung_tru, lung_itp['Linear']) cos_diff = rse(lung_tru, lung_itp['Cosine']) ner_diff = rse(lung_tru, lung_itp['Nearest']) bsp_diff", ":].flatten(), n_error[:, 4, :].flatten())) print('Nearest:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 3, :].flatten())) shape =", "return img def normalize(a): b = (a - np.min(a))/np.ptp(a) return b def rse(x,", "print('Linear\\t\\t\\t Win Sinc\\t\\t\\t Nearest\\t\\t\\t BSpline\\t\\t\\t PixelMiner') print('\\t-\\t\\t\\t' , (lin_diff < cos_diff).sum() / t,", "< cos_diff).sum() / t, '\\t-\\t\\t\\t' , (ner_diff < bsp_diff).sum() / t, (ner_diff <", "numpy as np import matplotlib.pyplot as plt from ccc import concordance_correlation_coefficient from scipy.stats", "= x - y sqrd = diff ** 2 sqrt = np.sqrt(sqrd) return", "/ t) print((cnn_diff < lin_diff).sum() / t, (cnn_diff < cos_diff).sum() / t, (cnn_diff", "display_results(lung_results, features) cnn_diff = rse(lung_tru, lung_cnn) lin_diff = rse(lung_tru, lung_itp['Linear']) cos_diff = rse(lung_tru,", "= rse(lung_tru, lung_cnn) lin_diff = rse(lung_tru, lung_itp['Linear']) cos_diff = rse(lung_tru, lung_itp['Cosine']) ner_diff =", "(cos_diff < bsp_diff).sum() / t, (cos_diff < cnn_diff).sum() / t) print((ner_diff < lin_diff).sum()", "STD:') print('PixelMiner:', n_error[0].std()) print('Linear:', n_error[1].std()) print('Win Sinc:', n_error[2].std()) print('Nearest:', n_error[3].std()) print('BSpline', n_error[4].std()) ccc_cnn", "binom_test((n_error[:, 0, :] < n_error[:, 4, :]).sum() , shape)) print('Nearest:', binom_test((n_error[:, 0, :]", "matplotlib.pyplot as plt from ccc import concordance_correlation_coefficient from scipy.stats import wilcoxon, ttest_rel, ttest_ind,", "i], lung_itp['Cosine'][:, i]) for i in range(lung_tru.shape[1])]) ccc_nn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Nearest'][:, i])", ":].flatten())) print('Linear:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 1, :].flatten())) print('BSpline:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:,", "feature in features] features = [feature.split('_') for feature in features] features = np.array(features)", "'lung') lung_cnn = get_all_features(path, 'PixelCNN', 'lung') lung_itp['Linear'] = get_all_features(path, 'Linear', 'lung') lung_itp['BSpline'] =", "/ t, (cnn_diff < ner_diff).sum() / t, (cnn_diff < bsp_diff).sum() / t, '\\t-\\t\\t'", "'\\n' 'BSpline', (cccs[1] > thresh).sum() / 51, '\\n' 'Nearest', (cccs[2] > thresh).sum() /", "Sinc', (cccs[3] > thresh).sum() / 51, '\\n' 'BSpline', (cccs[1] > thresh).sum() / 51,", ":] < n_error[:, 2, :]).sum() , shape)) print('Linear:', binom_test((n_error[:, 0, :] < n_error[:,", "= [re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", feature) for feature in features] features = [feature.split('_') for", "= get_results(lung_tru, lung_cnn, lung_itp) display_results(lung_results, features) cnn_diff = rse(lung_tru, lung_cnn) lin_diff = rse(lung_tru,", "(cnn_diff < ner_diff).sum() / t, (cnn_diff < bsp_diff).sum() / t, '\\t-\\t\\t' ) error", "= np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Cosine'][:, i]) for i in range(lung_tru.shape[1])]) ccc_nn = np.array([concordance_correlation_coefficient(lung_tru[:, i],", "0, :].flatten(), n_error[:, 4, :].flatten())) print('Nearest:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 3, :].flatten())) shape", "arr2) features = [key for key in features.keys() if key.find('diagnostic') < 0] features", "(ner_diff < cos_diff).sum() / t, '\\t-\\t\\t\\t' , (ner_diff < bsp_diff).sum() / t, (ner_diff", "print('BSpline', n_error[4].std()) ccc_cnn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_cnn[:, i]) for i in range(lung_tru.shape[1])]) ccc_lin", "lung_itp['Cosine'][:, i]) for i in range(lung_tru.shape[1])]) ccc_nn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Nearest'][:, i]) for", "mannwhitneyu, ranksums from scipy.stats import f, shapiro, bartlett, f_oneway, kruskal from statsmodels.stats.weightstats import", "cccs[1].mean(), '\\n' 'Nearest', cccs[2].mean(), '\\n' 'Linear', cccs[4].mean()) print() print('Reproducibility') thresh = .85 print('PixelMiner',", "binom_test((n_error[:, 0, :] < n_error[:, 2, :]).sum() , shape)) print('Linear:', binom_test((n_error[:, 0, :]", "/ 51) print('Wilcoxons:') print('Win Sinc:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 2, :].flatten())) print('Linear:', wilcoxon(n_error[:,", "n_error[1].std()) print('Win Sinc:', n_error[2].std()) print('Nearest:', n_error[3].std()) print('BSpline', n_error[4].std()) ccc_cnn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_cnn[:,", "get_features(arr1, arr2) features = [key for key in features.keys() if key.find('diagnostic') < 0]", "< n_error[:, 2, :]).sum() , shape)) print('Linear:', binom_test((n_error[:, 0, :] < n_error[:, 1,", "print('Linear:', n_error[1].mean()) print('Win Sinc:', n_error[2].mean()) print('Nearest:', n_error[3].mean()) print('BSpline', n_error[4].mean()) print() print('NRMSE STD:') print('PixelMiner:',", "'\\t-\\t\\t\\t' , (cos_diff < ner_diff).sum() / t, (cos_diff < bsp_diff).sum() / t, (cos_diff", "in range(lung_tru.shape[1])]) ccc_bsp = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['BSpline'][:, i]) for i in range(lung_tru.shape[1])]) ccc_ws", "cccs = np.vstack((ccc_cnn, ccc_bsp, ccc_nn, ccc_ws, ccc_lin)) print('Mean CCC') print('PixelMiner', cccs[0].mean(), '\\n' 'Win", "plt from ccc import concordance_correlation_coefficient from scipy.stats import wilcoxon, ttest_rel, ttest_ind, mannwhitneyu, ranksums", "= .85 print('PixelMiner', (cccs[0] > thresh).sum() / 51, '\\n' 'Win Sinc', (cccs[3] >", "n_error = np.zeros((5, 50, 51)) for i in range(error.shape[-1]): n_error[:, :, i] =", "/ 51, '\\n' 'Linear', (cccs[4] > thresh).sum() / 51) print('Wilcoxons:') print('Win Sinc:', wilcoxon(n_error[:,", "ner_diff = rse(lung_tru, lung_itp['Nearest']) bsp_diff = rse(lung_tru, lung_itp['BSpline']) t = cnn_diff.shape[0] * cnn_diff.shape[1]", "lung_tru = get_all_features(path, 'tru_one', 'lung') lung_cnn = get_all_features(path, 'PixelCNN', 'lung') lung_itp['Linear'] = get_all_features(path,", "import f, shapiro, bartlett, f_oneway, kruskal from statsmodels.stats.weightstats import ztest from scipy.stats import", "key.find('diagnostic') < 0] features = [feature[9:] for feature in features] features = [re.sub(r\"(\\w)([A-Z])\",", "51, '\\n' 'Linear', (cccs[4] > thresh).sum() / 51) print('Wilcoxons:') print('Win Sinc:', wilcoxon(n_error[:, 0,", ") error = np.array([cnn_diff, lin_diff, cos_diff, ner_diff, bsp_diff]) n_error = np.zeros((5, 50, 51))", "y): diff = x - y sqrd = diff ** 2 sqrt =", "in range(error.shape[-1]): n_error[:, :, i] = normalize(error[:, :, i]) print() print('NRMSE Mean:') print('PixelMiner:',", "normalize(a): b = (a - np.min(a))/np.ptp(a) return b def rse(x, y): diff =", "'\\n' 'Nearest', cccs[2].mean(), '\\n' 'Linear', cccs[4].mean()) print() print('Reproducibility') thresh = .85 print('PixelMiner', (cccs[0]", "features = get_features(arr1, arr2) features = [key for key in features.keys() if key.find('diagnostic')", "/ 51, '\\n' 'Win Sinc', (cccs[3] > thresh).sum() / 51, '\\n' 'BSpline', (cccs[1]", "= np.load(os.path.join(path, files[8])) features = get_features(arr1, arr2) features = [key for key in", "/= 2 img *= (1024 + 3071) #img -= 1024 #img *= 255", "Nearest\\t\\t\\t BSpline\\t\\t\\t PixelMiner') print('\\t-\\t\\t\\t' , (lin_diff < cos_diff).sum() / t, (lin_diff < ner_diff).sum()", "features] features = [feature.split('_') for feature in features] features = np.array(features) lung_itp =", "print('Nearest:', n_error[3].std()) print('BSpline', n_error[4].std()) ccc_cnn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_cnn[:, i]) for i in", "path = r'H:\\Data\\W' files = os.listdir(path) print(files[14]) arr1 = np.load(os.path.join(path, files[14])) arr1 =", "import os import re import numpy as np import matplotlib.pyplot as plt from", "np.load(os.path.join(path, files[8])) features = get_features(arr1, arr2) features = [key for key in features.keys()", "bsp_diff).sum() / t, (cos_diff < cnn_diff).sum() / t) print((ner_diff < lin_diff).sum() / t,", "Sinc:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 2, :].flatten())) print('Linear:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 1,", "os import re import numpy as np import matplotlib.pyplot as plt from ccc", "from get_features_functions import get_features, final, get_results, display_results from get_features_functions import listfiles, unnormalize, get_all_features", "for i in range(lung_tru.shape[1])]) ccc_ws = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Cosine'][:, i]) for i in", "0, :].flatten(), n_error[:, 1, :].flatten())) print('BSpline:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 4, :].flatten())) print('Nearest:',", "n_error[:, 1, :]).sum() , shape)) print('BSpline:', binom_test((n_error[:, 0, :] < n_error[:, 4, :]).sum()", "for feature in features] features = np.array(features) lung_itp = {} lung_tru = get_all_features(path,", "for i in range(lung_tru.shape[1])]) ccc_nn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Nearest'][:, i]) for i in", "SimpleITK as sitk import pandas as pd from random import randint from tqdm", "t, (cnn_diff < bsp_diff).sum() / t, '\\t-\\t\\t' ) error = np.array([cnn_diff, lin_diff, cos_diff,", "print('Reproducibility') thresh = .85 print('PixelMiner', (cccs[0] > thresh).sum() / 51, '\\n' 'Win Sinc',", "ccc_ws = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Cosine'][:, i]) for i in range(lung_tru.shape[1])]) ccc_nn = np.array([concordance_correlation_coefficient(lung_tru[:,", "t, (bsp_diff < cos_diff).sum() / t, (bsp_diff < ner_diff).sum() / t, '\\t-\\t\\t\\t' ,", "[re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", feature) for feature in features] features = [feature.split('_') for feature", "matplotlib.pyplot as plt from functools import partial from get_features_functions import get_features, final, get_results,", "ztest from scipy.stats import binom_test from radiomics import featureextractor, getTestCase import SimpleITK as", "cnn_diff.shape[1] print() print('Percent Greater:') print('Linear\\t\\t\\t Win Sinc\\t\\t\\t Nearest\\t\\t\\t BSpline\\t\\t\\t PixelMiner') print('\\t-\\t\\t\\t' , (lin_diff", "i in range(lung_tru.shape[1])]) ccc_ws = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Cosine'][:, i]) for i in range(lung_tru.shape[1])])", ", shape)) print('BSpline:', binom_test((n_error[:, 0, :] < n_error[:, 4, :]).sum() , shape)) print('Nearest:',", "/ t, (lin_diff < ner_diff).sum() / t, (lin_diff < bsp_diff).sum() / t, (lin_diff", "i], lung_itp['BSpline'][:, i]) for i in range(lung_tru.shape[1])]) ccc_ws = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Cosine'][:, i])", "wilcoxons, ttests, para_non_para from get_features_functions import get_all_features, get_rmses, normalize def unnormalize(img): img +=", "get_rmses, normalize def unnormalize(img): img += 1 img /= 2 img *= (1024", "get_all_features(path, 'tru_one', 'lung') lung_cnn = get_all_features(path, 'PixelCNN', 'lung') lung_itp['Linear'] = get_all_features(path, 'Linear', 'lung')", "= rse(lung_tru, lung_itp['BSpline']) t = cnn_diff.shape[0] * cnn_diff.shape[1] print() print('Percent Greater:') print('Linear\\t\\t\\t Win", "bsp_diff).sum() / t, (lin_diff < cnn_diff).sum() / t) print((cos_diff < lin_diff).sum() / t,", "n_error[0].std()) print('Linear:', n_error[1].std()) print('Win Sinc:', n_error[2].std()) print('Nearest:', n_error[3].std()) print('BSpline', n_error[4].std()) ccc_cnn = np.array([concordance_correlation_coefficient(lung_tru[:,", "thresh).sum() / 51, '\\n' 'BSpline', (cccs[1] > thresh).sum() / 51, '\\n' 'Nearest', (cccs[2]", "arr1 = np.load(os.path.join(path, files[14])) arr1 = unnormalize(arr1) print(arr1.dtype, arr1.min(), arr1.max()) print(files[8]) arr2 =", "cccs[0].mean(), '\\n' 'Win Sinc', cccs[3].mean(), '\\n' 'BSpline', cccs[1].mean(), '\\n' 'Nearest', cccs[2].mean(), '\\n' 'Linear',", "- y sqrd = diff ** 2 sqrt = np.sqrt(sqrd) return sqrt n", "np import matplotlib.pyplot as plt from ccc import concordance_correlation_coefficient from scipy.stats import wilcoxon,", "thresh).sum() / 51, '\\n' 'Win Sinc', (cccs[3] > thresh).sum() / 51, '\\n' 'BSpline',", ":].flatten())) shape = n_error.shape[0] * n_error.shape[2] print('Binomial test:') print('Win Sinc:', binom_test((n_error[:, 0, :]", "lung_itp['Cosine'] = get_all_features(path, 'Cosine', 'lung') lung_itp['Nearest'] = get_all_features(path, 'Nearest', 'lung') lung_results = get_results(lung_tru,", "ccc_lin)) print('Mean CCC') print('PixelMiner', cccs[0].mean(), '\\n' 'Win Sinc', cccs[3].mean(), '\\n' 'BSpline', cccs[1].mean(), '\\n'", "i in range(error.shape[-1]): n_error[:, :, i] = normalize(error[:, :, i]) print() print('NRMSE Mean:')", "as plt from ccc import concordance_correlation_coefficient from scipy.stats import wilcoxon, ttest_rel, ttest_ind, mannwhitneyu,", ":, i]) print() print('NRMSE Mean:') print('PixelMiner:', n_error[0].mean()) print('Linear:', n_error[1].mean()) print('Win Sinc:', n_error[2].mean()) print('Nearest:',", "'Win Sinc', cccs[3].mean(), '\\n' 'BSpline', cccs[1].mean(), '\\n' 'Nearest', cccs[2].mean(), '\\n' 'Linear', cccs[4].mean()) print()", "lung_itp['Linear'] = get_all_features(path, 'Linear', 'lung') lung_itp['BSpline'] = get_all_features(path, 'BSpline', 'lung') lung_itp['Cosine'] = get_all_features(path,", "key in features.keys() if key.find('diagnostic') < 0] features = [feature[9:] for feature in", "features = [key for key in features.keys() if key.find('diagnostic') < 0] features =", "> thresh).sum() / 51, '\\n' 'Nearest', (cccs[2] > thresh).sum() / 51, '\\n' 'Linear',", "/ t) print((cos_diff < lin_diff).sum() / t, '\\t-\\t\\t\\t' , (cos_diff < ner_diff).sum() /", "< ner_diff).sum() / t, (cos_diff < bsp_diff).sum() / t, (cos_diff < cnn_diff).sum() /", "b = (a - np.min(a))/np.ptp(a) return b def rse(x, y): diff = x", "#from sklearn.model_selection import train_test_split from sklearn.feature_extraction import image import matplotlib.pyplot as plt from", "scipy.stats import f, shapiro, bartlett, f_oneway, kruskal from statsmodels.stats.weightstats import ztest from scipy.stats", ":]).sum() , shape)) print('BSpline:', binom_test((n_error[:, 0, :] < n_error[:, 4, :]).sum() , shape))", "rse(lung_tru, lung_itp['Cosine']) ner_diff = rse(lung_tru, lung_itp['Nearest']) bsp_diff = rse(lung_tru, lung_itp['BSpline']) t = cnn_diff.shape[0]", "random import randint from tqdm import tqdm from PIL import Image, ImageOps, ImageEnhance", "sqrt = np.sqrt(sqrd) return sqrt n = 0 path = r'H:\\Data\\W' files =", "'Nearest', (cccs[2] > thresh).sum() / 51, '\\n' 'Linear', (cccs[4] > thresh).sum() / 51)", "get_features_functions import listfiles, unnormalize, get_all_features from get_features_functions import rmses, wilcoxons, ttests, para_non_para from", "rmses, wilcoxons, ttests, para_non_para from get_features_functions import get_all_features, get_rmses, normalize def unnormalize(img): img", "** 2 sqrt = np.sqrt(sqrd) return sqrt n = 0 path = r'H:\\Data\\W'", "(cccs[3] > thresh).sum() / 51, '\\n' 'BSpline', (cccs[1] > thresh).sum() / 51, '\\n'", "i], lung_itp['Linear'][:, i]) for i in range(lung_tru.shape[1])]) ccc_bsp = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['BSpline'][:, i])", "print('Wilcoxons:') print('Win Sinc:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 2, :].flatten())) print('Linear:', wilcoxon(n_error[:, 0, :].flatten(),", "for key in features.keys() if key.find('diagnostic') < 0] features = [feature[9:] for feature", "i]) print() print('NRMSE Mean:') print('PixelMiner:', n_error[0].mean()) print('Linear:', n_error[1].mean()) print('Win Sinc:', n_error[2].mean()) print('Nearest:', n_error[3].mean())", ", shape)) print('Linear:', binom_test((n_error[:, 0, :] < n_error[:, 1, :]).sum() , shape)) print('BSpline:',", "wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 3, :].flatten())) shape = n_error.shape[0] * n_error.shape[2] print('Binomial test:')", "ccc import concordance_correlation_coefficient from scipy.stats import wilcoxon, ttest_rel, ttest_ind, mannwhitneyu, ranksums from scipy.stats", "print('BSpline:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 4, :].flatten())) print('Nearest:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 3,", "4, :].flatten())) print('Nearest:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 3, :].flatten())) shape = n_error.shape[0] *", "print((bsp_diff < lin_diff).sum() / t, (bsp_diff < cos_diff).sum() / t, (bsp_diff < ner_diff).sum()", "pd from random import randint from tqdm import tqdm from PIL import Image,", "print('Win Sinc:', n_error[2].mean()) print('Nearest:', n_error[3].mean()) print('BSpline', n_error[4].mean()) print() print('NRMSE STD:') print('PixelMiner:', n_error[0].std()) print('Linear:',", "i]) for i in range(lung_tru.shape[1])]) ccc_ws = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Cosine'][:, i]) for i", "n_error[:, 4, :]).sum() , shape)) print('Nearest:', binom_test((n_error[:, 0, :] < n_error[:, 3, :]).sum()", "i in range(lung_tru.shape[1])]) ccc_nn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Nearest'][:, i]) for i in range(lung_tru.shape[1])])", ":]).sum() , shape)) print('Linear:', binom_test((n_error[:, 0, :] < n_error[:, 1, :]).sum() , shape))", "Win Sinc\\t\\t\\t Nearest\\t\\t\\t BSpline\\t\\t\\t PixelMiner') print('\\t-\\t\\t\\t' , (lin_diff < cos_diff).sum() / t, (lin_diff", "rse(lung_tru, lung_itp['Linear']) cos_diff = rse(lung_tru, lung_itp['Cosine']) ner_diff = rse(lung_tru, lung_itp['Nearest']) bsp_diff = rse(lung_tru,", "r'H:\\Data\\W' files = os.listdir(path) print(files[14]) arr1 = np.load(os.path.join(path, files[14])) arr1 = unnormalize(arr1) print(arr1.dtype,", "unnormalize(img): img += 1 img /= 2 img *= (1024 + 3071) #img", "< cnn_diff).sum() / t) print((cnn_diff < lin_diff).sum() / t, (cnn_diff < cos_diff).sum() /", "> thresh).sum() / 51, '\\n' 'Win Sinc', (cccs[3] > thresh).sum() / 51, '\\n'", "'\\t-\\t\\t\\t' , (bsp_diff < cnn_diff).sum() / t) print((cnn_diff < lin_diff).sum() / t, (cnn_diff", "n_error.shape[2] print('Binomial test:') print('Win Sinc:', binom_test((n_error[:, 0, :] < n_error[:, 2, :]).sum() ,", "in range(lung_tru.shape[1])]) cccs = np.vstack((ccc_cnn, ccc_bsp, ccc_nn, ccc_ws, ccc_lin)) print('Mean CCC') print('PixelMiner', cccs[0].mean(),", "'lung') lung_itp['Linear'] = get_all_features(path, 'Linear', 'lung') lung_itp['BSpline'] = get_all_features(path, 'BSpline', 'lung') lung_itp['Cosine'] =", "ccc_ws, ccc_lin)) print('Mean CCC') print('PixelMiner', cccs[0].mean(), '\\n' 'Win Sinc', cccs[3].mean(), '\\n' 'BSpline', cccs[1].mean(),", "255 img = img.astype(np.uint8) print(img.min(), img.max()) return img def normalize(a): b = (a", "get_all_features(path, 'BSpline', 'lung') lung_itp['Cosine'] = get_all_features(path, 'Cosine', 'lung') lung_itp['Nearest'] = get_all_features(path, 'Nearest', 'lung')", "range(lung_tru.shape[1])]) ccc_nn = np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Nearest'][:, i]) for i in range(lung_tru.shape[1])]) cccs =", "in features.keys() if key.find('diagnostic') < 0] features = [feature[9:] for feature in features]", "unnormalize, get_all_features from get_features_functions import rmses, wilcoxons, ttests, para_non_para from get_features_functions import get_all_features,", "get_all_features(path, 'Nearest', 'lung') lung_results = get_results(lung_tru, lung_cnn, lung_itp) display_results(lung_results, features) cnn_diff = rse(lung_tru,", "print('\\t-\\t\\t\\t' , (lin_diff < cos_diff).sum() / t, (lin_diff < ner_diff).sum() / t, (lin_diff", "< cnn_diff).sum() / t) print((bsp_diff < lin_diff).sum() / t, (bsp_diff < cos_diff).sum() /", ":].flatten(), n_error[:, 1, :].flatten())) print('BSpline:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 4, :].flatten())) print('Nearest:', wilcoxon(n_error[:,", "0, :] < n_error[:, 1, :]).sum() , shape)) print('BSpline:', binom_test((n_error[:, 0, :] <", "img += 1 img /= 2 img *= (1024 + 3071) #img -=", "sklearn.model_selection import train_test_split from sklearn.feature_extraction import image import matplotlib.pyplot as plt from functools", "get_features_functions import rmses, wilcoxons, ttests, para_non_para from get_features_functions import get_all_features, get_rmses, normalize def", "/ t, (ner_diff < cos_diff).sum() / t, '\\t-\\t\\t\\t' , (ner_diff < bsp_diff).sum() /", "'tru_one', 'lung') lung_cnn = get_all_features(path, 'PixelCNN', 'lung') lung_itp['Linear'] = get_all_features(path, 'Linear', 'lung') lung_itp['BSpline']", "'Cosine', 'lung') lung_itp['Nearest'] = get_all_features(path, 'Nearest', 'lung') lung_results = get_results(lung_tru, lung_cnn, lung_itp) display_results(lung_results,", "Mean:') print('PixelMiner:', n_error[0].mean()) print('Linear:', n_error[1].mean()) print('Win Sinc:', n_error[2].mean()) print('Nearest:', n_error[3].mean()) print('BSpline', n_error[4].mean()) print()", "/ 51, '\\n' 'BSpline', (cccs[1] > thresh).sum() / 51, '\\n' 'Nearest', (cccs[2] >", "< lin_diff).sum() / t, '\\t-\\t\\t\\t' , (cos_diff < ner_diff).sum() / t, (cos_diff <", "final, get_results, display_results from get_features_functions import listfiles, unnormalize, get_all_features from get_features_functions import rmses,", "lung_itp['Nearest'][:, i]) for i in range(lung_tru.shape[1])]) cccs = np.vstack((ccc_cnn, ccc_bsp, ccc_nn, ccc_ws, ccc_lin))", "{} lung_tru = get_all_features(path, 'tru_one', 'lung') lung_cnn = get_all_features(path, 'PixelCNN', 'lung') lung_itp['Linear'] =", "print('Nearest:', wilcoxon(n_error[:, 0, :].flatten(), n_error[:, 3, :].flatten())) shape = n_error.shape[0] * n_error.shape[2] print('Binomial", "= np.array([concordance_correlation_coefficient(lung_tru[:, i], lung_itp['Nearest'][:, i]) for i in range(lung_tru.shape[1])]) cccs = np.vstack((ccc_cnn, ccc_bsp,", "1 img /= 2 img *= (1024 + 3071) #img -= 1024 #img", "51, '\\n' 'BSpline', (cccs[1] > thresh).sum() / 51, '\\n' 'Nearest', (cccs[2] > thresh).sum()", "n_error.shape[0] * n_error.shape[2] print('Binomial test:') print('Win Sinc:', binom_test((n_error[:, 0, :] < n_error[:, 2,", "'\\n' 'BSpline', cccs[1].mean(), '\\n' 'Nearest', cccs[2].mean(), '\\n' 'Linear', cccs[4].mean()) print() print('Reproducibility') thresh =", "= np.vstack((ccc_cnn, ccc_bsp, ccc_nn, ccc_ws, ccc_lin)) print('Mean CCC') print('PixelMiner', cccs[0].mean(), '\\n' 'Win Sinc',", "t, (lin_diff < cnn_diff).sum() / t) print((cos_diff < lin_diff).sum() / t, '\\t-\\t\\t\\t' ,", "import partial from get_features_functions import get_features, final, get_results, display_results from get_features_functions import listfiles,", "range(error.shape[-1]): n_error[:, :, i] = normalize(error[:, :, i]) print() print('NRMSE Mean:') print('PixelMiner:', n_error[0].mean())" ]
[ "the way I want it '''), epilog = \"Contact:<EMAIL>\" ) parser.add_argument(\"infile\", nargs=\"?\", type=argparse.FileType(\"r\"),", "'''), epilog = \"Contact:<EMAIL>\" ) parser.add_argument(\"infile\", nargs=\"?\", type=argparse.FileType(\"r\"), default=sys.stdin) parser.add_argument(\"ofile\", nargs=\"?\", type=argparse.FileType(\"w\"), default=sys.stdout)", "= \"argparse_example\", # default is sys.argv[0], formatter_class = argparse.RawDescriptionHelpFormatter, description = dedent(''' Please", "= argparse.RawDescriptionHelpFormatter, description = dedent(''' Please do not mess up this text! --------------------------------", "\"Contact:<EMAIL>\" ) parser.add_argument(\"infile\", nargs=\"?\", type=argparse.FileType(\"r\"), default=sys.stdin) parser.add_argument(\"ofile\", nargs=\"?\", type=argparse.FileType(\"w\"), default=sys.stdout) args = parser.parse_args()", "for line in indata: odata.write(line) if __name__ == \"__main__\": parser = argparse.ArgumentParser( prog", "argparse from textwrap import dedent def main(kwargs): with kwargs[\"infile\"] as indata,\\ kwargs[\"ofile\"] as", "it '''), epilog = \"Contact:<EMAIL>\" ) parser.add_argument(\"infile\", nargs=\"?\", type=argparse.FileType(\"r\"), default=sys.stdin) parser.add_argument(\"ofile\", nargs=\"?\", type=argparse.FileType(\"w\"),", "\"__main__\": parser = argparse.ArgumentParser( prog = \"argparse_example\", # default is sys.argv[0], formatter_class =", "with kwargs[\"infile\"] as indata,\\ kwargs[\"ofile\"] as odata: for line in indata: odata.write(line) if", "= argparse.ArgumentParser( prog = \"argparse_example\", # default is sys.argv[0], formatter_class = argparse.RawDescriptionHelpFormatter, description", "indented it exactly the way I want it '''), epilog = \"Contact:<EMAIL>\" )", "\"argparse_example\", # default is sys.argv[0], formatter_class = argparse.RawDescriptionHelpFormatter, description = dedent(''' Please do", "formatter_class = argparse.RawDescriptionHelpFormatter, description = dedent(''' Please do not mess up this text!", "not mess up this text! -------------------------------- I have indented it exactly the way", "odata.write(line) if __name__ == \"__main__\": parser = argparse.ArgumentParser( prog = \"argparse_example\", # default", "default is sys.argv[0], formatter_class = argparse.RawDescriptionHelpFormatter, description = dedent(''' Please do not mess", "parser = argparse.ArgumentParser( prog = \"argparse_example\", # default is sys.argv[0], formatter_class = argparse.RawDescriptionHelpFormatter,", "this text! -------------------------------- I have indented it exactly the way I want it", "I have indented it exactly the way I want it '''), epilog =", "way I want it '''), epilog = \"Contact:<EMAIL>\" ) parser.add_argument(\"infile\", nargs=\"?\", type=argparse.FileType(\"r\"), default=sys.stdin)", "main(kwargs): with kwargs[\"infile\"] as indata,\\ kwargs[\"ofile\"] as odata: for line in indata: odata.write(line)", "__name__ == \"__main__\": parser = argparse.ArgumentParser( prog = \"argparse_example\", # default is sys.argv[0],", "# default is sys.argv[0], formatter_class = argparse.RawDescriptionHelpFormatter, description = dedent(''' Please do not", "argparse.RawDescriptionHelpFormatter, description = dedent(''' Please do not mess up this text! -------------------------------- I", "import argparse from textwrap import dedent def main(kwargs): with kwargs[\"infile\"] as indata,\\ kwargs[\"ofile\"]", "if __name__ == \"__main__\": parser = argparse.ArgumentParser( prog = \"argparse_example\", # default is", "it exactly the way I want it '''), epilog = \"Contact:<EMAIL>\" ) parser.add_argument(\"infile\",", "kwargs[\"ofile\"] as odata: for line in indata: odata.write(line) if __name__ == \"__main__\": parser", "sys import argparse from textwrap import dedent def main(kwargs): with kwargs[\"infile\"] as indata,\\", "want it '''), epilog = \"Contact:<EMAIL>\" ) parser.add_argument(\"infile\", nargs=\"?\", type=argparse.FileType(\"r\"), default=sys.stdin) parser.add_argument(\"ofile\", nargs=\"?\",", "dedent def main(kwargs): with kwargs[\"infile\"] as indata,\\ kwargs[\"ofile\"] as odata: for line in", "= \"Contact:<EMAIL>\" ) parser.add_argument(\"infile\", nargs=\"?\", type=argparse.FileType(\"r\"), default=sys.stdin) parser.add_argument(\"ofile\", nargs=\"?\", type=argparse.FileType(\"w\"), default=sys.stdout) args =", "import dedent def main(kwargs): with kwargs[\"infile\"] as indata,\\ kwargs[\"ofile\"] as odata: for line", "do not mess up this text! -------------------------------- I have indented it exactly the", "indata,\\ kwargs[\"ofile\"] as odata: for line in indata: odata.write(line) if __name__ == \"__main__\":", "argparse.ArgumentParser( prog = \"argparse_example\", # default is sys.argv[0], formatter_class = argparse.RawDescriptionHelpFormatter, description =", ") parser.add_argument(\"infile\", nargs=\"?\", type=argparse.FileType(\"r\"), default=sys.stdin) parser.add_argument(\"ofile\", nargs=\"?\", type=argparse.FileType(\"w\"), default=sys.stdout) args = parser.parse_args() main(vars(args))", "prog = \"argparse_example\", # default is sys.argv[0], formatter_class = argparse.RawDescriptionHelpFormatter, description = dedent('''", "Please do not mess up this text! -------------------------------- I have indented it exactly", "mess up this text! -------------------------------- I have indented it exactly the way I", "sys.argv[0], formatter_class = argparse.RawDescriptionHelpFormatter, description = dedent(''' Please do not mess up this", "have indented it exactly the way I want it '''), epilog = \"Contact:<EMAIL>\"", "as indata,\\ kwargs[\"ofile\"] as odata: for line in indata: odata.write(line) if __name__ ==", "from textwrap import dedent def main(kwargs): with kwargs[\"infile\"] as indata,\\ kwargs[\"ofile\"] as odata:", "def main(kwargs): with kwargs[\"infile\"] as indata,\\ kwargs[\"ofile\"] as odata: for line in indata:", "odata: for line in indata: odata.write(line) if __name__ == \"__main__\": parser = argparse.ArgumentParser(", "indata: odata.write(line) if __name__ == \"__main__\": parser = argparse.ArgumentParser( prog = \"argparse_example\", #", "-------------------------------- I have indented it exactly the way I want it '''), epilog", "epilog = \"Contact:<EMAIL>\" ) parser.add_argument(\"infile\", nargs=\"?\", type=argparse.FileType(\"r\"), default=sys.stdin) parser.add_argument(\"ofile\", nargs=\"?\", type=argparse.FileType(\"w\"), default=sys.stdout) args", "in indata: odata.write(line) if __name__ == \"__main__\": parser = argparse.ArgumentParser( prog = \"argparse_example\",", "line in indata: odata.write(line) if __name__ == \"__main__\": parser = argparse.ArgumentParser( prog =", "I want it '''), epilog = \"Contact:<EMAIL>\" ) parser.add_argument(\"infile\", nargs=\"?\", type=argparse.FileType(\"r\"), default=sys.stdin) parser.add_argument(\"ofile\",", "== \"__main__\": parser = argparse.ArgumentParser( prog = \"argparse_example\", # default is sys.argv[0], formatter_class", "import sys import argparse from textwrap import dedent def main(kwargs): with kwargs[\"infile\"] as", "is sys.argv[0], formatter_class = argparse.RawDescriptionHelpFormatter, description = dedent(''' Please do not mess up", "textwrap import dedent def main(kwargs): with kwargs[\"infile\"] as indata,\\ kwargs[\"ofile\"] as odata: for", "dedent(''' Please do not mess up this text! -------------------------------- I have indented it", "exactly the way I want it '''), epilog = \"Contact:<EMAIL>\" ) parser.add_argument(\"infile\", nargs=\"?\",", "description = dedent(''' Please do not mess up this text! -------------------------------- I have", "kwargs[\"infile\"] as indata,\\ kwargs[\"ofile\"] as odata: for line in indata: odata.write(line) if __name__", "text! -------------------------------- I have indented it exactly the way I want it '''),", "up this text! -------------------------------- I have indented it exactly the way I want", "= dedent(''' Please do not mess up this text! -------------------------------- I have indented", "as odata: for line in indata: odata.write(line) if __name__ == \"__main__\": parser =" ]
[ "import fits import logging try: import imageio except ImportError: imageio = None try:", "np.ndarray) return colaps def writefits(img: np.ndarray, outfn: Path): outfn = Path(outfn).expanduser() f =", "from scipy.io import loadmat except ImportError: loadmat = None def meanstack( infn: Path,", "int): key = slice(0, Navg) elif len(Navg) == 1: key = slice(0, Navg[0])", "KeyError: pass return img, ut1 def collapsestack(img: np.ndarray, key: slice, method: str) ->", "install scipy\") img = loadmat(infn) img = collapsestack(img[\"data\"].T, key, method) # matlab is", "img = np.rot90(img, k=f[\"/params\"][\"rotccw\"]) except KeyError: pass return img, ut1 def collapsestack(img: np.ndarray,", "raise ImportError(\"pip install scipy\") img = loadmat(infn) img = collapsestack(img[\"data\"].T, key, method) #", "else: raise ValueError(f\"not sure what you mean by Navg={Navg}\") # %% load images", "script to ingest a variety of files and average the specified frames then", "pass # %% orientation try: img = np.rot90(img, k=f[\"/params\"][\"rotccw\"]) except KeyError: pass return", "if h5py is None: raise ImportError(\"pip install h5py\") img, ut1 = _h5mean(infn, ut1,", "# mmap doesn't work with BZERO/BSCALE/BLANK with fits.open(infn, mode=\"readonly\", memmap=False) as f: img", "to load if isinstance(Navg, slice): key = Navg elif isinstance(Navg, int): key =", "FITS when reading in: PyFits, AstroPy, or ImageMagick is: IOError: Header missing END", "use in astrometry.net The error you might get from an ImageJ saved FITS", "method) return img, ut1 def _h5mean(fn: Path, ut1: datetime, key: slice, method: str)", "Path(outfn).expanduser() f = fits.PrimaryHDU(img) try: f.writeto(outfn, overwrite=False, checksum=True) # no close() print(\"writing\", outfn)", "is None: try: ut1 = f[\"/ut1_unix\"][key][0] except KeyError: pass # %% orientation try:", "def _h5mean(fn: Path, ut1: datetime, key: slice, method: str) -> tuple[np.ndarray, datetime]: with", "<reponame>scienceopen/astrometry<filename>src/astrometry_azel/io.py \"\"\" Image stack -> average -> write FITS Because ImageJ has been", "Because ImageJ has been a little buggy about writing FITS files, in particular", "elif infn.suffix == \".mat\": if loadmat is None: raise ImportError(\"pip install scipy\") img", "loadmat = None def meanstack( infn: Path, Navg: int, ut1: datetime = None,", "> 0 assert isinstance(colaps, np.ndarray) return colaps def writefits(img: np.ndarray, outfn: Path): outfn", "= _h5mean(infn, ut1, key, method) elif infn.suffix in (\".fits\", \".new\"): # mmap doesn't", "install imageio\") img = imageio.imread(infn, as_gray=True) if img.ndim in (3, 4) and img.shape[-1]", "f.writeto(outfn, overwrite=False, checksum=True) # no close() print(\"writing\", outfn) except OSError: logging.warning(f\"did not overwrite", "write FITS Because ImageJ has been a little buggy about writing FITS files,", "Path): outfn = Path(outfn).expanduser() f = fits.PrimaryHDU(img) try: f.writeto(outfn, overwrite=False, checksum=True) # no", "to improve efficiency with huge files \"\"\" if infn.suffix == \".h5\": if h5py", "1: key = slice(0, Navg[0]) elif len(Navg) == 2: key = slice(Navg[0], Navg[1])", "as np from datetime import datetime from astropy.io import fits import logging try:", "infn: Path, Navg: int, ut1: datetime = None, method: str = \"mean\" )", "by Navg={Navg}\") # %% load images \"\"\" some methods handled individually to improve", "is None: raise ImportError(\"pip install h5py\") img, ut1 = _h5mean(infn, ut1, key, method)", "ImportError: imageio = None try: import h5py except ImportError: h5py = None try:", "Path import numpy as np from datetime import datetime from astropy.io import fits", "# %% 3-D if method == \"mean\": func = np.mean elif method ==", "this quick script to ingest a variety of files and average the specified", "key = slice(0, Navg) elif len(Navg) == 1: key = slice(0, Navg[0]) elif", "== \".h5\": if h5py is None: raise ImportError(\"pip install h5py\") img, ut1 =", "loadmat is None: raise ImportError(\"pip install scipy\") img = loadmat(infn) img = collapsestack(img[\"data\"].T,", "method) elif infn.suffix == \".mat\": if loadmat is None: raise ImportError(\"pip install scipy\")", "= imageio.imread(infn, as_gray=True) if img.ndim in (3, 4) and img.shape[-1] == 3: #", "Navg[1]) else: raise ValueError(f\"not sure what you mean by Navg={Navg}\") # %% load", "are handled\") # %% 2-D if img.ndim == 2: return img # %%", "-> average -> write FITS Because ImageJ has been a little buggy about", "None: try: ut1 = f[\"/ut1_unix\"][key][0] except KeyError: pass # %% orientation try: img", "logging try: import imageio except ImportError: imageio = None try: import h5py except", "img = collapsestack(img, key, method) return img, ut1 def _h5mean(fn: Path, ut1: datetime,", "slice(0, Navg[0]) elif len(Navg) == 2: key = slice(Navg[0], Navg[1]) else: raise ValueError(f\"not", "= slice(Navg[0], Navg[1]) else: raise ValueError(f\"not sure what you mean by Navg={Navg}\") #", "def writefits(img: np.ndarray, outfn: Path): outfn = Path(outfn).expanduser() f = fits.PrimaryHDU(img) try: f.writeto(outfn,", "or ImageMagick is: IOError: Header missing END card. \"\"\" from __future__ import annotations", "FITS files, in particular the header that astrometry.net then crashes on, we wrote", "in (2, 3, 4): raise ValueError(\"only 2D, 3D, or 4D image stacks are", "_h5mean(infn, ut1, key, method) elif infn.suffix in (\".fits\", \".new\"): # mmap doesn't work", "h5py.File(fn, \"r\") as f: try: latlon = (f[\"/sensorloc\"][\"glat\"], f[\"/sensorloc\"][\"glon\"]) except KeyError: try: latlon", "imageio is None: raise ImportError(\"pip install imageio\") img = imageio.imread(infn, as_gray=True) if img.ndim", "OSError: logging.warning(f\"did not overwrite existing {outfn}\") def readh5coord(fn: Path) -> tuple[float, float]: if", "writing FITS files, in particular the header that astrometry.net then crashes on, we", "2-D if img.ndim == 2: return img # %% 3-D if method ==", "= f[\"/ut1_unix\"][key][0] except KeyError: pass # %% orientation try: img = np.rot90(img, k=f[\"/params\"][\"rotccw\"])", "h5py is None: raise ImportError(\"pip install h5py\") img, ut1 = _h5mean(infn, ut1, key,", "= np.mean elif method == \"median\": func = np.median else: raise TypeError(f\"unknown method", "assert colaps.ndim > 0 assert isinstance(colaps, np.ndarray) return colaps def writefits(img: np.ndarray, outfn:", "isinstance(Navg, int): key = slice(0, Navg) elif len(Navg) == 1: key = slice(0,", "FITS Because ImageJ has been a little buggy about writing FITS files, in", "with h5py.File(fn, \"r\") as f: try: latlon = (f[\"/sensorloc\"][\"glat\"], f[\"/sensorloc\"][\"glon\"]) except KeyError: try:", "if infn.suffix == \".h5\": if h5py is None: raise ImportError(\"pip install h5py\") img,", "\"mean\" ) -> tuple[np.ndarray, datetime]: infn = Path(infn).expanduser().resolve(strict=True) # %% parse indicies to", "return img # %% 3-D if method == \"mean\": func = np.mean elif", "crashes on, we wrote this quick script to ingest a variety of files", "logging.warning(f\"did not overwrite existing {outfn}\") def readh5coord(fn: Path) -> tuple[float, float]: if not", "wrote this quick script to ingest a variety of files and average the", "latlon = (f[\"/sensorloc\"][\"glat\"], f[\"/sensorloc\"][\"glon\"]) except KeyError: try: latlon = f[\"/lla\"][:2] except KeyError: return", "get from an ImageJ saved FITS when reading in: PyFits, AstroPy, or ImageMagick", "= None try: from scipy.io import loadmat except ImportError: loadmat = None def", "mode=\"readonly\", memmap=False) as f: img = collapsestack(f[0].data, key, method) elif infn.suffix == \".mat\":", "None try: import h5py except ImportError: h5py = None try: from scipy.io import", "overwrite=False, checksum=True) # no close() print(\"writing\", outfn) except OSError: logging.warning(f\"did not overwrite existing", "def collapsestack(img: np.ndarray, key: slice, method: str) -> np.ndarray: if img.ndim not in", "a variety of files and average the specified frames then write a FITS.", "what you mean by Navg={Navg}\") # %% load images \"\"\" some methods handled", "to ingest a variety of files and average the specified frames then write", "checksum=True) # no close() print(\"writing\", outfn) except OSError: logging.warning(f\"did not overwrite existing {outfn}\")", "datetime]: with h5py.File(fn, \"r\") as f: img = collapsestack(f[\"/rawimg\"], key, method) # %%", "ImageJ saved FITS when reading in: PyFits, AstroPy, or ImageMagick is: IOError: Header", "else: # .tif etc. if imageio is None: raise ImportError(\"pip install imageio\") img", "if not fn.suffix == \".h5\": return None with h5py.File(fn, \"r\") as f: try:", "h5py except ImportError: h5py = None try: from scipy.io import loadmat except ImportError:", "The reason we average a selected stack of images is to reduce the", "fits.open(infn, mode=\"readonly\", memmap=False) as f: img = collapsestack(f[0].data, key, method) elif infn.suffix ==", "%% time if ut1 is None: try: ut1 = f[\"/ut1_unix\"][key][0] except KeyError: pass", "if loadmat is None: raise ImportError(\"pip install scipy\") img = loadmat(infn) img =", "import logging try: import imageio except ImportError: imageio = None try: import h5py", "then write a FITS. The reason we average a selected stack of images", "import annotations from pathlib import Path import numpy as np from datetime import", "key, method) elif infn.suffix in (\".fits\", \".new\"): # mmap doesn't work with BZERO/BSCALE/BLANK", "Image stack -> average -> write FITS Because ImageJ has been a little", "datetime import datetime from astropy.io import fits import logging try: import imageio except", "2: return img # %% 3-D if method == \"mean\": func = np.mean", "assume RGB img = collapsestack(img, key, method) return img, ut1 def _h5mean(fn: Path,", "fortran order else: # .tif etc. if imageio is None: raise ImportError(\"pip install", "image stacks are handled\") # %% 2-D if img.ndim == 2: return img", "some methods handled individually to improve efficiency with huge files \"\"\" if infn.suffix", "BZERO/BSCALE/BLANK with fits.open(infn, mode=\"readonly\", memmap=False) as f: img = collapsestack(f[0].data, key, method) elif", "== 1: key = slice(0, Navg[0]) elif len(Navg) == 2: key = slice(Navg[0],", "ut1, key, method) elif infn.suffix in (\".fits\", \".new\"): # mmap doesn't work with", "a little buggy about writing FITS files, in particular the header that astrometry.net", "images is to reduce the noise for use in astrometry.net The error you", "RGB img = collapsestack(img, key, method) return img, ut1 def _h5mean(fn: Path, ut1:", "\"\"\" from __future__ import annotations from pathlib import Path import numpy as np", "from an ImageJ saved FITS when reading in: PyFits, AstroPy, or ImageMagick is:", "an ImageJ saved FITS when reading in: PyFits, AstroPy, or ImageMagick is: IOError:", "from __future__ import annotations from pathlib import Path import numpy as np from", "key: slice, method: str) -> tuple[np.ndarray, datetime]: with h5py.File(fn, \"r\") as f: img", "key, method) # matlab is fortran order else: # .tif etc. if imageio", "of images is to reduce the noise for use in astrometry.net The error", "None try: from scipy.io import loadmat except ImportError: loadmat = None def meanstack(", "as_gray=True) if img.ndim in (3, 4) and img.shape[-1] == 3: # assume RGB", "img = collapsestack(f[\"/rawimg\"], key, method) # %% time if ut1 is None: try:", "infn.suffix == \".h5\": if h5py is None: raise ImportError(\"pip install h5py\") img, ut1", "_h5mean(fn: Path, ut1: datetime, key: slice, method: str) -> tuple[np.ndarray, datetime]: with h5py.File(fn,", "\".h5\": return None with h5py.File(fn, \"r\") as f: try: latlon = (f[\"/sensorloc\"][\"glat\"], f[\"/sensorloc\"][\"glon\"])", "float]: if not fn.suffix == \".h5\": return None with h5py.File(fn, \"r\") as f:", "(\".fits\", \".new\"): # mmap doesn't work with BZERO/BSCALE/BLANK with fits.open(infn, mode=\"readonly\", memmap=False) as", "from pathlib import Path import numpy as np from datetime import datetime from", "of files and average the specified frames then write a FITS. The reason", "# assume RGB img = collapsestack(img, key, method) return img, ut1 def _h5mean(fn:", "outfn = Path(outfn).expanduser() f = fits.PrimaryHDU(img) try: f.writeto(outfn, overwrite=False, checksum=True) # no close()", "files, in particular the header that astrometry.net then crashes on, we wrote this", "len(Navg) == 2: key = slice(Navg[0], Navg[1]) else: raise ValueError(f\"not sure what you", "not fn.suffix == \".h5\": return None with h5py.File(fn, \"r\") as f: try: latlon", "from astropy.io import fits import logging try: import imageio except ImportError: imageio =", "in (\".fits\", \".new\"): # mmap doesn't work with BZERO/BSCALE/BLANK with fits.open(infn, mode=\"readonly\", memmap=False)", "handled individually to improve efficiency with huge files \"\"\" if infn.suffix == \".h5\":", "try: f.writeto(outfn, overwrite=False, checksum=True) # no close() print(\"writing\", outfn) except OSError: logging.warning(f\"did not", "imageio = None try: import h5py except ImportError: h5py = None try: from", "no close() print(\"writing\", outfn) except OSError: logging.warning(f\"did not overwrite existing {outfn}\") def readh5coord(fn:", "np.median else: raise TypeError(f\"unknown method {method}\") colaps = func(img[key, ...], axis=0).astype(img.dtype) assert colaps.ndim", "# .tif etc. if imageio is None: raise ImportError(\"pip install imageio\") img =", "def readh5coord(fn: Path) -> tuple[float, float]: if not fn.suffix == \".h5\": return None", "= slice(0, Navg) elif len(Navg) == 1: key = slice(0, Navg[0]) elif len(Navg)", "error you might get from an ImageJ saved FITS when reading in: PyFits,", "END card. \"\"\" from __future__ import annotations from pathlib import Path import numpy", "colaps = func(img[key, ...], axis=0).astype(img.dtype) assert colaps.ndim > 0 assert isinstance(colaps, np.ndarray) return", "ut1 is None: try: ut1 = f[\"/ut1_unix\"][key][0] except KeyError: pass # %% orientation", "# %% parse indicies to load if isinstance(Navg, slice): key = Navg elif", "specified frames then write a FITS. The reason we average a selected stack", "method == \"median\": func = np.median else: raise TypeError(f\"unknown method {method}\") colaps =", "method {method}\") colaps = func(img[key, ...], axis=0).astype(img.dtype) assert colaps.ndim > 0 assert isinstance(colaps,", "as f: img = collapsestack(f[\"/rawimg\"], key, method) # %% time if ut1 is", "slice(0, Navg) elif len(Navg) == 1: key = slice(0, Navg[0]) elif len(Navg) ==", "%% 2-D if img.ndim == 2: return img # %% 3-D if method", "-> tuple[np.ndarray, datetime]: infn = Path(infn).expanduser().resolve(strict=True) # %% parse indicies to load if", "key = slice(Navg[0], Navg[1]) else: raise ValueError(f\"not sure what you mean by Navg={Navg}\")", "work with BZERO/BSCALE/BLANK with fits.open(infn, mode=\"readonly\", memmap=False) as f: img = collapsestack(f[0].data, key,", "assert isinstance(colaps, np.ndarray) return colaps def writefits(img: np.ndarray, outfn: Path): outfn = Path(outfn).expanduser()", "np.ndarray, outfn: Path): outfn = Path(outfn).expanduser() f = fits.PrimaryHDU(img) try: f.writeto(outfn, overwrite=False, checksum=True)", "None def meanstack( infn: Path, Navg: int, ut1: datetime = None, method: str", "IOError: Header missing END card. \"\"\" from __future__ import annotations from pathlib import", "buggy about writing FITS files, in particular the header that astrometry.net then crashes", "files and average the specified frames then write a FITS. The reason we", "# no close() print(\"writing\", outfn) except OSError: logging.warning(f\"did not overwrite existing {outfn}\") def", "to reduce the noise for use in astrometry.net The error you might get", "with BZERO/BSCALE/BLANK with fits.open(infn, mode=\"readonly\", memmap=False) as f: img = collapsestack(f[0].data, key, method)", "# %% orientation try: img = np.rot90(img, k=f[\"/params\"][\"rotccw\"]) except KeyError: pass return img,", "fits import logging try: import imageio except ImportError: imageio = None try: import", "img = loadmat(infn) img = collapsestack(img[\"data\"].T, key, method) # matlab is fortran order", "try: from scipy.io import loadmat except ImportError: loadmat = None def meanstack( infn:", "ImportError: loadmat = None def meanstack( infn: Path, Navg: int, ut1: datetime =", "2: key = slice(Navg[0], Navg[1]) else: raise ValueError(f\"not sure what you mean by", "with huge files \"\"\" if infn.suffix == \".h5\": if h5py is None: raise", "np.ndarray: if img.ndim not in (2, 3, 4): raise ValueError(\"only 2D, 3D, or", "%% 3-D if method == \"mean\": func = np.mean elif method == \"median\":", "\".h5\": if h5py is None: raise ImportError(\"pip install h5py\") img, ut1 = _h5mean(infn,", "as f: img = collapsestack(f[0].data, key, method) elif infn.suffix == \".mat\": if loadmat", "mean by Navg={Navg}\") # %% load images \"\"\" some methods handled individually to", "f: img = collapsestack(f[\"/rawimg\"], key, method) # %% time if ut1 is None:", "close() print(\"writing\", outfn) except OSError: logging.warning(f\"did not overwrite existing {outfn}\") def readh5coord(fn: Path)", ".tif etc. if imageio is None: raise ImportError(\"pip install imageio\") img = imageio.imread(infn,", "ImportError(\"pip install imageio\") img = imageio.imread(infn, as_gray=True) if img.ndim in (3, 4) and", "and img.shape[-1] == 3: # assume RGB img = collapsestack(img, key, method) return", "datetime]: infn = Path(infn).expanduser().resolve(strict=True) # %% parse indicies to load if isinstance(Navg, slice):", "collapsestack(img, key, method) return img, ut1 def _h5mean(fn: Path, ut1: datetime, key: slice,", "img, ut1 = _h5mean(infn, ut1, key, method) elif infn.suffix in (\".fits\", \".new\"): #", "stack of images is to reduce the noise for use in astrometry.net The", "elif infn.suffix in (\".fits\", \".new\"): # mmap doesn't work with BZERO/BSCALE/BLANK with fits.open(infn,", "return None with h5py.File(fn, \"r\") as f: try: latlon = (f[\"/sensorloc\"][\"glat\"], f[\"/sensorloc\"][\"glon\"]) except", "3D, or 4D image stacks are handled\") # %% 2-D if img.ndim ==", "infn = Path(infn).expanduser().resolve(strict=True) # %% parse indicies to load if isinstance(Navg, slice): key", "ImportError(\"pip install scipy\") img = loadmat(infn) img = collapsestack(img[\"data\"].T, key, method) # matlab", "\"r\") as f: try: latlon = (f[\"/sensorloc\"][\"glat\"], f[\"/sensorloc\"][\"glon\"]) except KeyError: try: latlon =", "# matlab is fortran order else: # .tif etc. if imageio is None:", "try: img = np.rot90(img, k=f[\"/params\"][\"rotccw\"]) except KeyError: pass return img, ut1 def collapsestack(img:", "ValueError(\"only 2D, 3D, or 4D image stacks are handled\") # %% 2-D if", "try: latlon = (f[\"/sensorloc\"][\"glat\"], f[\"/sensorloc\"][\"glon\"]) except KeyError: try: latlon = f[\"/lla\"][:2] except KeyError:", "slice, method: str) -> np.ndarray: if img.ndim not in (2, 3, 4): raise", "datetime, key: slice, method: str) -> tuple[np.ndarray, datetime]: with h5py.File(fn, \"r\") as f:", "int, ut1: datetime = None, method: str = \"mean\" ) -> tuple[np.ndarray, datetime]:", "None with h5py.File(fn, \"r\") as f: try: latlon = (f[\"/sensorloc\"][\"glat\"], f[\"/sensorloc\"][\"glon\"]) except KeyError:", "key = slice(0, Navg[0]) elif len(Navg) == 2: key = slice(Navg[0], Navg[1]) else:", "sure what you mean by Navg={Navg}\") # %% load images \"\"\" some methods", "in astrometry.net The error you might get from an ImageJ saved FITS when", "readh5coord(fn: Path) -> tuple[float, float]: if not fn.suffix == \".h5\": return None with", "raise ValueError(\"only 2D, 3D, or 4D image stacks are handled\") # %% 2-D", "f[\"/ut1_unix\"][key][0] except KeyError: pass # %% orientation try: img = np.rot90(img, k=f[\"/params\"][\"rotccw\"]) except", "if imageio is None: raise ImportError(\"pip install imageio\") img = imageio.imread(infn, as_gray=True) if", "import loadmat except ImportError: loadmat = None def meanstack( infn: Path, Navg: int,", "raise ImportError(\"pip install h5py\") img, ut1 = _h5mean(infn, ut1, key, method) elif infn.suffix", "a FITS. The reason we average a selected stack of images is to", "== \".mat\": if loadmat is None: raise ImportError(\"pip install scipy\") img = loadmat(infn)", "\"\"\" if infn.suffix == \".h5\": if h5py is None: raise ImportError(\"pip install h5py\")", "None: raise ImportError(\"pip install imageio\") img = imageio.imread(infn, as_gray=True) if img.ndim in (3,", "is to reduce the noise for use in astrometry.net The error you might", "= slice(0, Navg[0]) elif len(Navg) == 2: key = slice(Navg[0], Navg[1]) else: raise", "improve efficiency with huge files \"\"\" if infn.suffix == \".h5\": if h5py is", "infn.suffix in (\".fits\", \".new\"): # mmap doesn't work with BZERO/BSCALE/BLANK with fits.open(infn, mode=\"readonly\",", "str = \"mean\" ) -> tuple[np.ndarray, datetime]: infn = Path(infn).expanduser().resolve(strict=True) # %% parse", "load images \"\"\" some methods handled individually to improve efficiency with huge files", "else: raise TypeError(f\"unknown method {method}\") colaps = func(img[key, ...], axis=0).astype(img.dtype) assert colaps.ndim >", "= func(img[key, ...], axis=0).astype(img.dtype) assert colaps.ndim > 0 assert isinstance(colaps, np.ndarray) return colaps", "saved FITS when reading in: PyFits, AstroPy, or ImageMagick is: IOError: Header missing", "tuple[np.ndarray, datetime]: infn = Path(infn).expanduser().resolve(strict=True) # %% parse indicies to load if isinstance(Navg,", "in (3, 4) and img.shape[-1] == 3: # assume RGB img = collapsestack(img,", "loadmat except ImportError: loadmat = None def meanstack( infn: Path, Navg: int, ut1:", "if img.ndim == 2: return img # %% 3-D if method == \"mean\":", "\"\"\" Image stack -> average -> write FITS Because ImageJ has been a", "= \"mean\" ) -> tuple[np.ndarray, datetime]: infn = Path(infn).expanduser().resolve(strict=True) # %% parse indicies", "pass return img, ut1 def collapsestack(img: np.ndarray, key: slice, method: str) -> np.ndarray:", "(f[\"/sensorloc\"][\"glat\"], f[\"/sensorloc\"][\"glon\"]) except KeyError: try: latlon = f[\"/lla\"][:2] except KeyError: return None return", "= Path(outfn).expanduser() f = fits.PrimaryHDU(img) try: f.writeto(outfn, overwrite=False, checksum=True) # no close() print(\"writing\",", "etc. if imageio is None: raise ImportError(\"pip install imageio\") img = imageio.imread(infn, as_gray=True)", "-> tuple[np.ndarray, datetime]: with h5py.File(fn, \"r\") as f: img = collapsestack(f[\"/rawimg\"], key, method)", "when reading in: PyFits, AstroPy, or ImageMagick is: IOError: Header missing END card.", "elif len(Navg) == 1: key = slice(0, Navg[0]) elif len(Navg) == 2: key", "collapsestack(f[0].data, key, method) elif infn.suffix == \".mat\": if loadmat is None: raise ImportError(\"pip", "== \"median\": func = np.median else: raise TypeError(f\"unknown method {method}\") colaps = func(img[key,", "\"mean\": func = np.mean elif method == \"median\": func = np.median else: raise", "average -> write FITS Because ImageJ has been a little buggy about writing", "about writing FITS files, in particular the header that astrometry.net then crashes on,", "method: str) -> np.ndarray: if img.ndim not in (2, 3, 4): raise ValueError(\"only", "Header missing END card. \"\"\" from __future__ import annotations from pathlib import Path", "imageio.imread(infn, as_gray=True) if img.ndim in (3, 4) and img.shape[-1] == 3: # assume", "img = collapsestack(f[0].data, key, method) elif infn.suffix == \".mat\": if loadmat is None:", "f: try: latlon = (f[\"/sensorloc\"][\"glat\"], f[\"/sensorloc\"][\"glon\"]) except KeyError: try: latlon = f[\"/lla\"][:2] except", "== 3: # assume RGB img = collapsestack(img, key, method) return img, ut1", "collapsestack(img: np.ndarray, key: slice, method: str) -> np.ndarray: if img.ndim not in (2,", "= collapsestack(f[\"/rawimg\"], key, method) # %% time if ut1 is None: try: ut1", "you mean by Navg={Navg}\") # %% load images \"\"\" some methods handled individually", "ImageJ has been a little buggy about writing FITS files, in particular the", "if img.ndim in (3, 4) and img.shape[-1] == 3: # assume RGB img", "img = collapsestack(img[\"data\"].T, key, method) # matlab is fortran order else: # .tif", "Path) -> tuple[float, float]: if not fn.suffix == \".h5\": return None with h5py.File(fn,", "annotations from pathlib import Path import numpy as np from datetime import datetime", "pathlib import Path import numpy as np from datetime import datetime from astropy.io", "= Navg elif isinstance(Navg, int): key = slice(0, Navg) elif len(Navg) == 1:", "%% load images \"\"\" some methods handled individually to improve efficiency with huge", "func = np.median else: raise TypeError(f\"unknown method {method}\") colaps = func(img[key, ...], axis=0).astype(img.dtype)", "Navg elif isinstance(Navg, int): key = slice(0, Navg) elif len(Navg) == 1: key", "__future__ import annotations from pathlib import Path import numpy as np from datetime", "ut1 = _h5mean(infn, ut1, key, method) elif infn.suffix in (\".fits\", \".new\"): # mmap", "Navg={Navg}\") # %% load images \"\"\" some methods handled individually to improve efficiency", "mmap doesn't work with BZERO/BSCALE/BLANK with fits.open(infn, mode=\"readonly\", memmap=False) as f: img =", "(2, 3, 4): raise ValueError(\"only 2D, 3D, or 4D image stacks are handled\")", "= np.rot90(img, k=f[\"/params\"][\"rotccw\"]) except KeyError: pass return img, ut1 def collapsestack(img: np.ndarray, key:", "f[\"/sensorloc\"][\"glon\"]) except KeyError: try: latlon = f[\"/lla\"][:2] except KeyError: return None return latlon", "install h5py\") img, ut1 = _h5mean(infn, ut1, key, method) elif infn.suffix in (\".fits\",", "-> tuple[float, float]: if not fn.suffix == \".h5\": return None with h5py.File(fn, \"r\")", "\".new\"): # mmap doesn't work with BZERO/BSCALE/BLANK with fits.open(infn, mode=\"readonly\", memmap=False) as f:", "ImageMagick is: IOError: Header missing END card. \"\"\" from __future__ import annotations from", "Navg) elif len(Navg) == 1: key = slice(0, Navg[0]) elif len(Navg) == 2:", "k=f[\"/params\"][\"rotccw\"]) except KeyError: pass return img, ut1 def collapsestack(img: np.ndarray, key: slice, method:", "3: # assume RGB img = collapsestack(img, key, method) return img, ut1 def", "order else: # .tif etc. if imageio is None: raise ImportError(\"pip install imageio\")", "a selected stack of images is to reduce the noise for use in", "that astrometry.net then crashes on, we wrote this quick script to ingest a", "individually to improve efficiency with huge files \"\"\" if infn.suffix == \".h5\": if", "f: img = collapsestack(f[0].data, key, method) elif infn.suffix == \".mat\": if loadmat is", "datetime from astropy.io import fits import logging try: import imageio except ImportError: imageio", "raise ValueError(f\"not sure what you mean by Navg={Navg}\") # %% load images \"\"\"", "str) -> np.ndarray: if img.ndim not in (2, 3, 4): raise ValueError(\"only 2D,", "%% parse indicies to load if isinstance(Navg, slice): key = Navg elif isinstance(Navg,", "np.ndarray, key: slice, method: str) -> np.ndarray: if img.ndim not in (2, 3,", "2D, 3D, or 4D image stacks are handled\") # %% 2-D if img.ndim", "np from datetime import datetime from astropy.io import fits import logging try: import", "handled\") # %% 2-D if img.ndim == 2: return img # %% 3-D", "key, method) return img, ut1 def _h5mean(fn: Path, ut1: datetime, key: slice, method:", "collapsestack(f[\"/rawimg\"], key, method) # %% time if ut1 is None: try: ut1 =", "return img, ut1 def collapsestack(img: np.ndarray, key: slice, method: str) -> np.ndarray: if", "has been a little buggy about writing FITS files, in particular the header", "is fortran order else: # .tif etc. if imageio is None: raise ImportError(\"pip", "load if isinstance(Navg, slice): key = Navg elif isinstance(Navg, int): key = slice(0,", "= collapsestack(img[\"data\"].T, key, method) # matlab is fortran order else: # .tif etc.", "ut1: datetime = None, method: str = \"mean\" ) -> tuple[np.ndarray, datetime]: infn", "\"\"\" some methods handled individually to improve efficiency with huge files \"\"\" if", "you might get from an ImageJ saved FITS when reading in: PyFits, AstroPy,", "# %% time if ut1 is None: try: ut1 = f[\"/ut1_unix\"][key][0] except KeyError:", "= collapsestack(img, key, method) return img, ut1 def _h5mean(fn: Path, ut1: datetime, key:", "astrometry.net then crashes on, we wrote this quick script to ingest a variety", "len(Navg) == 1: key = slice(0, Navg[0]) elif len(Navg) == 2: key =", "Path(infn).expanduser().resolve(strict=True) # %% parse indicies to load if isinstance(Navg, slice): key = Navg", "infn.suffix == \".mat\": if loadmat is None: raise ImportError(\"pip install scipy\") img =", "KeyError: pass # %% orientation try: img = np.rot90(img, k=f[\"/params\"][\"rotccw\"]) except KeyError: pass", "= np.median else: raise TypeError(f\"unknown method {method}\") colaps = func(img[key, ...], axis=0).astype(img.dtype) assert", "for use in astrometry.net The error you might get from an ImageJ saved", "h5py.File(fn, \"r\") as f: img = collapsestack(f[\"/rawimg\"], key, method) # %% time if", "img.shape[-1] == 3: # assume RGB img = collapsestack(img, key, method) return img,", "isinstance(colaps, np.ndarray) return colaps def writefits(img: np.ndarray, outfn: Path): outfn = Path(outfn).expanduser() f", "except ImportError: loadmat = None def meanstack( infn: Path, Navg: int, ut1: datetime", "h5py = None try: from scipy.io import loadmat except ImportError: loadmat = None", "been a little buggy about writing FITS files, in particular the header that", "write a FITS. The reason we average a selected stack of images is", "method) # %% time if ut1 is None: try: ut1 = f[\"/ut1_unix\"][key][0] except", "particular the header that astrometry.net then crashes on, we wrote this quick script", "doesn't work with BZERO/BSCALE/BLANK with fits.open(infn, mode=\"readonly\", memmap=False) as f: img = collapsestack(f[0].data,", "import Path import numpy as np from datetime import datetime from astropy.io import", "raise TypeError(f\"unknown method {method}\") colaps = func(img[key, ...], axis=0).astype(img.dtype) assert colaps.ndim > 0", "= None def meanstack( infn: Path, Navg: int, ut1: datetime = None, method:", "ImportError: h5py = None try: from scipy.io import loadmat except ImportError: loadmat =", "ut1: datetime, key: slice, method: str) -> tuple[np.ndarray, datetime]: with h5py.File(fn, \"r\") as", "import imageio except ImportError: imageio = None try: import h5py except ImportError: h5py", "imageio except ImportError: imageio = None try: import h5py except ImportError: h5py =", "orientation try: img = np.rot90(img, k=f[\"/params\"][\"rotccw\"]) except KeyError: pass return img, ut1 def", "might get from an ImageJ saved FITS when reading in: PyFits, AstroPy, or", "method) elif infn.suffix in (\".fits\", \".new\"): # mmap doesn't work with BZERO/BSCALE/BLANK with", "key, method) # %% time if ut1 is None: try: ut1 = f[\"/ut1_unix\"][key][0]", "import datetime from astropy.io import fits import logging try: import imageio except ImportError:", "print(\"writing\", outfn) except OSError: logging.warning(f\"did not overwrite existing {outfn}\") def readh5coord(fn: Path) ->", "huge files \"\"\" if infn.suffix == \".h5\": if h5py is None: raise ImportError(\"pip", "if isinstance(Navg, slice): key = Navg elif isinstance(Navg, int): key = slice(0, Navg)", "Navg: int, ut1: datetime = None, method: str = \"mean\" ) -> tuple[np.ndarray,", "key = Navg elif isinstance(Navg, int): key = slice(0, Navg) elif len(Navg) ==", "in: PyFits, AstroPy, or ImageMagick is: IOError: Header missing END card. \"\"\" from", "if method == \"mean\": func = np.mean elif method == \"median\": func =", "stack -> average -> write FITS Because ImageJ has been a little buggy", "is None: raise ImportError(\"pip install scipy\") img = loadmat(infn) img = collapsestack(img[\"data\"].T, key,", "from datetime import datetime from astropy.io import fits import logging try: import imageio", "def meanstack( infn: Path, Navg: int, ut1: datetime = None, method: str =", "\".mat\": if loadmat is None: raise ImportError(\"pip install scipy\") img = loadmat(infn) img", "ingest a variety of files and average the specified frames then write a", "slice): key = Navg elif isinstance(Navg, int): key = slice(0, Navg) elif len(Navg)", "4): raise ValueError(\"only 2D, 3D, or 4D image stacks are handled\") # %%", "except KeyError: pass # %% orientation try: img = np.rot90(img, k=f[\"/params\"][\"rotccw\"]) except KeyError:", "images \"\"\" some methods handled individually to improve efficiency with huge files \"\"\"", "frames then write a FITS. The reason we average a selected stack of", "func(img[key, ...], axis=0).astype(img.dtype) assert colaps.ndim > 0 assert isinstance(colaps, np.ndarray) return colaps def", "except OSError: logging.warning(f\"did not overwrite existing {outfn}\") def readh5coord(fn: Path) -> tuple[float, float]:", "we wrote this quick script to ingest a variety of files and average", "efficiency with huge files \"\"\" if infn.suffix == \".h5\": if h5py is None:", "img, ut1 def collapsestack(img: np.ndarray, key: slice, method: str) -> np.ndarray: if img.ndim", "colaps def writefits(img: np.ndarray, outfn: Path): outfn = Path(outfn).expanduser() f = fits.PrimaryHDU(img) try:", "3-D if method == \"mean\": func = np.mean elif method == \"median\": func", "ValueError(f\"not sure what you mean by Navg={Navg}\") # %% load images \"\"\" some", "ut1 def collapsestack(img: np.ndarray, key: slice, method: str) -> np.ndarray: if img.ndim not", "memmap=False) as f: img = collapsestack(f[0].data, key, method) elif infn.suffix == \".mat\": if", "not overwrite existing {outfn}\") def readh5coord(fn: Path) -> tuple[float, float]: if not fn.suffix", "FITS. The reason we average a selected stack of images is to reduce", "indicies to load if isinstance(Navg, slice): key = Navg elif isinstance(Navg, int): key", "img, ut1 def _h5mean(fn: Path, ut1: datetime, key: slice, method: str) -> tuple[np.ndarray,", "with h5py.File(fn, \"r\") as f: img = collapsestack(f[\"/rawimg\"], key, method) # %% time", "func = np.mean elif method == \"median\": func = np.median else: raise TypeError(f\"unknown", "%% orientation try: img = np.rot90(img, k=f[\"/params\"][\"rotccw\"]) except KeyError: pass return img, ut1", "missing END card. \"\"\" from __future__ import annotations from pathlib import Path import", "ut1 def _h5mean(fn: Path, ut1: datetime, key: slice, method: str) -> tuple[np.ndarray, datetime]:", "import numpy as np from datetime import datetime from astropy.io import fits import", "in particular the header that astrometry.net then crashes on, we wrote this quick", "files \"\"\" if infn.suffix == \".h5\": if h5py is None: raise ImportError(\"pip install", "average the specified frames then write a FITS. The reason we average a", "variety of files and average the specified frames then write a FITS. The", "loadmat(infn) img = collapsestack(img[\"data\"].T, key, method) # matlab is fortran order else: #", "overwrite existing {outfn}\") def readh5coord(fn: Path) -> tuple[float, float]: if not fn.suffix ==", "4) and img.shape[-1] == 3: # assume RGB img = collapsestack(img, key, method)", "The error you might get from an ImageJ saved FITS when reading in:", "meanstack( infn: Path, Navg: int, ut1: datetime = None, method: str = \"mean\"", "key: slice, method: str) -> np.ndarray: if img.ndim not in (2, 3, 4):", "imageio\") img = imageio.imread(infn, as_gray=True) if img.ndim in (3, 4) and img.shape[-1] ==", "\"r\") as f: img = collapsestack(f[\"/rawimg\"], key, method) # %% time if ut1", "with fits.open(infn, mode=\"readonly\", memmap=False) as f: img = collapsestack(f[0].data, key, method) elif infn.suffix", "try: import imageio except ImportError: imageio = None try: import h5py except ImportError:", "= None, method: str = \"mean\" ) -> tuple[np.ndarray, datetime]: infn = Path(infn).expanduser().resolve(strict=True)", "outfn: Path): outfn = Path(outfn).expanduser() f = fits.PrimaryHDU(img) try: f.writeto(outfn, overwrite=False, checksum=True) #", "return img, ut1 def _h5mean(fn: Path, ut1: datetime, key: slice, method: str) ->", "quick script to ingest a variety of files and average the specified frames", "-> np.ndarray: if img.ndim not in (2, 3, 4): raise ValueError(\"only 2D, 3D,", "import h5py except ImportError: h5py = None try: from scipy.io import loadmat except", "the specified frames then write a FITS. The reason we average a selected", "except ImportError: imageio = None try: import h5py except ImportError: h5py = None", "tuple[np.ndarray, datetime]: with h5py.File(fn, \"r\") as f: img = collapsestack(f[\"/rawimg\"], key, method) #", "collapsestack(img[\"data\"].T, key, method) # matlab is fortran order else: # .tif etc. if", "3, 4): raise ValueError(\"only 2D, 3D, or 4D image stacks are handled\") #", "None: raise ImportError(\"pip install h5py\") img, ut1 = _h5mean(infn, ut1, key, method) elif", "method: str) -> tuple[np.ndarray, datetime]: with h5py.File(fn, \"r\") as f: img = collapsestack(f[\"/rawimg\"],", "str) -> tuple[np.ndarray, datetime]: with h5py.File(fn, \"r\") as f: img = collapsestack(f[\"/rawimg\"], key,", "# %% 2-D if img.ndim == 2: return img # %% 3-D if", "fn.suffix == \".h5\": return None with h5py.File(fn, \"r\") as f: try: latlon =", "as f: try: latlon = (f[\"/sensorloc\"][\"glat\"], f[\"/sensorloc\"][\"glon\"]) except KeyError: try: latlon = f[\"/lla\"][:2]", "= Path(infn).expanduser().resolve(strict=True) # %% parse indicies to load if isinstance(Navg, slice): key =", "scipy.io import loadmat except ImportError: loadmat = None def meanstack( infn: Path, Navg:", "header that astrometry.net then crashes on, we wrote this quick script to ingest", "axis=0).astype(img.dtype) assert colaps.ndim > 0 assert isinstance(colaps, np.ndarray) return colaps def writefits(img: np.ndarray,", "then crashes on, we wrote this quick script to ingest a variety of", "= None try: import h5py except ImportError: h5py = None try: from scipy.io", "datetime = None, method: str = \"mean\" ) -> tuple[np.ndarray, datetime]: infn =", "methods handled individually to improve efficiency with huge files \"\"\" if infn.suffix ==", "slice(Navg[0], Navg[1]) else: raise ValueError(f\"not sure what you mean by Navg={Navg}\") # %%", "h5py\") img, ut1 = _h5mean(infn, ut1, key, method) elif infn.suffix in (\".fits\", \".new\"):", "slice, method: str) -> tuple[np.ndarray, datetime]: with h5py.File(fn, \"r\") as f: img =", "method: str = \"mean\" ) -> tuple[np.ndarray, datetime]: infn = Path(infn).expanduser().resolve(strict=True) # %%", "elif method == \"median\": func = np.median else: raise TypeError(f\"unknown method {method}\") colaps", "parse indicies to load if isinstance(Navg, slice): key = Navg elif isinstance(Navg, int):", "{method}\") colaps = func(img[key, ...], axis=0).astype(img.dtype) assert colaps.ndim > 0 assert isinstance(colaps, np.ndarray)", "not in (2, 3, 4): raise ValueError(\"only 2D, 3D, or 4D image stacks", "None: raise ImportError(\"pip install scipy\") img = loadmat(infn) img = collapsestack(img[\"data\"].T, key, method)", "method) # matlab is fortran order else: # .tif etc. if imageio is", "TypeError(f\"unknown method {method}\") colaps = func(img[key, ...], axis=0).astype(img.dtype) assert colaps.ndim > 0 assert", "= collapsestack(f[0].data, key, method) elif infn.suffix == \".mat\": if loadmat is None: raise", "fits.PrimaryHDU(img) try: f.writeto(outfn, overwrite=False, checksum=True) # no close() print(\"writing\", outfn) except OSError: logging.warning(f\"did", "== 2: return img # %% 3-D if method == \"mean\": func =", "card. \"\"\" from __future__ import annotations from pathlib import Path import numpy as", "existing {outfn}\") def readh5coord(fn: Path) -> tuple[float, float]: if not fn.suffix == \".h5\":", "average a selected stack of images is to reduce the noise for use", "selected stack of images is to reduce the noise for use in astrometry.net", "isinstance(Navg, slice): key = Navg elif isinstance(Navg, int): key = slice(0, Navg) elif", "= loadmat(infn) img = collapsestack(img[\"data\"].T, key, method) # matlab is fortran order else:", "Path, ut1: datetime, key: slice, method: str) -> tuple[np.ndarray, datetime]: with h5py.File(fn, \"r\")", "except ImportError: h5py = None try: from scipy.io import loadmat except ImportError: loadmat", "except KeyError: pass return img, ut1 def collapsestack(img: np.ndarray, key: slice, method: str)", "4D image stacks are handled\") # %% 2-D if img.ndim == 2: return", "(3, 4) and img.shape[-1] == 3: # assume RGB img = collapsestack(img, key,", "reading in: PyFits, AstroPy, or ImageMagick is: IOError: Header missing END card. \"\"\"", "if ut1 is None: try: ut1 = f[\"/ut1_unix\"][key][0] except KeyError: pass # %%", "matlab is fortran order else: # .tif etc. if imageio is None: raise", "the noise for use in astrometry.net The error you might get from an", "writefits(img: np.ndarray, outfn: Path): outfn = Path(outfn).expanduser() f = fits.PrimaryHDU(img) try: f.writeto(outfn, overwrite=False,", "-> write FITS Because ImageJ has been a little buggy about writing FITS", "== \".h5\": return None with h5py.File(fn, \"r\") as f: try: latlon = (f[\"/sensorloc\"][\"glat\"],", "stacks are handled\") # %% 2-D if img.ndim == 2: return img #", "# %% load images \"\"\" some methods handled individually to improve efficiency with", "{outfn}\") def readh5coord(fn: Path) -> tuple[float, float]: if not fn.suffix == \".h5\": return", "is None: raise ImportError(\"pip install imageio\") img = imageio.imread(infn, as_gray=True) if img.ndim in", "numpy as np from datetime import datetime from astropy.io import fits import logging", "elif isinstance(Navg, int): key = slice(0, Navg) elif len(Navg) == 1: key =", "is: IOError: Header missing END card. \"\"\" from __future__ import annotations from pathlib", "Path, Navg: int, ut1: datetime = None, method: str = \"mean\" ) ->", "img # %% 3-D if method == \"mean\": func = np.mean elif method", "\"median\": func = np.median else: raise TypeError(f\"unknown method {method}\") colaps = func(img[key, ...],", "on, we wrote this quick script to ingest a variety of files and", "= (f[\"/sensorloc\"][\"glat\"], f[\"/sensorloc\"][\"glon\"]) except KeyError: try: latlon = f[\"/lla\"][:2] except KeyError: return None", "elif len(Navg) == 2: key = slice(Navg[0], Navg[1]) else: raise ValueError(f\"not sure what", ") -> tuple[np.ndarray, datetime]: infn = Path(infn).expanduser().resolve(strict=True) # %% parse indicies to load", "noise for use in astrometry.net The error you might get from an ImageJ", "np.mean elif method == \"median\": func = np.median else: raise TypeError(f\"unknown method {method}\")", "0 assert isinstance(colaps, np.ndarray) return colaps def writefits(img: np.ndarray, outfn: Path): outfn =", "Navg[0]) elif len(Navg) == 2: key = slice(Navg[0], Navg[1]) else: raise ValueError(f\"not sure", "PyFits, AstroPy, or ImageMagick is: IOError: Header missing END card. \"\"\" from __future__", "method == \"mean\": func = np.mean elif method == \"median\": func = np.median", "ut1 = f[\"/ut1_unix\"][key][0] except KeyError: pass # %% orientation try: img = np.rot90(img,", "reason we average a selected stack of images is to reduce the noise", "np.rot90(img, k=f[\"/params\"][\"rotccw\"]) except KeyError: pass return img, ut1 def collapsestack(img: np.ndarray, key: slice,", "or 4D image stacks are handled\") # %% 2-D if img.ndim == 2:", "raise ImportError(\"pip install imageio\") img = imageio.imread(infn, as_gray=True) if img.ndim in (3, 4)", "outfn) except OSError: logging.warning(f\"did not overwrite existing {outfn}\") def readh5coord(fn: Path) -> tuple[float,", "None, method: str = \"mean\" ) -> tuple[np.ndarray, datetime]: infn = Path(infn).expanduser().resolve(strict=True) #", "...], axis=0).astype(img.dtype) assert colaps.ndim > 0 assert isinstance(colaps, np.ndarray) return colaps def writefits(img:", "if img.ndim not in (2, 3, 4): raise ValueError(\"only 2D, 3D, or 4D", "reduce the noise for use in astrometry.net The error you might get from", "img.ndim not in (2, 3, 4): raise ValueError(\"only 2D, 3D, or 4D image", "img.ndim == 2: return img # %% 3-D if method == \"mean\": func", "astrometry.net The error you might get from an ImageJ saved FITS when reading", "scipy\") img = loadmat(infn) img = collapsestack(img[\"data\"].T, key, method) # matlab is fortran", "img = imageio.imread(infn, as_gray=True) if img.ndim in (3, 4) and img.shape[-1] == 3:", "tuple[float, float]: if not fn.suffix == \".h5\": return None with h5py.File(fn, \"r\") as", "try: ut1 = f[\"/ut1_unix\"][key][0] except KeyError: pass # %% orientation try: img =", "f = fits.PrimaryHDU(img) try: f.writeto(outfn, overwrite=False, checksum=True) # no close() print(\"writing\", outfn) except", "colaps.ndim > 0 assert isinstance(colaps, np.ndarray) return colaps def writefits(img: np.ndarray, outfn: Path):", "time if ut1 is None: try: ut1 = f[\"/ut1_unix\"][key][0] except KeyError: pass #", "the header that astrometry.net then crashes on, we wrote this quick script to", "and average the specified frames then write a FITS. The reason we average", "key, method) elif infn.suffix == \".mat\": if loadmat is None: raise ImportError(\"pip install", "== \"mean\": func = np.mean elif method == \"median\": func = np.median else:", "== 2: key = slice(Navg[0], Navg[1]) else: raise ValueError(f\"not sure what you mean", "img.ndim in (3, 4) and img.shape[-1] == 3: # assume RGB img =", "try: import h5py except ImportError: h5py = None try: from scipy.io import loadmat", "= fits.PrimaryHDU(img) try: f.writeto(outfn, overwrite=False, checksum=True) # no close() print(\"writing\", outfn) except OSError:", "astropy.io import fits import logging try: import imageio except ImportError: imageio = None", "we average a selected stack of images is to reduce the noise for", "ImportError(\"pip install h5py\") img, ut1 = _h5mean(infn, ut1, key, method) elif infn.suffix in", "return colaps def writefits(img: np.ndarray, outfn: Path): outfn = Path(outfn).expanduser() f = fits.PrimaryHDU(img)", "AstroPy, or ImageMagick is: IOError: Header missing END card. \"\"\" from __future__ import", "little buggy about writing FITS files, in particular the header that astrometry.net then" ]
[ "# By default, VRM Importer includes leaf bones automatically. # It's cool and", "# Use this script to obliterate those leaf bones in one click. if", "models! import bpy context = bpy.context obj = context.object # By default, VRM", "import bpy context = bpy.context obj = context.object # By default, VRM Importer", "long warning when imported to UE4. # Use this script to obliterate those", "bpy.context obj = context.object # By default, VRM Importer includes leaf bones automatically.", "warning when imported to UE4. # Use this script to obliterate those leaf", "if obj.type == 'ARMATURE': armature = obj.data bpy.ops.object.mode_set(mode='EDIT') for bone in armature.edit_bones: if", "and will spew out # scary long warning when imported to UE4. #", "not necessary for Blender, and will spew out # scary long warning when", "= bpy.context obj = context.object # By default, VRM Importer includes leaf bones", "Use this script to obliterate those leaf bones in one click. if obj.type", "armature = obj.data bpy.ops.object.mode_set(mode='EDIT') for bone in armature.edit_bones: if bone.name.endswith(\"_end\") : armature.edit_bones.remove(bone) else:", "scary long warning when imported to UE4. # Use this script to obliterate", "when imported to UE4. # Use this script to obliterate those leaf bones", "'ARMATURE': armature = obj.data bpy.ops.object.mode_set(mode='EDIT') for bone in armature.edit_bones: if bone.name.endswith(\"_end\") : armature.edit_bones.remove(bone)", "bones in VRoid models! import bpy context = bpy.context obj = context.object #", "in one click. if obj.type == 'ARMATURE': armature = obj.data bpy.ops.object.mode_set(mode='EDIT') for bone", "context = bpy.context obj = context.object # By default, VRM Importer includes leaf", "# It's cool and stuff, but it's not necessary for Blender, and will", "= obj.data bpy.ops.object.mode_set(mode='EDIT') for bone in armature.edit_bones: if bone.name.endswith(\"_end\") : armature.edit_bones.remove(bone) else: continue", "leaf bones in VRoid models! import bpy context = bpy.context obj = context.object", "but it's not necessary for Blender, and will spew out # scary long", "to obliterate those leaf bones in one click. if obj.type == 'ARMATURE': armature", "obj.data bpy.ops.object.mode_set(mode='EDIT') for bone in armature.edit_bones: if bone.name.endswith(\"_end\") : armature.edit_bones.remove(bone) else: continue bpy.ops.object.mode_set(mode='OBJECT')", "necessary for Blender, and will spew out # scary long warning when imported", "spew out # scary long warning when imported to UE4. # Use this", "= context.object # By default, VRM Importer includes leaf bones automatically. # It's", "leaf bones automatically. # It's cool and stuff, but it's not necessary for", "Blender, and will spew out # scary long warning when imported to UE4.", "will spew out # scary long warning when imported to UE4. # Use", "in VRoid models! import bpy context = bpy.context obj = context.object # By", "and stuff, but it's not necessary for Blender, and will spew out #", "for Blender, and will spew out # scary long warning when imported to", "bones automatically. # It's cool and stuff, but it's not necessary for Blender,", "Importer includes leaf bones automatically. # It's cool and stuff, but it's not", "UE4. # Use this script to obliterate those leaf bones in one click.", "VRoid models! import bpy context = bpy.context obj = context.object # By default,", "VRM Importer includes leaf bones automatically. # It's cool and stuff, but it's", "script to obliterate those leaf bones in one click. if obj.type == 'ARMATURE':", "it's not necessary for Blender, and will spew out # scary long warning", "== 'ARMATURE': armature = obj.data bpy.ops.object.mode_set(mode='EDIT') for bone in armature.edit_bones: if bone.name.endswith(\"_end\") :", "context.object # By default, VRM Importer includes leaf bones automatically. # It's cool", "this script to obliterate those leaf bones in one click. if obj.type ==", "obj = context.object # By default, VRM Importer includes leaf bones automatically. #", "unused leaf bones in VRoid models! import bpy context = bpy.context obj =", "default, VRM Importer includes leaf bones automatically. # It's cool and stuff, but", "leaf bones in one click. if obj.type == 'ARMATURE': armature = obj.data bpy.ops.object.mode_set(mode='EDIT')", "cool and stuff, but it's not necessary for Blender, and will spew out", "# scary long warning when imported to UE4. # Use this script to", "# Obliterate unused leaf bones in VRoid models! import bpy context = bpy.context", "stuff, but it's not necessary for Blender, and will spew out # scary", "click. if obj.type == 'ARMATURE': armature = obj.data bpy.ops.object.mode_set(mode='EDIT') for bone in armature.edit_bones:", "bones in one click. if obj.type == 'ARMATURE': armature = obj.data bpy.ops.object.mode_set(mode='EDIT') for", "bpy context = bpy.context obj = context.object # By default, VRM Importer includes", "obliterate those leaf bones in one click. if obj.type == 'ARMATURE': armature =", "out # scary long warning when imported to UE4. # Use this script", "includes leaf bones automatically. # It's cool and stuff, but it's not necessary", "one click. if obj.type == 'ARMATURE': armature = obj.data bpy.ops.object.mode_set(mode='EDIT') for bone in", "Obliterate unused leaf bones in VRoid models! import bpy context = bpy.context obj", "automatically. # It's cool and stuff, but it's not necessary for Blender, and", "By default, VRM Importer includes leaf bones automatically. # It's cool and stuff,", "imported to UE4. # Use this script to obliterate those leaf bones in", "those leaf bones in one click. if obj.type == 'ARMATURE': armature = obj.data", "to UE4. # Use this script to obliterate those leaf bones in one", "obj.type == 'ARMATURE': armature = obj.data bpy.ops.object.mode_set(mode='EDIT') for bone in armature.edit_bones: if bone.name.endswith(\"_end\")", "It's cool and stuff, but it's not necessary for Blender, and will spew" ]
[ "\")) e=int(input(\"enter a end \")) for n in range(s,e+1): order=len(str(n)) num=0 backup=n while(n>0):", "s=int(input(\"enter start \")) e=int(input(\"enter a end \")) for n in range(s,e+1): order=len(str(n)) num=0", "start \")) e=int(input(\"enter a end \")) for n in range(s,e+1): order=len(str(n)) num=0 backup=n", "e=int(input(\"enter a end \")) for n in range(s,e+1): order=len(str(n)) num=0 backup=n while(n>0): x=n%10", "\")) for n in range(s,e+1): order=len(str(n)) num=0 backup=n while(n>0): x=n%10 num+=x**order n=n//10 if(num==backup):", "end \")) for n in range(s,e+1): order=len(str(n)) num=0 backup=n while(n>0): x=n%10 num+=x**order n=n//10", "for n in range(s,e+1): order=len(str(n)) num=0 backup=n while(n>0): x=n%10 num+=x**order n=n//10 if(num==backup): print(num,\"\\t\",end='')", "a end \")) for n in range(s,e+1): order=len(str(n)) num=0 backup=n while(n>0): x=n%10 num+=x**order" ]
[ "* application = Flask(\"rsa-core\") application.config['JWT_SECRET_KEY'] = config['jwt_key'] jwt = JWTManager(application) application.url_map.converters['list'] = ListConverter", ".security import * application = Flask(\"rsa-core\") application.config['JWT_SECRET_KEY'] = config['jwt_key'] jwt = JWTManager(application) application.url_map.converters['list']", "application.register_blueprint(docs) application.register_blueprint(corps) application.register_blueprint(read) application.register_blueprint(manage) application.register_blueprint(admin) security_provider = config['security_provider'] @application.route(\"/\") def index(): return jsonify({\"msg\":", "jwt = JWTManager(application) application.url_map.converters['list'] = ListConverter application.register_blueprint(docs) application.register_blueprint(corps) application.register_blueprint(read) application.register_blueprint(manage) application.register_blueprint(admin) security_provider =", "jsonify({\"msg\": \"ok\"}) #@application.route(\"/tokens\") #def tokens(): # return jsonify(security_provider.create_temp_tokens()) if __name__ == \"__main__\": application.run(host='0.0.0.0',", "flask import Flask, jsonify from flask_jwt_extended import JWTManager from .config import config from", "import Flask, jsonify from flask_jwt_extended import JWTManager from .config import config from .controllers", "from .utils import ListConverter from .security import * application = Flask(\"rsa-core\") application.config['JWT_SECRET_KEY'] =", "config['jwt_key'] jwt = JWTManager(application) application.url_map.converters['list'] = ListConverter application.register_blueprint(docs) application.register_blueprint(corps) application.register_blueprint(read) application.register_blueprint(manage) application.register_blueprint(admin) security_provider", "import config from .controllers import * from .utils import ListConverter from .security import", "JWTManager(application) application.url_map.converters['list'] = ListConverter application.register_blueprint(docs) application.register_blueprint(corps) application.register_blueprint(read) application.register_blueprint(manage) application.register_blueprint(admin) security_provider = config['security_provider'] @application.route(\"/\")", "application.register_blueprint(manage) application.register_blueprint(admin) security_provider = config['security_provider'] @application.route(\"/\") def index(): return jsonify({\"msg\": \"ok\"}) #@application.route(\"/tokens\") #def", "from flask import Flask, jsonify from flask_jwt_extended import JWTManager from .config import config", "ListConverter from .security import * application = Flask(\"rsa-core\") application.config['JWT_SECRET_KEY'] = config['jwt_key'] jwt =", "config['security_provider'] @application.route(\"/\") def index(): return jsonify({\"msg\": \"ok\"}) #@application.route(\"/tokens\") #def tokens(): # return jsonify(security_provider.create_temp_tokens())", "import * from .utils import ListConverter from .security import * application = Flask(\"rsa-core\")", "application.register_blueprint(admin) security_provider = config['security_provider'] @application.route(\"/\") def index(): return jsonify({\"msg\": \"ok\"}) #@application.route(\"/tokens\") #def tokens():", "flask_jwt_extended import JWTManager from .config import config from .controllers import * from .utils", ".controllers import * from .utils import ListConverter from .security import * application =", "= ListConverter application.register_blueprint(docs) application.register_blueprint(corps) application.register_blueprint(read) application.register_blueprint(manage) application.register_blueprint(admin) security_provider = config['security_provider'] @application.route(\"/\") def index():", "from flask_jwt_extended import JWTManager from .config import config from .controllers import * from", "security_provider = config['security_provider'] @application.route(\"/\") def index(): return jsonify({\"msg\": \"ok\"}) #@application.route(\"/tokens\") #def tokens(): #", "config from .controllers import * from .utils import ListConverter from .security import *", "import ListConverter from .security import * application = Flask(\"rsa-core\") application.config['JWT_SECRET_KEY'] = config['jwt_key'] jwt", ".config import config from .controllers import * from .utils import ListConverter from .security", "import JWTManager from .config import config from .controllers import * from .utils import", "index(): return jsonify({\"msg\": \"ok\"}) #@application.route(\"/tokens\") #def tokens(): # return jsonify(security_provider.create_temp_tokens()) if __name__ ==", ".utils import ListConverter from .security import * application = Flask(\"rsa-core\") application.config['JWT_SECRET_KEY'] = config['jwt_key']", "import * application = Flask(\"rsa-core\") application.config['JWT_SECRET_KEY'] = config['jwt_key'] jwt = JWTManager(application) application.url_map.converters['list'] =", "application.config['JWT_SECRET_KEY'] = config['jwt_key'] jwt = JWTManager(application) application.url_map.converters['list'] = ListConverter application.register_blueprint(docs) application.register_blueprint(corps) application.register_blueprint(read) application.register_blueprint(manage)", "jsonify from flask_jwt_extended import JWTManager from .config import config from .controllers import *", "application.register_blueprint(corps) application.register_blueprint(read) application.register_blueprint(manage) application.register_blueprint(admin) security_provider = config['security_provider'] @application.route(\"/\") def index(): return jsonify({\"msg\": \"ok\"})", "@application.route(\"/\") def index(): return jsonify({\"msg\": \"ok\"}) #@application.route(\"/tokens\") #def tokens(): # return jsonify(security_provider.create_temp_tokens()) if", "def index(): return jsonify({\"msg\": \"ok\"}) #@application.route(\"/tokens\") #def tokens(): # return jsonify(security_provider.create_temp_tokens()) if __name__", "\"ok\"}) #@application.route(\"/tokens\") #def tokens(): # return jsonify(security_provider.create_temp_tokens()) if __name__ == \"__main__\": application.run(host='0.0.0.0', port=config['port'])", "<gh_stars>1-10 from flask import Flask, jsonify from flask_jwt_extended import JWTManager from .config import", "application.register_blueprint(read) application.register_blueprint(manage) application.register_blueprint(admin) security_provider = config['security_provider'] @application.route(\"/\") def index(): return jsonify({\"msg\": \"ok\"}) #@application.route(\"/tokens\")", "= config['security_provider'] @application.route(\"/\") def index(): return jsonify({\"msg\": \"ok\"}) #@application.route(\"/tokens\") #def tokens(): # return", "application = Flask(\"rsa-core\") application.config['JWT_SECRET_KEY'] = config['jwt_key'] jwt = JWTManager(application) application.url_map.converters['list'] = ListConverter application.register_blueprint(docs)", "JWTManager from .config import config from .controllers import * from .utils import ListConverter", "from .config import config from .controllers import * from .utils import ListConverter from", "from .controllers import * from .utils import ListConverter from .security import * application", "= config['jwt_key'] jwt = JWTManager(application) application.url_map.converters['list'] = ListConverter application.register_blueprint(docs) application.register_blueprint(corps) application.register_blueprint(read) application.register_blueprint(manage) application.register_blueprint(admin)", "return jsonify({\"msg\": \"ok\"}) #@application.route(\"/tokens\") #def tokens(): # return jsonify(security_provider.create_temp_tokens()) if __name__ == \"__main__\":", "Flask, jsonify from flask_jwt_extended import JWTManager from .config import config from .controllers import", "from .security import * application = Flask(\"rsa-core\") application.config['JWT_SECRET_KEY'] = config['jwt_key'] jwt = JWTManager(application)", "* from .utils import ListConverter from .security import * application = Flask(\"rsa-core\") application.config['JWT_SECRET_KEY']", "= Flask(\"rsa-core\") application.config['JWT_SECRET_KEY'] = config['jwt_key'] jwt = JWTManager(application) application.url_map.converters['list'] = ListConverter application.register_blueprint(docs) application.register_blueprint(corps)", "application.url_map.converters['list'] = ListConverter application.register_blueprint(docs) application.register_blueprint(corps) application.register_blueprint(read) application.register_blueprint(manage) application.register_blueprint(admin) security_provider = config['security_provider'] @application.route(\"/\") def", "ListConverter application.register_blueprint(docs) application.register_blueprint(corps) application.register_blueprint(read) application.register_blueprint(manage) application.register_blueprint(admin) security_provider = config['security_provider'] @application.route(\"/\") def index(): return", "Flask(\"rsa-core\") application.config['JWT_SECRET_KEY'] = config['jwt_key'] jwt = JWTManager(application) application.url_map.converters['list'] = ListConverter application.register_blueprint(docs) application.register_blueprint(corps) application.register_blueprint(read)", "= JWTManager(application) application.url_map.converters['list'] = ListConverter application.register_blueprint(docs) application.register_blueprint(corps) application.register_blueprint(read) application.register_blueprint(manage) application.register_blueprint(admin) security_provider = config['security_provider']" ]
[ "name = du.get_dataset_name(global_name, subset) dataset_path = os.path.join(storage_data_path, global_name) original_data_path = du.get_original_data_path(global_name) # Build", "recover the study name of the image name to construct the name of", "the sub-folder for the current subset dst_folder_path = os.path.join(dataset_path, dst_folder) # Copy the", "are left over for validation affine = np.array([[1, 0, 0, 0], [0, 1,", "brain for side in (\"_L\", \"_R\"): study_name = match[0] + side y =", "os.listdir(os.path.join(dataset_path, dst_folder))) for study_name in study_names: instances.append(SegmentationInstance( x_path=os.path.join(dataset_path, dst_folder, study_name + '.nii.gz'), y_path=os.path.join(dataset_path,", "set(file_name.split('.nii')[0].split('_gt')[0] for file_name in os.listdir(os.path.join(dataset_path, dst_folder))) for study_name in study_names: instances.append(SegmentationInstance( x_path=os.path.join(dataset_path, dst_folder,", "of the image name to construct the name of the segmentation files match", "files_with_swapped_masks): y = y[40: 104, 78: 142, 49: 97] x_cropped = x[40: 104,", "x[40: 104, 78: 142, 49: 97] else: y = y[40: 104, 78: 142,", "else: subset = default if hold_out_ixs is None: hold_out_ixs = [] global_name =", "if not os.path.isdir(dst_folder_path): _extract_images(original_data_path, dst_folder_path, orig_folder) # Fetch all patient/study names study_names =", "is None: raise Exception(f\"A file ({filename}) does not match the expected file naming", "does not match the expected file naming format\") # For each side of", "nibabel as nib import numpy as np import mp.data.datasets.dataset_utils as du from mp.data.datasets.dataset_segmentation", "import nibabel as nib import numpy as np import mp.data.datasets.dataset_utils as du from", "as .nii files and the scans as .mnc files. \"\"\" def __init__(self, subset=None,", "\"\"\" # Folder 100 is for training (100 subjects), 35 subjects are left", "if hold_out_ixs is None: hold_out_ixs = [] global_name = 'HarP' name = du.get_dataset_name(global_name,", "directories if not os.path.isdir(target_path): os.makedirs(target_path) files_with_swapped_masks = {\"ADNI_007_S_1304_74384_ACPC.mnc\", \"ADNI_016_S_4121_280306_ACPC.mnc\", \"ADNI_029_S_4279_265980_ACPC.mnc\", \"ADNI_136_S_0429_109839_ACPC.mnc\"} # For", "match[0] + side y = sitk.ReadImage(os.path.join(labels_path, study_name + \".nii\")) y = sitk.GetArrayFromImage(y) #", "images if not done already if not os.path.isdir(dst_folder_path): _extract_images(original_data_path, dst_folder_path, orig_folder) # Fetch", "filename) if match is None: raise Exception(f\"A file ({filename}) does not match the", "computed to fit the ground truth if (side == \"_L\") ^ (filename in", "orig_folder) # Fetch all patient/study names study_names = set(file_name.split('.nii')[0].split('_gt')[0] for file_name in os.listdir(os.path.join(dataset_path,", "+ side y = sitk.ReadImage(os.path.join(labels_path, study_name + \".nii\")) y = sitk.GetArrayFromImage(y) # Shape", "BUGFIX: Some segmentation have some weird values eg {26896.988, 26897.988} instead of {0,", "x_cropped = x[40: 104, 78: 142, 97: 145] # Need to do move", "os.path.join(source_path, f'Labels_{subset}_NIFTI') # Create directories if not os.path.isdir(target_path): os.makedirs(target_path) files_with_swapped_masks = {\"ADNI_007_S_1304_74384_ACPC.mnc\", \"ADNI_016_S_4121_280306_ACPC.mnc\",", "files_with_swapped_masks = {\"ADNI_007_S_1304_74384_ACPC.mnc\", \"ADNI_016_S_4121_280306_ACPC.mnc\", \"ADNI_029_S_4279_265980_ACPC.mnc\", \"ADNI_136_S_0429_109839_ACPC.mnc\"} # For each MRI, there are 2", "dataset, found at http://www.hippocampal-protocol.net/SOPs/index.php with the masks as .nii files and the scans", "26897.988} instead of {0, 1} y = (y - np.min(y.flat)).astype(np.uint32) # Cropping bounds", "= re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\", filename) if match is None: raise Exception(f\"A file ({filename}) does not", "of the HarP dataset, found at http://www.hippocampal-protocol.net/SOPs/index.php with the masks as .nii files", "and saves the modified images. \"\"\" # Folder 100 is for training (100", "side in (\"_L\", \"_R\"): study_name = match[0] + side y = sitk.ReadImage(os.path.join(labels_path, study_name", "loaded directly sitk.WriteImage(sitk.GetImageFromArray(y), join_path([target_path, study_name + \"_gt.nii.gz\"])) nib.save(nib.Nifti1Image(x_cropped, affine), join_path([target_path, study_name + \".nii.gz\"]))", "subset = default else: subset = default if hold_out_ixs is None: hold_out_ixs =", "# Cropping bounds computed to fit the ground truth if (side == \"_L\")", "label_names=label_names, modality='T1w MRI', nr_channels=1, hold_out_ixs=hold_out_ixs) def _extract_images(source_path, target_path, subset): r\"\"\"Extracts images, merges mask", "1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) images_path =", "= y[40: 104, 78: 142, 97: 145] x_cropped = x[40: 104, 78: 142,", "\"_L\" else \"_L\") # Save new images so they can be loaded directly", "\"Training\")) if subset[\"Part\"] in [\"Validation\", \"All\"]: folders.append((\"35\", \"Validation\")) for orig_folder, dst_folder in folders:", "------------------------------------------------------------------------------ # Hippocampus segmentation task for the HarP dataset # (http://www.hippocampal-protocol.net/SOPs/index.php) # ------------------------------------------------------------------------------", "name=study_name, group_id=None )) label_names = ['background', 'hippocampus'] super().__init__(instances, name=name, label_names=label_names, modality='T1w MRI', nr_channels=1,", "the image name to construct the name of the segmentation files match =", "import storage_data_path from mp.utils.mask_bounding_box import mask_bbox_3D from mp.utils.load_restore import join_path class HarP(SegmentationDataset): r\"\"\"Class", "with the masks as .nii files and the scans as .mnc files. \"\"\"", "\"All\"]: folders.append((\"100\", \"Training\")) if subset[\"Part\"] in [\"Validation\", \"All\"]: folders.append((\"35\", \"Validation\")) for orig_folder, dst_folder", "filename in files_with_swapped_masks: study_name = match[0] + (\"_R\" if side == \"_L\" else", "in files_with_swapped_masks): y = y[40: 104, 78: 142, 49: 97] x_cropped = x[40:", "104, 78: 142, 97: 145] x_cropped = x[40: 104, 78: 142, 97: 145]", "y_path=os.path.join(dataset_path, dst_folder, study_name + '_gt.nii.gz'), name=study_name, group_id=None )) label_names = ['background', 'hippocampus'] super().__init__(instances,", "study_name = match[0] + (\"_R\" if side == \"_L\" else \"_L\") # Save", "= np.moveaxis(x_cropped, [0, 2], [2, 0]) # Changing the study name if needed", "in folders: # Paths with the sub-folder for the current subset dst_folder_path =", "files and the scans as .mnc files. \"\"\" def __init__(self, subset=None, hold_out_ixs=None): #", "study_name + \".nii\")) y = sitk.GetArrayFromImage(y) # Shape expected: (189, 233, 197) assert", "(http://www.hippocampal-protocol.net/SOPs/index.php) # ------------------------------------------------------------------------------ import os import re import SimpleITK as sitk import nibabel", "= default else: subset = default if hold_out_ixs is None: hold_out_ixs = []", "the segmentation of the HarP dataset, found at http://www.hippocampal-protocol.net/SOPs/index.php with the masks as", "affine = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1,", "Create directories if not os.path.isdir(target_path): os.makedirs(target_path) files_with_swapped_masks = {\"ADNI_007_S_1304_74384_ACPC.mnc\", \"ADNI_016_S_4121_280306_ACPC.mnc\", \"ADNI_029_S_4279_265980_ACPC.mnc\", \"ADNI_136_S_0429_109839_ACPC.mnc\"} #", "233, 197) assert x.shape == y.shape # BUGFIX: Some segmentation have some weird", "subset[\"Part\"] in [\"Training\", \"All\"]: folders.append((\"100\", \"Training\")) if subset[\"Part\"] in [\"Validation\", \"All\"]: folders.append((\"35\", \"Validation\"))", "not match the expected file naming format\") # For each side of the", "move an axis as numpy coordinates are [z, y, x] and SimpleITK's are", "truth if (side == \"_L\") ^ (filename in files_with_swapped_masks): y = y[40: 104,", "as numpy coordinates are [z, y, x] and SimpleITK's are [x, y, z]", "os.path.join(storage_data_path, global_name) original_data_path = du.get_original_data_path(global_name) # Build instances instances = [] folders =", "Copy the images if not done already if not os.path.isdir(dst_folder_path): _extract_images(original_data_path, dst_folder_path, orig_folder)", "of {0, 1} y = (y - np.min(y.flat)).astype(np.uint32) # Cropping bounds computed to", "patient/study names study_names = set(file_name.split('.nii')[0].split('_gt')[0] for file_name in os.listdir(os.path.join(dataset_path, dst_folder))) for study_name in", "side == \"_L\" else \"_L\") # Save new images so they can be", "to construct the name of the segmentation files match = re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\", filename) if", "[0, 0, 0, 1]]) images_path = os.path.join(source_path, subset) labels_path = os.path.join(source_path, f'Labels_{subset}_NIFTI') #", "scans as .mnc files. \"\"\" def __init__(self, subset=None, hold_out_ixs=None): # Part is either:", "format\") # For each side of the brain for side in (\"_L\", \"_R\"):", "os.makedirs(target_path) files_with_swapped_masks = {\"ADNI_007_S_1304_74384_ACPC.mnc\", \"ADNI_016_S_4121_280306_ACPC.mnc\", \"ADNI_029_S_4279_265980_ACPC.mnc\", \"ADNI_136_S_0429_109839_ACPC.mnc\"} # For each MRI, there are", "= [] if subset[\"Part\"] in [\"Training\", \"All\"]: folders.append((\"100\", \"Training\")) if subset[\"Part\"] in [\"Validation\",", "import mp.data.datasets.dataset_utils as du from mp.data.datasets.dataset_segmentation import SegmentationDataset, SegmentationInstance from mp.paths import storage_data_path", "0, 1]]) images_path = os.path.join(source_path, subset) labels_path = os.path.join(source_path, f'Labels_{subset}_NIFTI') # Create directories", "default else: subset = default if hold_out_ixs is None: hold_out_ixs = [] global_name", "subjects), 35 subjects are left over for validation affine = np.array([[1, 0, 0,", "for validation affine = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0,", "right hippocampus) for filename in os.listdir(images_path): # Loading the .mnc file and converting", "name to construct the name of the segmentation files match = re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\", filename)", "have some weird values eg {26896.988, 26897.988} instead of {0, 1} y =", "mp.utils.load_restore import join_path class HarP(SegmentationDataset): r\"\"\"Class for the segmentation of the HarP dataset,", "found at http://www.hippocampal-protocol.net/SOPs/index.php with the masks as .nii files and the scans as", ".nii.gz file minc = nib.load(os.path.join(images_path, filename)) x: np.array = nib.Nifti1Image(np.asarray(minc.dataobj), affine=affine).get_data() # We", "and SimpleITK's are [x, y, z] x_cropped = np.moveaxis(x_cropped, [0, 2], [2, 0])", "= nib.load(os.path.join(images_path, filename)) x: np.array = nib.Nifti1Image(np.asarray(minc.dataobj), affine=affine).get_data() # We need to recover", "assert x.shape == y.shape # BUGFIX: Some segmentation have some weird values eg", "'_gt.nii.gz'), name=study_name, group_id=None )) label_names = ['background', 'hippocampus'] super().__init__(instances, name=name, label_names=label_names, modality='T1w MRI',", "not done already if not os.path.isdir(dst_folder_path): _extract_images(original_data_path, dst_folder_path, orig_folder) # Fetch all patient/study", "\"\"\" def __init__(self, subset=None, hold_out_ixs=None): # Part is either: \"Training\", \"Validation\" or \"All\"", "78: 142, 49: 97] else: y = y[40: 104, 78: 142, 97: 145]", "0]) # Changing the study name if needed if filename in files_with_swapped_masks: study_name", "Loading the .mnc file and converting it to a .nii.gz file minc =", "Part is either: \"Training\", \"Validation\" or \"All\" default = {\"Part\": \"All\"} if subset", "+ (\"_R\" if side == \"_L\" else \"_L\") # Save new images so", "== \"_L\" else \"_L\") # Save new images so they can be loaded", "145] x_cropped = x[40: 104, 78: 142, 97: 145] # Need to do", "Fetch all patient/study names study_names = set(file_name.split('.nii')[0].split('_gt')[0] for file_name in os.listdir(os.path.join(dataset_path, dst_folder))) for", "= sitk.ReadImage(os.path.join(labels_path, study_name + \".nii\")) y = sitk.GetArrayFromImage(y) # Shape expected: (189, 233,", "the ground truth if (side == \"_L\") ^ (filename in files_with_swapped_masks): y =", "with the sub-folder for the current subset dst_folder_path = os.path.join(dataset_path, dst_folder) # Copy", "masks as .nii files and the scans as .mnc files. \"\"\" def __init__(self,", "study_name + '.nii.gz'), y_path=os.path.join(dataset_path, dst_folder, study_name + '_gt.nii.gz'), name=study_name, group_id=None )) label_names =", "sitk import nibabel as nib import numpy as np import mp.data.datasets.dataset_utils as du", "nr_channels=1, hold_out_ixs=hold_out_ixs) def _extract_images(source_path, target_path, subset): r\"\"\"Extracts images, merges mask labels (if specified)", "naming format\") # For each side of the brain for side in (\"_L\",", "np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0,", "x_cropped = np.moveaxis(x_cropped, [0, 2], [2, 0]) # Changing the study name if", "\"_L\") # Save new images so they can be loaded directly sitk.WriteImage(sitk.GetImageFromArray(y), join_path([target_path,", "49: 97] x_cropped = x[40: 104, 78: 142, 49: 97] else: y =", "subset = default if hold_out_ixs is None: hold_out_ixs = [] global_name = 'HarP'", "np.array = nib.Nifti1Image(np.asarray(minc.dataobj), affine=affine).get_data() # We need to recover the study name of", "y = y[40: 104, 78: 142, 97: 145] x_cropped = x[40: 104, 78:", "y[40: 104, 78: 142, 49: 97] x_cropped = x[40: 104, 78: 142, 49:", "modality='T1w MRI', nr_channels=1, hold_out_ixs=hold_out_ixs) def _extract_images(source_path, target_path, subset): r\"\"\"Extracts images, merges mask labels", "Folder 100 is for training (100 subjects), 35 subjects are left over for", "= [] global_name = 'HarP' name = du.get_dataset_name(global_name, subset) dataset_path = os.path.join(storage_data_path, global_name)", "from mp.utils.mask_bounding_box import mask_bbox_3D from mp.utils.load_restore import join_path class HarP(SegmentationDataset): r\"\"\"Class for the", "study_name = match[0] + side y = sitk.ReadImage(os.path.join(labels_path, study_name + \".nii\")) y =", "Save new images so they can be loaded directly sitk.WriteImage(sitk.GetImageFromArray(y), join_path([target_path, study_name +", "fit the ground truth if (side == \"_L\") ^ (filename in files_with_swapped_masks): y", "file and converting it to a .nii.gz file minc = nib.load(os.path.join(images_path, filename)) x:", "filename in os.listdir(images_path): # Loading the .mnc file and converting it to a", "raise Exception(f\"A file ({filename}) does not match the expected file naming format\") #", "some weird values eg {26896.988, 26897.988} instead of {0, 1} y = (y", "for orig_folder, dst_folder in folders: # Paths with the sub-folder for the current", "the masks as .nii files and the scans as .mnc files. \"\"\" def", "subset): r\"\"\"Extracts images, merges mask labels (if specified) and saves the modified images.", "# Build instances instances = [] folders = [] if subset[\"Part\"] in [\"Training\",", "145] # Need to do move an axis as numpy coordinates are [z,", "subset[\"Part\"] in [\"Validation\", \"All\"]: folders.append((\"35\", \"Validation\")) for orig_folder, dst_folder in folders: # Paths", "104, 78: 142, 49: 97] else: y = y[40: 104, 78: 142, 97:", "== \"_L\") ^ (filename in files_with_swapped_masks): y = y[40: 104, 78: 142, 49:", "49: 97] else: y = y[40: 104, 78: 142, 97: 145] x_cropped =", "# BUGFIX: Some segmentation have some weird values eg {26896.988, 26897.988} instead of", "du.get_original_data_path(global_name) # Build instances instances = [] folders = [] if subset[\"Part\"] in", "in [\"Training\", \"All\"]: folders.append((\"100\", \"Training\")) if subset[\"Part\"] in [\"Validation\", \"All\"]: folders.append((\"35\", \"Validation\")) for", ".mnc file and converting it to a .nii.gz file minc = nib.load(os.path.join(images_path, filename))", "97] x_cropped = x[40: 104, 78: 142, 49: 97] else: y = y[40:", "# ------------------------------------------------------------------------------ import os import re import SimpleITK as sitk import nibabel as", "subset is not None: default.update(subset) subset = default else: subset = default if", "to recover the study name of the image name to construct the name", "x] and SimpleITK's are [x, y, z] x_cropped = np.moveaxis(x_cropped, [0, 2], [2,", "# Create directories if not os.path.isdir(target_path): os.makedirs(target_path) files_with_swapped_masks = {\"ADNI_007_S_1304_74384_ACPC.mnc\", \"ADNI_016_S_4121_280306_ACPC.mnc\", \"ADNI_029_S_4279_265980_ACPC.mnc\", \"ADNI_136_S_0429_109839_ACPC.mnc\"}", "97: 145] x_cropped = x[40: 104, 78: 142, 97: 145] # Need to", "np.moveaxis(x_cropped, [0, 2], [2, 0]) # Changing the study name if needed if", "(side == \"_L\") ^ (filename in files_with_swapped_masks): y = y[40: 104, 78: 142,", "of the brain for side in (\"_L\", \"_R\"): study_name = match[0] + side", "from mp.data.datasets.dataset_segmentation import SegmentationDataset, SegmentationInstance from mp.paths import storage_data_path from mp.utils.mask_bounding_box import mask_bbox_3D", "{\"Part\": \"All\"} if subset is not None: default.update(subset) subset = default else: subset", "97] else: y = y[40: 104, 78: 142, 97: 145] x_cropped = x[40:", "\"ADNI_136_S_0429_109839_ACPC.mnc\"} # For each MRI, there are 2 segmentation (left and right hippocampus)", "(189, 233, 197) assert x.shape == y.shape # BUGFIX: Some segmentation have some", "if filename in files_with_swapped_masks: study_name = match[0] + (\"_R\" if side == \"_L\"", "dst_folder_path, orig_folder) # Fetch all patient/study names study_names = set(file_name.split('.nii')[0].split('_gt')[0] for file_name in", "f'Labels_{subset}_NIFTI') # Create directories if not os.path.isdir(target_path): os.makedirs(target_path) files_with_swapped_masks = {\"ADNI_007_S_1304_74384_ACPC.mnc\", \"ADNI_016_S_4121_280306_ACPC.mnc\", \"ADNI_029_S_4279_265980_ACPC.mnc\",", "weird values eg {26896.988, 26897.988} instead of {0, 1} y = (y -", "coordinates are [z, y, x] and SimpleITK's are [x, y, z] x_cropped =", "dst_folder_path = os.path.join(dataset_path, dst_folder) # Copy the images if not done already if", "{26896.988, 26897.988} instead of {0, 1} y = (y - np.min(y.flat)).astype(np.uint32) # Cropping", "images so they can be loaded directly sitk.WriteImage(sitk.GetImageFromArray(y), join_path([target_path, study_name + \"_gt.nii.gz\"])) nib.save(nib.Nifti1Image(x_cropped,", "from mp.paths import storage_data_path from mp.utils.mask_bounding_box import mask_bbox_3D from mp.utils.load_restore import join_path class", "is None: hold_out_ixs = [] global_name = 'HarP' name = du.get_dataset_name(global_name, subset) dataset_path", "[0, 2], [2, 0]) # Changing the study name if needed if filename", "Build instances instances = [] folders = [] if subset[\"Part\"] in [\"Training\", \"All\"]:", "import mask_bbox_3D from mp.utils.load_restore import join_path class HarP(SegmentationDataset): r\"\"\"Class for the segmentation of", "Some segmentation have some weird values eg {26896.988, 26897.988} instead of {0, 1}", "each MRI, there are 2 segmentation (left and right hippocampus) for filename in", "None: raise Exception(f\"A file ({filename}) does not match the expected file naming format\")", "ground truth if (side == \"_L\") ^ (filename in files_with_swapped_masks): y = y[40:", "# Need to do move an axis as numpy coordinates are [z, y,", "97: 145] # Need to do move an axis as numpy coordinates are", "0, 0, 1]]) images_path = os.path.join(source_path, subset) labels_path = os.path.join(source_path, f'Labels_{subset}_NIFTI') # Create", "name of the segmentation files match = re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\", filename) if match is None:", "the study name of the image name to construct the name of the", "in (\"_L\", \"_R\"): study_name = match[0] + side y = sitk.ReadImage(os.path.join(labels_path, study_name +", "default if hold_out_ixs is None: hold_out_ixs = [] global_name = 'HarP' name =", "hippocampus) for filename in os.listdir(images_path): # Loading the .mnc file and converting it", "os.path.isdir(dst_folder_path): _extract_images(original_data_path, dst_folder_path, orig_folder) # Fetch all patient/study names study_names = set(file_name.split('.nii')[0].split('_gt')[0] for", "merges mask labels (if specified) and saves the modified images. \"\"\" # Folder", "to fit the ground truth if (side == \"_L\") ^ (filename in files_with_swapped_masks):", "if not done already if not os.path.isdir(dst_folder_path): _extract_images(original_data_path, dst_folder_path, orig_folder) # Fetch all", "left over for validation affine = np.array([[1, 0, 0, 0], [0, 1, 0,", "# Loading the .mnc file and converting it to a .nii.gz file minc", "for side in (\"_L\", \"_R\"): study_name = match[0] + side y = sitk.ReadImage(os.path.join(labels_path,", "images. \"\"\" # Folder 100 is for training (100 subjects), 35 subjects are", "# Shape expected: (189, 233, 197) assert x.shape == y.shape # BUGFIX: Some", "{0, 1} y = (y - np.min(y.flat)).astype(np.uint32) # Cropping bounds computed to fit", "MRI', nr_channels=1, hold_out_ixs=hold_out_ixs) def _extract_images(source_path, target_path, subset): r\"\"\"Extracts images, merges mask labels (if", "the modified images. \"\"\" # Folder 100 is for training (100 subjects), 35", "labels_path = os.path.join(source_path, f'Labels_{subset}_NIFTI') # Create directories if not os.path.isdir(target_path): os.makedirs(target_path) files_with_swapped_masks =", "if subset[\"Part\"] in [\"Validation\", \"All\"]: folders.append((\"35\", \"Validation\")) for orig_folder, dst_folder in folders: #", "HarP dataset # (http://www.hippocampal-protocol.net/SOPs/index.php) # ------------------------------------------------------------------------------ import os import re import SimpleITK as", "0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0,", "side of the brain for side in (\"_L\", \"_R\"): study_name = match[0] +", "folders.append((\"35\", \"Validation\")) for orig_folder, dst_folder in folders: # Paths with the sub-folder for", "# Changing the study name if needed if filename in files_with_swapped_masks: study_name =", "study name if needed if filename in files_with_swapped_masks: study_name = match[0] + (\"_R\"", "if subset[\"Part\"] in [\"Training\", \"All\"]: folders.append((\"100\", \"Training\")) if subset[\"Part\"] in [\"Validation\", \"All\"]: folders.append((\"35\",", "side y = sitk.ReadImage(os.path.join(labels_path, study_name + \".nii\")) y = sitk.GetArrayFromImage(y) # Shape expected:", "file naming format\") # For each side of the brain for side in", "'.nii.gz'), y_path=os.path.join(dataset_path, dst_folder, study_name + '_gt.nii.gz'), name=study_name, group_id=None )) label_names = ['background', 'hippocampus']", "import SimpleITK as sitk import nibabel as nib import numpy as np import", "at http://www.hippocampal-protocol.net/SOPs/index.php with the masks as .nii files and the scans as .mnc", "name of the image name to construct the name of the segmentation files", "[z, y, x] and SimpleITK's are [x, y, z] x_cropped = np.moveaxis(x_cropped, [0,", "------------------------------------------------------------------------------ import os import re import SimpleITK as sitk import nibabel as nib", "os.path.isdir(target_path): os.makedirs(target_path) files_with_swapped_masks = {\"ADNI_007_S_1304_74384_ACPC.mnc\", \"ADNI_016_S_4121_280306_ACPC.mnc\", \"ADNI_029_S_4279_265980_ACPC.mnc\", \"ADNI_136_S_0429_109839_ACPC.mnc\"} # For each MRI, there", "subset=None, hold_out_ixs=None): # Part is either: \"Training\", \"Validation\" or \"All\" default = {\"Part\":", "for file_name in os.listdir(os.path.join(dataset_path, dst_folder))) for study_name in study_names: instances.append(SegmentationInstance( x_path=os.path.join(dataset_path, dst_folder, study_name", "name=name, label_names=label_names, modality='T1w MRI', nr_channels=1, hold_out_ixs=hold_out_ixs) def _extract_images(source_path, target_path, subset): r\"\"\"Extracts images, merges", "of the segmentation files match = re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\", filename) if match is None: raise", "= ['background', 'hippocampus'] super().__init__(instances, name=name, label_names=label_names, modality='T1w MRI', nr_channels=1, hold_out_ixs=hold_out_ixs) def _extract_images(source_path, target_path,", "it to a .nii.gz file minc = nib.load(os.path.join(images_path, filename)) x: np.array = nib.Nifti1Image(np.asarray(minc.dataobj),", "\"ADNI_016_S_4121_280306_ACPC.mnc\", \"ADNI_029_S_4279_265980_ACPC.mnc\", \"ADNI_136_S_0429_109839_ACPC.mnc\"} # For each MRI, there are 2 segmentation (left and", "else: y = y[40: 104, 78: 142, 97: 145] x_cropped = x[40: 104,", "if subset is not None: default.update(subset) subset = default else: subset = default", "in os.listdir(os.path.join(dataset_path, dst_folder))) for study_name in study_names: instances.append(SegmentationInstance( x_path=os.path.join(dataset_path, dst_folder, study_name + '.nii.gz'),", "files_with_swapped_masks: study_name = match[0] + (\"_R\" if side == \"_L\" else \"_L\") #", "group_id=None )) label_names = ['background', 'hippocampus'] super().__init__(instances, name=name, label_names=label_names, modality='T1w MRI', nr_channels=1, hold_out_ixs=hold_out_ixs)", "class HarP(SegmentationDataset): r\"\"\"Class for the segmentation of the HarP dataset, found at http://www.hippocampal-protocol.net/SOPs/index.php", "HarP(SegmentationDataset): r\"\"\"Class for the segmentation of the HarP dataset, found at http://www.hippocampal-protocol.net/SOPs/index.php with", "np import mp.data.datasets.dataset_utils as du from mp.data.datasets.dataset_segmentation import SegmentationDataset, SegmentationInstance from mp.paths import", "as nib import numpy as np import mp.data.datasets.dataset_utils as du from mp.data.datasets.dataset_segmentation import", "_extract_images(source_path, target_path, subset): r\"\"\"Extracts images, merges mask labels (if specified) and saves the", "if needed if filename in files_with_swapped_masks: study_name = match[0] + (\"_R\" if side", "142, 49: 97] x_cropped = x[40: 104, 78: 142, 49: 97] else: y", "dst_folder))) for study_name in study_names: instances.append(SegmentationInstance( x_path=os.path.join(dataset_path, dst_folder, study_name + '.nii.gz'), y_path=os.path.join(dataset_path, dst_folder,", "= 'HarP' name = du.get_dataset_name(global_name, subset) dataset_path = os.path.join(storage_data_path, global_name) original_data_path = du.get_original_data_path(global_name)", "\"Validation\")) for orig_folder, dst_folder in folders: # Paths with the sub-folder for the", "not os.path.isdir(dst_folder_path): _extract_images(original_data_path, dst_folder_path, orig_folder) # Fetch all patient/study names study_names = set(file_name.split('.nii')[0].split('_gt')[0]", "match = re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\", filename) if match is None: raise Exception(f\"A file ({filename}) does", "sitk.GetArrayFromImage(y) # Shape expected: (189, 233, 197) assert x.shape == y.shape # BUGFIX:", "match[0] + (\"_R\" if side == \"_L\" else \"_L\") # Save new images", "dataset # (http://www.hippocampal-protocol.net/SOPs/index.php) # ------------------------------------------------------------------------------ import os import re import SimpleITK as sitk", "match the expected file naming format\") # For each side of the brain", "global_name = 'HarP' name = du.get_dataset_name(global_name, subset) dataset_path = os.path.join(storage_data_path, global_name) original_data_path =", "1, 0], [0, 0, 0, 1]]) images_path = os.path.join(source_path, subset) labels_path = os.path.join(source_path,", "they can be loaded directly sitk.WriteImage(sitk.GetImageFromArray(y), join_path([target_path, study_name + \"_gt.nii.gz\"])) nib.save(nib.Nifti1Image(x_cropped, affine), join_path([target_path,", "= x[40: 104, 78: 142, 49: 97] else: y = y[40: 104, 78:", "\"Training\", \"Validation\" or \"All\" default = {\"Part\": \"All\"} if subset is not None:", "in [\"Validation\", \"All\"]: folders.append((\"35\", \"Validation\")) for orig_folder, dst_folder in folders: # Paths with", "+ '.nii.gz'), y_path=os.path.join(dataset_path, dst_folder, study_name + '_gt.nii.gz'), name=study_name, group_id=None )) label_names = ['background',", "default = {\"Part\": \"All\"} if subset is not None: default.update(subset) subset = default", "\"ADNI_029_S_4279_265980_ACPC.mnc\", \"ADNI_136_S_0429_109839_ACPC.mnc\"} # For each MRI, there are 2 segmentation (left and right", "We need to recover the study name of the image name to construct", "104, 78: 142, 49: 97] x_cropped = x[40: 104, 78: 142, 49: 97]", "study_names: instances.append(SegmentationInstance( x_path=os.path.join(dataset_path, dst_folder, study_name + '.nii.gz'), y_path=os.path.join(dataset_path, dst_folder, study_name + '_gt.nii.gz'), name=study_name,", "validation affine = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0,", "# (http://www.hippocampal-protocol.net/SOPs/index.php) # ------------------------------------------------------------------------------ import os import re import SimpleITK as sitk import", "as du from mp.data.datasets.dataset_segmentation import SegmentationDataset, SegmentationInstance from mp.paths import storage_data_path from mp.utils.mask_bounding_box", "values eg {26896.988, 26897.988} instead of {0, 1} y = (y - np.min(y.flat)).astype(np.uint32)", "# For each MRI, there are 2 segmentation (left and right hippocampus) for", "os.path.join(dataset_path, dst_folder) # Copy the images if not done already if not os.path.isdir(dst_folder_path):", "(y - np.min(y.flat)).astype(np.uint32) # Cropping bounds computed to fit the ground truth if", "(\"_L\", \"_R\"): study_name = match[0] + side y = sitk.ReadImage(os.path.join(labels_path, study_name + \".nii\"))", "[\"Training\", \"All\"]: folders.append((\"100\", \"Training\")) if subset[\"Part\"] in [\"Validation\", \"All\"]: folders.append((\"35\", \"Validation\")) for orig_folder,", ".nii files and the scans as .mnc files. \"\"\" def __init__(self, subset=None, hold_out_ixs=None):", "du.get_dataset_name(global_name, subset) dataset_path = os.path.join(storage_data_path, global_name) original_data_path = du.get_original_data_path(global_name) # Build instances instances", "from mp.utils.load_restore import join_path class HarP(SegmentationDataset): r\"\"\"Class for the segmentation of the HarP", "the HarP dataset # (http://www.hippocampal-protocol.net/SOPs/index.php) # ------------------------------------------------------------------------------ import os import re import SimpleITK", "files. \"\"\" def __init__(self, subset=None, hold_out_ixs=None): # Part is either: \"Training\", \"Validation\" or", "the .mnc file and converting it to a .nii.gz file minc = nib.load(os.path.join(images_path,", "HarP dataset, found at http://www.hippocampal-protocol.net/SOPs/index.php with the masks as .nii files and the", "dst_folder) # Copy the images if not done already if not os.path.isdir(dst_folder_path): _extract_images(original_data_path,", "dst_folder in folders: # Paths with the sub-folder for the current subset dst_folder_path", "(left and right hippocampus) for filename in os.listdir(images_path): # Loading the .mnc file", "instances instances = [] folders = [] if subset[\"Part\"] in [\"Training\", \"All\"]: folders.append((\"100\",", "a .nii.gz file minc = nib.load(os.path.join(images_path, filename)) x: np.array = nib.Nifti1Image(np.asarray(minc.dataobj), affine=affine).get_data() #", "y[40: 104, 78: 142, 97: 145] x_cropped = x[40: 104, 78: 142, 97:", "instances = [] folders = [] if subset[\"Part\"] in [\"Training\", \"All\"]: folders.append((\"100\", \"Training\"))", "if match is None: raise Exception(f\"A file ({filename}) does not match the expected", "study name of the image name to construct the name of the segmentation", "else \"_L\") # Save new images so they can be loaded directly sitk.WriteImage(sitk.GetImageFromArray(y),", "__init__(self, subset=None, hold_out_ixs=None): # Part is either: \"Training\", \"Validation\" or \"All\" default =", "'HarP' name = du.get_dataset_name(global_name, subset) dataset_path = os.path.join(storage_data_path, global_name) original_data_path = du.get_original_data_path(global_name) #", "'hippocampus'] super().__init__(instances, name=name, label_names=label_names, modality='T1w MRI', nr_channels=1, hold_out_ixs=hold_out_ixs) def _extract_images(source_path, target_path, subset): r\"\"\"Extracts", "for the segmentation of the HarP dataset, found at http://www.hippocampal-protocol.net/SOPs/index.php with the masks", "= nib.Nifti1Image(np.asarray(minc.dataobj), affine=affine).get_data() # We need to recover the study name of the", "r\"\"\"Class for the segmentation of the HarP dataset, found at http://www.hippocampal-protocol.net/SOPs/index.php with the", "+ \".nii\")) y = sitk.GetArrayFromImage(y) # Shape expected: (189, 233, 197) assert x.shape", "= {\"ADNI_007_S_1304_74384_ACPC.mnc\", \"ADNI_016_S_4121_280306_ACPC.mnc\", \"ADNI_029_S_4279_265980_ACPC.mnc\", \"ADNI_136_S_0429_109839_ACPC.mnc\"} # For each MRI, there are 2 segmentation", "mp.paths import storage_data_path from mp.utils.mask_bounding_box import mask_bbox_3D from mp.utils.load_restore import join_path class HarP(SegmentationDataset):", "# Save new images so they can be loaded directly sitk.WriteImage(sitk.GetImageFromArray(y), join_path([target_path, study_name", "modified images. \"\"\" # Folder 100 is for training (100 subjects), 35 subjects", "minc = nib.load(os.path.join(images_path, filename)) x: np.array = nib.Nifti1Image(np.asarray(minc.dataobj), affine=affine).get_data() # We need to", "78: 142, 97: 145] x_cropped = x[40: 104, 78: 142, 97: 145] #", "0], [0, 0, 0, 1]]) images_path = os.path.join(source_path, subset) labels_path = os.path.join(source_path, f'Labels_{subset}_NIFTI')", "x_cropped = x[40: 104, 78: 142, 49: 97] else: y = y[40: 104,", "nib.Nifti1Image(np.asarray(minc.dataobj), affine=affine).get_data() # We need to recover the study name of the image", "can be loaded directly sitk.WriteImage(sitk.GetImageFromArray(y), join_path([target_path, study_name + \"_gt.nii.gz\"])) nib.save(nib.Nifti1Image(x_cropped, affine), join_path([target_path, study_name", "[] if subset[\"Part\"] in [\"Training\", \"All\"]: folders.append((\"100\", \"Training\")) if subset[\"Part\"] in [\"Validation\", \"All\"]:", "Paths with the sub-folder for the current subset dst_folder_path = os.path.join(dataset_path, dst_folder) #", "\".nii\")) y = sitk.GetArrayFromImage(y) # Shape expected: (189, 233, 197) assert x.shape ==", "[] global_name = 'HarP' name = du.get_dataset_name(global_name, subset) dataset_path = os.path.join(storage_data_path, global_name) original_data_path", "None: default.update(subset) subset = default else: subset = default if hold_out_ixs is None:", "= du.get_original_data_path(global_name) # Build instances instances = [] folders = [] if subset[\"Part\"]", "[2, 0]) # Changing the study name if needed if filename in files_with_swapped_masks:", "the scans as .mnc files. \"\"\" def __init__(self, subset=None, hold_out_ixs=None): # Part is", "default.update(subset) subset = default else: subset = default if hold_out_ixs is None: hold_out_ixs", "y, z] x_cropped = np.moveaxis(x_cropped, [0, 2], [2, 0]) # Changing the study", "target_path, subset): r\"\"\"Extracts images, merges mask labels (if specified) and saves the modified", "training (100 subjects), 35 subjects are left over for validation affine = np.array([[1,", "subset) labels_path = os.path.join(source_path, f'Labels_{subset}_NIFTI') # Create directories if not os.path.isdir(target_path): os.makedirs(target_path) files_with_swapped_masks", "# We need to recover the study name of the image name to", "- np.min(y.flat)).astype(np.uint32) # Cropping bounds computed to fit the ground truth if (side", "so they can be loaded directly sitk.WriteImage(sitk.GetImageFromArray(y), join_path([target_path, study_name + \"_gt.nii.gz\"])) nib.save(nib.Nifti1Image(x_cropped, affine),", "^ (filename in files_with_swapped_masks): y = y[40: 104, 78: 142, 49: 97] x_cropped", "Cropping bounds computed to fit the ground truth if (side == \"_L\") ^", "the expected file naming format\") # For each side of the brain for", "to a .nii.gz file minc = nib.load(os.path.join(images_path, filename)) x: np.array = nib.Nifti1Image(np.asarray(minc.dataobj), affine=affine).get_data()", "segmentation of the HarP dataset, found at http://www.hippocampal-protocol.net/SOPs/index.php with the masks as .nii", "2 segmentation (left and right hippocampus) for filename in os.listdir(images_path): # Loading the", "du from mp.data.datasets.dataset_segmentation import SegmentationDataset, SegmentationInstance from mp.paths import storage_data_path from mp.utils.mask_bounding_box import", "z] x_cropped = np.moveaxis(x_cropped, [0, 2], [2, 0]) # Changing the study name", "numpy as np import mp.data.datasets.dataset_utils as du from mp.data.datasets.dataset_segmentation import SegmentationDataset, SegmentationInstance from", "the HarP dataset, found at http://www.hippocampal-protocol.net/SOPs/index.php with the masks as .nii files and", "task for the HarP dataset # (http://www.hippocampal-protocol.net/SOPs/index.php) # ------------------------------------------------------------------------------ import os import re", "numpy coordinates are [z, y, x] and SimpleITK's are [x, y, z] x_cropped", "# Part is either: \"Training\", \"Validation\" or \"All\" default = {\"Part\": \"All\"} if", "join_path class HarP(SegmentationDataset): r\"\"\"Class for the segmentation of the HarP dataset, found at", "an axis as numpy coordinates are [z, y, x] and SimpleITK's are [x,", "re import SimpleITK as sitk import nibabel as nib import numpy as np", "mp.data.datasets.dataset_utils as du from mp.data.datasets.dataset_segmentation import SegmentationDataset, SegmentationInstance from mp.paths import storage_data_path from", "each side of the brain for side in (\"_L\", \"_R\"): study_name = match[0]", "\"_L\") ^ (filename in files_with_swapped_masks): y = y[40: 104, 78: 142, 49: 97]", "+ '_gt.nii.gz'), name=study_name, group_id=None )) label_names = ['background', 'hippocampus'] super().__init__(instances, name=name, label_names=label_names, modality='T1w", "segmentation files match = re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\", filename) if match is None: raise Exception(f\"A file", "is either: \"Training\", \"Validation\" or \"All\" default = {\"Part\": \"All\"} if subset is", "needed if filename in files_with_swapped_masks: study_name = match[0] + (\"_R\" if side ==", "For each side of the brain for side in (\"_L\", \"_R\"): study_name =", "142, 97: 145] x_cropped = x[40: 104, 78: 142, 97: 145] # Need", "mask_bbox_3D from mp.utils.load_restore import join_path class HarP(SegmentationDataset): r\"\"\"Class for the segmentation of the", "over for validation affine = np.array([[1, 0, 0, 0], [0, 1, 0, 0],", "os import re import SimpleITK as sitk import nibabel as nib import numpy", "78: 142, 97: 145] # Need to do move an axis as numpy", "Changing the study name if needed if filename in files_with_swapped_masks: study_name = match[0]", "Need to do move an axis as numpy coordinates are [z, y, x]", "# Copy the images if not done already if not os.path.isdir(dst_folder_path): _extract_images(original_data_path, dst_folder_path,", "MRI, there are 2 segmentation (left and right hippocampus) for filename in os.listdir(images_path):", "done already if not os.path.isdir(dst_folder_path): _extract_images(original_data_path, dst_folder_path, orig_folder) # Fetch all patient/study names", "= x[40: 104, 78: 142, 97: 145] # Need to do move an", "[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) images_path", "78: 142, 49: 97] x_cropped = x[40: 104, 78: 142, 49: 97] else:", "and the scans as .mnc files. \"\"\" def __init__(self, subset=None, hold_out_ixs=None): # Part", "in study_names: instances.append(SegmentationInstance( x_path=os.path.join(dataset_path, dst_folder, study_name + '.nii.gz'), y_path=os.path.join(dataset_path, dst_folder, study_name + '_gt.nii.gz'),", "is for training (100 subjects), 35 subjects are left over for validation affine", "np.min(y.flat)).astype(np.uint32) # Cropping bounds computed to fit the ground truth if (side ==", "dst_folder, study_name + '_gt.nii.gz'), name=study_name, group_id=None )) label_names = ['background', 'hippocampus'] super().__init__(instances, name=name,", "# For each side of the brain for side in (\"_L\", \"_R\"): study_name", "\"All\"} if subset is not None: default.update(subset) subset = default else: subset =", "= match[0] + (\"_R\" if side == \"_L\" else \"_L\") # Save new", "nib import numpy as np import mp.data.datasets.dataset_utils as du from mp.data.datasets.dataset_segmentation import SegmentationDataset,", "as .mnc files. \"\"\" def __init__(self, subset=None, hold_out_ixs=None): # Part is either: \"Training\",", "def _extract_images(source_path, target_path, subset): r\"\"\"Extracts images, merges mask labels (if specified) and saves", "new images so they can be loaded directly sitk.WriteImage(sitk.GetImageFromArray(y), join_path([target_path, study_name + \"_gt.nii.gz\"]))", "study_name + '_gt.nii.gz'), name=study_name, group_id=None )) label_names = ['background', 'hippocampus'] super().__init__(instances, name=name, label_names=label_names,", "import join_path class HarP(SegmentationDataset): r\"\"\"Class for the segmentation of the HarP dataset, found", "filename)) x: np.array = nib.Nifti1Image(np.asarray(minc.dataobj), affine=affine).get_data() # We need to recover the study", "(100 subjects), 35 subjects are left over for validation affine = np.array([[1, 0,", "in files_with_swapped_masks: study_name = match[0] + (\"_R\" if side == \"_L\" else \"_L\")", "segmentation task for the HarP dataset # (http://www.hippocampal-protocol.net/SOPs/index.php) # ------------------------------------------------------------------------------ import os import", "= (y - np.min(y.flat)).astype(np.uint32) # Cropping bounds computed to fit the ground truth", "mp.utils.mask_bounding_box import mask_bbox_3D from mp.utils.load_restore import join_path class HarP(SegmentationDataset): r\"\"\"Class for the segmentation", "dataset_path = os.path.join(storage_data_path, global_name) original_data_path = du.get_original_data_path(global_name) # Build instances instances = []", "os.listdir(images_path): # Loading the .mnc file and converting it to a .nii.gz file", "None: hold_out_ixs = [] global_name = 'HarP' name = du.get_dataset_name(global_name, subset) dataset_path =", "= du.get_dataset_name(global_name, subset) dataset_path = os.path.join(storage_data_path, global_name) original_data_path = du.get_original_data_path(global_name) # Build instances", "names study_names = set(file_name.split('.nii')[0].split('_gt')[0] for file_name in os.listdir(os.path.join(dataset_path, dst_folder))) for study_name in study_names:", "for the HarP dataset # (http://www.hippocampal-protocol.net/SOPs/index.php) # ------------------------------------------------------------------------------ import os import re import", "def __init__(self, subset=None, hold_out_ixs=None): # Part is either: \"Training\", \"Validation\" or \"All\" default", ")) label_names = ['background', 'hippocampus'] super().__init__(instances, name=name, label_names=label_names, modality='T1w MRI', nr_channels=1, hold_out_ixs=hold_out_ixs) def", "not None: default.update(subset) subset = default else: subset = default if hold_out_ixs is", "142, 97: 145] # Need to do move an axis as numpy coordinates", "# ------------------------------------------------------------------------------ # Hippocampus segmentation task for the HarP dataset # (http://www.hippocampal-protocol.net/SOPs/index.php) #", "= default if hold_out_ixs is None: hold_out_ixs = [] global_name = 'HarP' name", "x[40: 104, 78: 142, 97: 145] # Need to do move an axis", "if not os.path.isdir(target_path): os.makedirs(target_path) files_with_swapped_masks = {\"ADNI_007_S_1304_74384_ACPC.mnc\", \"ADNI_016_S_4121_280306_ACPC.mnc\", \"ADNI_029_S_4279_265980_ACPC.mnc\", \"ADNI_136_S_0429_109839_ACPC.mnc\"} # For each", "label_names = ['background', 'hippocampus'] super().__init__(instances, name=name, label_names=label_names, modality='T1w MRI', nr_channels=1, hold_out_ixs=hold_out_ixs) def _extract_images(source_path,", "[x, y, z] x_cropped = np.moveaxis(x_cropped, [0, 2], [2, 0]) # Changing the", "as np import mp.data.datasets.dataset_utils as du from mp.data.datasets.dataset_segmentation import SegmentationDataset, SegmentationInstance from mp.paths", "folders.append((\"100\", \"Training\")) if subset[\"Part\"] in [\"Validation\", \"All\"]: folders.append((\"35\", \"Validation\")) for orig_folder, dst_folder in", "2], [2, 0]) # Changing the study name if needed if filename in", ".mnc files. \"\"\" def __init__(self, subset=None, hold_out_ixs=None): # Part is either: \"Training\", \"Validation\"", "= set(file_name.split('.nii')[0].split('_gt')[0] for file_name in os.listdir(os.path.join(dataset_path, dst_folder))) for study_name in study_names: instances.append(SegmentationInstance( x_path=os.path.join(dataset_path,", "y = sitk.ReadImage(os.path.join(labels_path, study_name + \".nii\")) y = sitk.GetArrayFromImage(y) # Shape expected: (189,", "if side == \"_L\" else \"_L\") # Save new images so they can", "(if specified) and saves the modified images. \"\"\" # Folder 100 is for", "0], [0, 0, 1, 0], [0, 0, 0, 1]]) images_path = os.path.join(source_path, subset)", "Shape expected: (189, 233, 197) assert x.shape == y.shape # BUGFIX: Some segmentation", "either: \"Training\", \"Validation\" or \"All\" default = {\"Part\": \"All\"} if subset is not", "converting it to a .nii.gz file minc = nib.load(os.path.join(images_path, filename)) x: np.array =", "segmentation (left and right hippocampus) for filename in os.listdir(images_path): # Loading the .mnc", "be loaded directly sitk.WriteImage(sitk.GetImageFromArray(y), join_path([target_path, study_name + \"_gt.nii.gz\"])) nib.save(nib.Nifti1Image(x_cropped, affine), join_path([target_path, study_name +", "study_name in study_names: instances.append(SegmentationInstance( x_path=os.path.join(dataset_path, dst_folder, study_name + '.nii.gz'), y_path=os.path.join(dataset_path, dst_folder, study_name +", "re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\", filename) if match is None: raise Exception(f\"A file ({filename}) does not match", "= sitk.GetArrayFromImage(y) # Shape expected: (189, 233, 197) assert x.shape == y.shape #", "0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0,", "the current subset dst_folder_path = os.path.join(dataset_path, dst_folder) # Copy the images if not", "for training (100 subjects), 35 subjects are left over for validation affine =", "affine=affine).get_data() # We need to recover the study name of the image name", "specified) and saves the modified images. \"\"\" # Folder 100 is for training", "Hippocampus segmentation task for the HarP dataset # (http://www.hippocampal-protocol.net/SOPs/index.php) # ------------------------------------------------------------------------------ import os", "SegmentationInstance from mp.paths import storage_data_path from mp.utils.mask_bounding_box import mask_bbox_3D from mp.utils.load_restore import join_path", "35 subjects are left over for validation affine = np.array([[1, 0, 0, 0],", "the brain for side in (\"_L\", \"_R\"): study_name = match[0] + side y", "= [] folders = [] if subset[\"Part\"] in [\"Training\", \"All\"]: folders.append((\"100\", \"Training\")) if", "(\"_R\" if side == \"_L\" else \"_L\") # Save new images so they", "instead of {0, 1} y = (y - np.min(y.flat)).astype(np.uint32) # Cropping bounds computed", "mask labels (if specified) and saves the modified images. \"\"\" # Folder 100", "hold_out_ixs=hold_out_ixs) def _extract_images(source_path, target_path, subset): r\"\"\"Extracts images, merges mask labels (if specified) and", "bounds computed to fit the ground truth if (side == \"_L\") ^ (filename", "import numpy as np import mp.data.datasets.dataset_utils as du from mp.data.datasets.dataset_segmentation import SegmentationDataset, SegmentationInstance", "\"All\" default = {\"Part\": \"All\"} if subset is not None: default.update(subset) subset =", "to do move an axis as numpy coordinates are [z, y, x] and", "y = y[40: 104, 78: 142, 49: 97] x_cropped = x[40: 104, 78:", "do move an axis as numpy coordinates are [z, y, x] and SimpleITK's", "http://www.hippocampal-protocol.net/SOPs/index.php with the masks as .nii files and the scans as .mnc files.", "sub-folder for the current subset dst_folder_path = os.path.join(dataset_path, dst_folder) # Copy the images", "match is None: raise Exception(f\"A file ({filename}) does not match the expected file", "import re import SimpleITK as sitk import nibabel as nib import numpy as", "folders: # Paths with the sub-folder for the current subset dst_folder_path = os.path.join(dataset_path,", "0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])", "images_path = os.path.join(source_path, subset) labels_path = os.path.join(source_path, f'Labels_{subset}_NIFTI') # Create directories if not", "need to recover the study name of the image name to construct the", "not os.path.isdir(target_path): os.makedirs(target_path) files_with_swapped_masks = {\"ADNI_007_S_1304_74384_ACPC.mnc\", \"ADNI_016_S_4121_280306_ACPC.mnc\", \"ADNI_029_S_4279_265980_ACPC.mnc\", \"ADNI_136_S_0429_109839_ACPC.mnc\"} # For each MRI,", "142, 49: 97] else: y = y[40: 104, 78: 142, 97: 145] x_cropped", "x: np.array = nib.Nifti1Image(np.asarray(minc.dataobj), affine=affine).get_data() # We need to recover the study name", "file_name in os.listdir(os.path.join(dataset_path, dst_folder))) for study_name in study_names: instances.append(SegmentationInstance( x_path=os.path.join(dataset_path, dst_folder, study_name +", "= y[40: 104, 78: 142, 49: 97] x_cropped = x[40: 104, 78: 142,", "mp.data.datasets.dataset_segmentation import SegmentationDataset, SegmentationInstance from mp.paths import storage_data_path from mp.utils.mask_bounding_box import mask_bbox_3D from", "labels (if specified) and saves the modified images. \"\"\" # Folder 100 is", "hold_out_ixs is None: hold_out_ixs = [] global_name = 'HarP' name = du.get_dataset_name(global_name, subset)", "[0, 0, 1, 0], [0, 0, 0, 1]]) images_path = os.path.join(source_path, subset) labels_path", "1]]) images_path = os.path.join(source_path, subset) labels_path = os.path.join(source_path, f'Labels_{subset}_NIFTI') # Create directories if", "or \"All\" default = {\"Part\": \"All\"} if subset is not None: default.update(subset) subset", "For each MRI, there are 2 segmentation (left and right hippocampus) for filename", "x.shape == y.shape # BUGFIX: Some segmentation have some weird values eg {26896.988,", "dst_folder, study_name + '.nii.gz'), y_path=os.path.join(dataset_path, dst_folder, study_name + '_gt.nii.gz'), name=study_name, group_id=None )) label_names", "and converting it to a .nii.gz file minc = nib.load(os.path.join(images_path, filename)) x: np.array", "197) assert x.shape == y.shape # BUGFIX: Some segmentation have some weird values", "r\"\"\"Extracts images, merges mask labels (if specified) and saves the modified images. \"\"\"", "subset) dataset_path = os.path.join(storage_data_path, global_name) original_data_path = du.get_original_data_path(global_name) # Build instances instances =", "= os.path.join(source_path, subset) labels_path = os.path.join(source_path, f'Labels_{subset}_NIFTI') # Create directories if not os.path.isdir(target_path):", "the study name if needed if filename in files_with_swapped_masks: study_name = match[0] +", "# Fetch all patient/study names study_names = set(file_name.split('.nii')[0].split('_gt')[0] for file_name in os.listdir(os.path.join(dataset_path, dst_folder)))", "the images if not done already if not os.path.isdir(dst_folder_path): _extract_images(original_data_path, dst_folder_path, orig_folder) #", "file ({filename}) does not match the expected file naming format\") # For each", "import os import re import SimpleITK as sitk import nibabel as nib import", "\"Validation\" or \"All\" default = {\"Part\": \"All\"} if subset is not None: default.update(subset)", "['background', 'hippocampus'] super().__init__(instances, name=name, label_names=label_names, modality='T1w MRI', nr_channels=1, hold_out_ixs=hold_out_ixs) def _extract_images(source_path, target_path, subset):", "there are 2 segmentation (left and right hippocampus) for filename in os.listdir(images_path): #", "expected file naming format\") # For each side of the brain for side", "(filename in files_with_swapped_masks): y = y[40: 104, 78: 142, 49: 97] x_cropped =", "is not None: default.update(subset) subset = default else: subset = default if hold_out_ixs", "the name of the segmentation files match = re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\", filename) if match is", "# Folder 100 is for training (100 subjects), 35 subjects are left over", "all patient/study names study_names = set(file_name.split('.nii')[0].split('_gt')[0] for file_name in os.listdir(os.path.join(dataset_path, dst_folder))) for study_name", "= os.path.join(source_path, f'Labels_{subset}_NIFTI') # Create directories if not os.path.isdir(target_path): os.makedirs(target_path) files_with_swapped_masks = {\"ADNI_007_S_1304_74384_ACPC.mnc\",", "{\"ADNI_007_S_1304_74384_ACPC.mnc\", \"ADNI_016_S_4121_280306_ACPC.mnc\", \"ADNI_029_S_4279_265980_ACPC.mnc\", \"ADNI_136_S_0429_109839_ACPC.mnc\"} # For each MRI, there are 2 segmentation (left", "SimpleITK's are [x, y, z] x_cropped = np.moveaxis(x_cropped, [0, 2], [2, 0]) #", "instances.append(SegmentationInstance( x_path=os.path.join(dataset_path, dst_folder, study_name + '.nii.gz'), y_path=os.path.join(dataset_path, dst_folder, study_name + '_gt.nii.gz'), name=study_name, group_id=None", "= os.path.join(dataset_path, dst_folder) # Copy the images if not done already if not", "y = sitk.GetArrayFromImage(y) # Shape expected: (189, 233, 197) assert x.shape == y.shape", "[] folders = [] if subset[\"Part\"] in [\"Training\", \"All\"]: folders.append((\"100\", \"Training\")) if subset[\"Part\"]", "for filename in os.listdir(images_path): # Loading the .mnc file and converting it to", "are [z, y, x] and SimpleITK's are [x, y, z] x_cropped = np.moveaxis(x_cropped,", "[\"Validation\", \"All\"]: folders.append((\"35\", \"Validation\")) for orig_folder, dst_folder in folders: # Paths with the", "eg {26896.988, 26897.988} instead of {0, 1} y = (y - np.min(y.flat)).astype(np.uint32) #", "orig_folder, dst_folder in folders: # Paths with the sub-folder for the current subset", "\"All\"]: folders.append((\"35\", \"Validation\")) for orig_folder, dst_folder in folders: # Paths with the sub-folder", "= np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0],", "= match[0] + side y = sitk.ReadImage(os.path.join(labels_path, study_name + \".nii\")) y = sitk.GetArrayFromImage(y)", "are [x, y, z] x_cropped = np.moveaxis(x_cropped, [0, 2], [2, 0]) # Changing", "current subset dst_folder_path = os.path.join(dataset_path, dst_folder) # Copy the images if not done", "SimpleITK as sitk import nibabel as nib import numpy as np import mp.data.datasets.dataset_utils", "subjects are left over for validation affine = np.array([[1, 0, 0, 0], [0,", "hold_out_ixs = [] global_name = 'HarP' name = du.get_dataset_name(global_name, subset) dataset_path = os.path.join(storage_data_path,", "== y.shape # BUGFIX: Some segmentation have some weird values eg {26896.988, 26897.988}", "nib.load(os.path.join(images_path, filename)) x: np.array = nib.Nifti1Image(np.asarray(minc.dataobj), affine=affine).get_data() # We need to recover the", "already if not os.path.isdir(dst_folder_path): _extract_images(original_data_path, dst_folder_path, orig_folder) # Fetch all patient/study names study_names", "if (side == \"_L\") ^ (filename in files_with_swapped_masks): y = y[40: 104, 78:", "# Paths with the sub-folder for the current subset dst_folder_path = os.path.join(dataset_path, dst_folder)", "segmentation have some weird values eg {26896.988, 26897.988} instead of {0, 1} y", "the segmentation files match = re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\", filename) if match is None: raise Exception(f\"A", "= {\"Part\": \"All\"} if subset is not None: default.update(subset) subset = default else:", "expected: (189, 233, 197) assert x.shape == y.shape # BUGFIX: Some segmentation have", "1} y = (y - np.min(y.flat)).astype(np.uint32) # Cropping bounds computed to fit the", "0, 1, 0], [0, 0, 0, 1]]) images_path = os.path.join(source_path, subset) labels_path =", "y.shape # BUGFIX: Some segmentation have some weird values eg {26896.988, 26897.988} instead", "storage_data_path from mp.utils.mask_bounding_box import mask_bbox_3D from mp.utils.load_restore import join_path class HarP(SegmentationDataset): r\"\"\"Class for", "({filename}) does not match the expected file naming format\") # For each side", "subset dst_folder_path = os.path.join(dataset_path, dst_folder) # Copy the images if not done already", "name if needed if filename in files_with_swapped_masks: study_name = match[0] + (\"_R\" if", "global_name) original_data_path = du.get_original_data_path(global_name) # Build instances instances = [] folders = []", "construct the name of the segmentation files match = re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\", filename) if match", "= os.path.join(storage_data_path, global_name) original_data_path = du.get_original_data_path(global_name) # Build instances instances = [] folders", "y = (y - np.min(y.flat)).astype(np.uint32) # Cropping bounds computed to fit the ground", "Exception(f\"A file ({filename}) does not match the expected file naming format\") # For", "study_names = set(file_name.split('.nii')[0].split('_gt')[0] for file_name in os.listdir(os.path.join(dataset_path, dst_folder))) for study_name in study_names: instances.append(SegmentationInstance(", "folders = [] if subset[\"Part\"] in [\"Training\", \"All\"]: folders.append((\"100\", \"Training\")) if subset[\"Part\"] in", "saves the modified images. \"\"\" # Folder 100 is for training (100 subjects),", "as sitk import nibabel as nib import numpy as np import mp.data.datasets.dataset_utils as", "image name to construct the name of the segmentation files match = re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\",", "# Hippocampus segmentation task for the HarP dataset # (http://www.hippocampal-protocol.net/SOPs/index.php) # ------------------------------------------------------------------------------ import", "104, 78: 142, 97: 145] # Need to do move an axis as", "hold_out_ixs=None): # Part is either: \"Training\", \"Validation\" or \"All\" default = {\"Part\": \"All\"}", "file minc = nib.load(os.path.join(images_path, filename)) x: np.array = nib.Nifti1Image(np.asarray(minc.dataobj), affine=affine).get_data() # We need", "y, x] and SimpleITK's are [x, y, z] x_cropped = np.moveaxis(x_cropped, [0, 2],", "and right hippocampus) for filename in os.listdir(images_path): # Loading the .mnc file and", "for the current subset dst_folder_path = os.path.join(dataset_path, dst_folder) # Copy the images if", "are 2 segmentation (left and right hippocampus) for filename in os.listdir(images_path): # Loading", "100 is for training (100 subjects), 35 subjects are left over for validation", "images, merges mask labels (if specified) and saves the modified images. \"\"\" #", "\"_R\"): study_name = match[0] + side y = sitk.ReadImage(os.path.join(labels_path, study_name + \".nii\")) y", "for study_name in study_names: instances.append(SegmentationInstance( x_path=os.path.join(dataset_path, dst_folder, study_name + '.nii.gz'), y_path=os.path.join(dataset_path, dst_folder, study_name", "import SegmentationDataset, SegmentationInstance from mp.paths import storage_data_path from mp.utils.mask_bounding_box import mask_bbox_3D from mp.utils.load_restore", "files match = re.match(r\"ADNI_[0-9]+_S_[0-9]+_[0-9]+\", filename) if match is None: raise Exception(f\"A file ({filename})", "SegmentationDataset, SegmentationInstance from mp.paths import storage_data_path from mp.utils.mask_bounding_box import mask_bbox_3D from mp.utils.load_restore import", "super().__init__(instances, name=name, label_names=label_names, modality='T1w MRI', nr_channels=1, hold_out_ixs=hold_out_ixs) def _extract_images(source_path, target_path, subset): r\"\"\"Extracts images,", "axis as numpy coordinates are [z, y, x] and SimpleITK's are [x, y,", "original_data_path = du.get_original_data_path(global_name) # Build instances instances = [] folders = [] if", "_extract_images(original_data_path, dst_folder_path, orig_folder) # Fetch all patient/study names study_names = set(file_name.split('.nii')[0].split('_gt')[0] for file_name", "os.path.join(source_path, subset) labels_path = os.path.join(source_path, f'Labels_{subset}_NIFTI') # Create directories if not os.path.isdir(target_path): os.makedirs(target_path)", "sitk.ReadImage(os.path.join(labels_path, study_name + \".nii\")) y = sitk.GetArrayFromImage(y) # Shape expected: (189, 233, 197)", "0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) images_path = os.path.join(source_path,", "in os.listdir(images_path): # Loading the .mnc file and converting it to a .nii.gz", "x_path=os.path.join(dataset_path, dst_folder, study_name + '.nii.gz'), y_path=os.path.join(dataset_path, dst_folder, study_name + '_gt.nii.gz'), name=study_name, group_id=None ))" ]
[ "def buildTransformationName(roi, representation, transformer, input_transformation, nodeid): if input_transformation is None: return f\"{transformer.name}_rep-{representation.id}_roi-{roi.id}_node-{nodeid}\" else:", "representation, transformer, input_transformation, nodeid): if input_transformation is None: return f\"{transformer.name}_rep-{representation.id}_roi-{roi.id}_node-{nodeid}\" else: return f\"{transformer.name}_trans-{input_transformation.id}_rep-{representation.id}_roi-{roi.id}_node-{nodeid}\"", "is not None: return f\"{name} {nodeid}\" else: return f\"{name}\" def buildTransformationName(roi, representation, transformer,", "return f\"{name} {nodeid}\" else: return f\"{name}\" def buildTransformationName(roi, representation, transformer, input_transformation, nodeid): if", "None: return f\"{name} {nodeid}\" else: return f\"{name}\" def buildTransformationName(roi, representation, transformer, input_transformation, nodeid):", "else: return f\"{name}\" def buildTransformationName(roi, representation, transformer, input_transformation, nodeid): if input_transformation is None:", "return f\"{name}\" def buildTransformationName(roi, representation, transformer, input_transformation, nodeid): if input_transformation is None: return", "if nodeid is not None: return f\"{name} {nodeid}\" else: return f\"{name}\" def buildTransformationName(roi,", "nodeid): if nodeid is not None: return f\"{name} {nodeid}\" else: return f\"{name}\" def", "not None: return f\"{name} {nodeid}\" else: return f\"{name}\" def buildTransformationName(roi, representation, transformer, input_transformation,", "f\"{name}\" def buildTransformationName(roi, representation, transformer, input_transformation, nodeid): if input_transformation is None: return f\"{transformer.name}_rep-{representation.id}_roi-{roi.id}_node-{nodeid}\"", "{nodeid}\" else: return f\"{name}\" def buildTransformationName(roi, representation, transformer, input_transformation, nodeid): if input_transformation is", "buildRepresentationName(name, nodeid): if nodeid is not None: return f\"{name} {nodeid}\" else: return f\"{name}\"", "buildTransformationName(roi, representation, transformer, input_transformation, nodeid): if input_transformation is None: return f\"{transformer.name}_rep-{representation.id}_roi-{roi.id}_node-{nodeid}\" else: return", "f\"{name} {nodeid}\" else: return f\"{name}\" def buildTransformationName(roi, representation, transformer, input_transformation, nodeid): if input_transformation", "def buildRepresentationName(name, nodeid): if nodeid is not None: return f\"{name} {nodeid}\" else: return", "nodeid is not None: return f\"{name} {nodeid}\" else: return f\"{name}\" def buildTransformationName(roi, representation," ]
[ "image_files: image_file = os.path.join(folder, image) try: image_data = (ndimage.imread(image_file).astype(float) - pixel_depth / 2)", "% set_filename) dataset = load_letter(folder, min_num_images_per_class) try: with open(set_filename, 'wb') as f: pickle.dump(dataset,", "= merge_datasets( train_datasets, train_size, valid_size) _, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size) indices", "dataset, labels): X = np.reshape(dataset, (dataset.shape[0],-1)) y = labels return model.score(X, y) def", "== 0: sys.stdout.write(\"%s%%\" % percent) sys.stdout.flush() else: sys.stdout.write(\".\") sys.stdout.flush() last_percent_reported = percent def", "remove .tar.gz if os.path.isdir(root) and not force: # You may override by setting", "valid_size // num_classes tsize_per_class = train_size // num_classes start_v, start_t = 0, 0", "valid_test_similar) try: f = open(sanit_pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels,", "[ os.path.join(root, d) for d in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, d))] if len(data_folders) !=", "# show_images(valid_dataset, valid_labels, 3) pickle_file = 'notMNIST.pickle' if not os.path.exists(pickle_file): train_size = 200000", "!= (image_size, image_size): raise Exception('Unexpected image shape: %s' % str(image_data.shape)) dataset[num_images, :, :]", "the letters to have random validation and training set np.random.shuffle(letter_set) if valid_dataset is", "dataset_names = [] for folder in data_folders: set_filename = folder + '.pickle' dataset_names.append(set_filename)", "train_datasets, train_size, valid_size) _, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size) indices = np.arange(train_dataset.shape[0])", "pickle_file, ':', e) raise train_dataset, train_labels, filtered_valid_dataset, filtered_valid_labels, filtered_test_dataset, filtered_test_labels = load_datasets(sanit_pickle_file) print('Training", "is None: size = maxSize elif size > maxSize: size = maxSize else:", "filename, filename, reporthook=download_progress_hook) print('\\nDownload Complete!') statinfo = os.stat(filename) if statinfo.st_size == expected_bytes: print('Found", "print(smallNameJ) # smallDataJ = load_dataset(smallNameJ) # img2 = smallDataJ[0, :, :] # plt.matshow(img2,", "print(largeNameA) # largeDataA = load_dataset(largeNameA) # img1 = largeDataA[0, :, :] # plt.matshow(img1,", "size = maxSize elif size > maxSize: size = maxSize else: dataset =", "maxSize: size = maxSize else: dataset = dataset[0:size] labels = labels[0:size] X =", "valid_labels = save['valid_labels'] test_dataset = save['test_dataset'] test_labels = save['test_labels'] return train_dataset, train_labels, valid_dataset,", "size in [50, 100, 1000, 5000]: train(size) # training on all examples: #train()", "os import sys import tarfile from IPython.display import display, Image from scipy import", "size.\"\"\" if force or not os.path.exists(filename): print('Attempting to download:', filename) filename, _ =", "train_dataset, 'train_labels': train_labels, 'valid_dataset': valid_dataset, 'valid_labels': valid_labels, 'test_dataset': test_dataset, 'test_labels': test_labels, } pickle.dump(save,", "# show_images(test_dataset, test_labels, 3) # show_images(valid_dataset, valid_labels, 3) pickle_file = 'notMNIST.pickle' if not", "valid_dataset.shape, valid_labels.shape) print('Testing:', test_dataset.shape, test_labels.shape) def sanitize_dataset(dataset, labels, filter_dataset, similarity_epsilon): similarity = cosine_similarity(np.reshape(dataset,", "code changed to Python3 import matplotlib import matplotlib.pyplot as plt import numpy as", "train_letter train_labels[start_t:end_t] = label start_t += tsize_per_class end_t += tsize_per_class except Exception as", "data_folders = [ os.path.join(root, d) for d in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, d))] if", "None: valid_letter = letter_set[:vsize_per_class, :, :] valid_dataset[start_v:end_v, :, :] = valid_letter valid_labels[start_v:end_v] =", "np.reshape(filter_dataset, (filter_dataset.shape[0],-1))) same_filter = np.sum(similarity == 1, axis=1) > 0 similar_filter = np.sum(similarity", "filtered_test_labels, filtered_valid_dataset, 0.001) print(\"validation-testing: same=\", valid_test_same, \"similar=\", valid_test_similar) try: f = open(sanit_pickle_file, 'wb')", "(dataset.shape[0],-1)), np.reshape(filter_dataset, (filter_dataset.shape[0],-1))) same_filter = np.sum(similarity == 1, axis=1) > 0 similar_filter =", "ndimage from sklearn.linear_model import LogisticRegression from sklearn.metrics.pairwise import cosine_similarity from urllib.request import urlretrieve", ":] = valid_letter valid_labels[start_v:end_v] = label start_v += vsize_per_class end_v += vsize_per_class train_letter", "plt.show() # # smallNameJ = test_datasets[9] # print(smallNameJ) # smallDataJ = load_dataset(smallNameJ) #", "= np.ndarray((nb_rows, img_size, img_size), dtype=np.float32) labels = np.ndarray(nb_rows, dtype=np.int32) else: dataset, labels =", "train_labels, filtered_valid_dataset, filtered_valid_labels, filtered_test_dataset, filtered_test_labels = load_datasets(sanit_pickle_file) print('Training (sanitized):', train_dataset.shape, train_labels.shape) print('Validation (sanitized):',", "test_labels, train_dataset, 0.001) print(\"training-testing: same=\", train_test_same, \"similar=\", train_test_similar) filtered_test_dataset, filtered_test_labels, valid_test_same, valid_test_similar =", "':', e) raise def load_datasets(pickle_file): statinfo = os.stat(pickle_file) print('Compressed pickle size:', statinfo.st_size) f", "percent def maybe_download(filename, expected_bytes, force=False): \"\"\"Download a file if not present, and make", "print('Training (sanitized):', train_dataset.shape, train_labels.shape) print('Validation (sanitized):', filtered_valid_dataset.shape, filtered_valid_labels.shape) print('Testing (sanitized):', filtered_test_dataset.shape, filtered_test_labels.shape) def", "a single letter label.\"\"\" image_files = os.listdir(folder) dataset = np.ndarray(shape=(len(image_files), image_size, image_size), dtype=np.float32)", "% (num_images, min_num_images)) print('Full dataset tensor:', dataset.shape) print('Mean:', np.mean(dataset)) print('Standard deviation:', np.std(dataset)) return", "load_datasets(pickle_file) print('Training:', train_dataset.shape, train_labels.shape) print('Validation:', valid_dataset.shape, valid_labels.shape) print('Testing:', test_dataset.shape, test_labels.shape) def sanitize_dataset(dataset, labels,", "largeDataA[0, :, :] # plt.matshow(img1, cmap=plt.cm.gray) # plt.show() # # smallNameJ = test_datasets[9]", "not os.path.exists(filename): print('Attempting to download:', filename) filename, _ = urlretrieve(url + filename, filename,", "by setting force=True. print('%s already present - Skipping extraction of %s.' % (root,", "raise Exception( 'Expected %d folders, one per class. Found %d instead.' % (", "let's shuffle the letters to have random validation and training set np.random.shuffle(letter_set) if", "# for i in range(0,count): # print(labels[i]) # plt.matshow(dataset[i,:,:], cmap=plt.cm.gray) # plt.show() #", "statinfo = os.stat(filename) if statinfo.st_size == expected_bytes: print('Found and verified', filename) else: raise", "np import os import sys import tarfile from IPython.display import display, Image from", "Config the matlotlib backend as plotting inline in IPython # %matplotlib inline url", "'- it\\'s ok, skipping.') dataset = dataset[0:num_images, :, :] if num_images < min_num_images:", "print(\"Training with all examples:\") else: print(\"Training with \", size, \" examples:\") model =", "= { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': valid_dataset, 'valid_labels': valid_labels, 'test_dataset': test_dataset, 'test_labels':", "if os.path.isdir(os.path.join(root, d))] if len(data_folders) != num_classes: raise Exception( 'Expected %d folders, one", "verified', filename) else: raise Exception( 'Failed to verify ' + filename + '.", "get to it with a browser?') return filename train_filename = maybe_download('notMNIST_large.tar.gz', 247336696) test_filename", "as f: pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable to save data", "expected: %d < %d' % (num_images, min_num_images)) print('Full dataset tensor:', dataset.shape) print('Mean:', np.mean(dataset))", "inline url = 'http://commondatastorage.googleapis.com/books1000/' last_percent_reported = None def download_progress_hook(count, blockSize, totalSize): \"\"\"A hook", "filename train_filename = maybe_download('notMNIST_large.tar.gz', 247336696) test_filename = maybe_download('notMNIST_small.tar.gz', 8458043) num_classes = 10 np.random.seed(133)", "= None def download_progress_hook(count, blockSize, totalSize): \"\"\"A hook to report the progress of", ".tar.gz if os.path.isdir(root) and not force: # You may override by setting force=True.", "Exception( 'Expected %d folders, one per class. Found %d instead.' % ( num_classes,", "\"\"\"Load the data for a single letter label.\"\"\" image_files = os.listdir(folder) dataset =", "last_percent_reported != percent: if percent % 5 == 0: sys.stdout.write(\"%s%%\" % percent) sys.stdout.flush()", "= len(pickle_files) valid_dataset, valid_labels = make_arrays(valid_size, image_size) train_dataset, train_labels = make_arrays(train_size, image_size) vsize_per_class", "end_v += vsize_per_class train_letter = letter_set[vsize_per_class:end_l, :, :] train_dataset[start_t:end_t, :, :] = train_letter", "inline in IPython # %matplotlib inline url = 'http://commondatastorage.googleapis.com/books1000/' last_percent_reported = None def", ":] train_dataset[start_t:end_t, :, :] = train_letter train_labels[start_t:end_t] = label start_t += tsize_per_class end_t", "valid_labels, train_dataset, train_labels = merge_datasets( train_datasets, train_size, valid_size) _, _, test_dataset, test_labels =", "print('Testing (sanitized):', filtered_test_dataset.shape, filtered_test_labels.shape) def train_model(dataset, labels, size=None): maxSize = dataset.shape[0] if size", "internet connections. Reports every 1% change in download progress. \"\"\" global last_percent_reported percent", "e, '- it\\'s ok, skipping.') dataset = dataset[0:num_images, :, :] if num_images <", "img_size): if nb_rows: dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32) labels = np.ndarray(nb_rows, dtype=np.int32)", "import os import sys import tarfile from IPython.display import display, Image from scipy", "sklearn.linear_model import LogisticRegression from sklearn.metrics.pairwise import cosine_similarity from urllib.request import urlretrieve import pickle", "the data is balanced between classes # for name in train_datasets: # dataset", "= open(sanit_pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': filtered_valid_dataset, 'valid_labels':", "%matplotlib inline url = 'http://commondatastorage.googleapis.com/books1000/' last_percent_reported = None def download_progress_hook(count, blockSize, totalSize): \"\"\"A", "tar = tarfile.open(filename) sys.stdout.flush() tar.extractall() tar.close() data_folders = [ os.path.join(root, d) for d", "in range(0,count): # print(labels[i]) # plt.matshow(dataset[i,:,:], cmap=plt.cm.gray) # plt.show() # show_images(train_dataset, train_labels, 3)", "force or not os.path.exists(filename): print('Attempting to download:', filename) filename, _ = urlretrieve(url +", "plt.matshow(dataset[i,:,:], cmap=plt.cm.gray) # plt.show() # show_images(train_dataset, train_labels, 3) # show_images(test_dataset, test_labels, 3) #", "train_size, valid_size) _, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size) indices = np.arange(train_dataset.shape[0]) np.random.shuffle(indices)", "from sklearn.linear_model import LogisticRegression from sklearn.metrics.pairwise import cosine_similarity from urllib.request import urlretrieve import", "import cosine_similarity from urllib.request import urlretrieve import pickle import IPython # Config the", "= valid_size // num_classes tsize_per_class = train_size // num_classes start_v, start_t = 0,", "You may override by setting force=True. print('%s already present - Skipping pickling.' %", "with open(set_filename, 'wb') as f: pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable", "force=True. print('%s already present - Skipping pickling.' % set_filename) else: print('Pickling %s.' %", "np.sum(same_filter) similar_count = np.sum(similar_filter) filtered_dataset = dataset[same_filter==False] filtered_labels = labels[same_filter==False] return filtered_dataset, filtered_labels,", "train_labels[start_t:end_t] = label start_t += tsize_per_class end_t += tsize_per_class except Exception as e:", "else: dataset, labels = None, None return dataset, labels def merge_datasets(pickle_files, train_size, valid_size=0):", "if os.path.exists(set_filename) and not force: # You may override by setting force=True. print('%s", "backend as plotting inline in IPython # %matplotlib inline url = 'http://commondatastorage.googleapis.com/books1000/' last_percent_reported", "the modules we'll be using later. Make sure you can import them #", "# remove .tar.gz if os.path.isdir(root) and not force: # You may override by", "{ 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': valid_dataset, 'valid_labels': valid_labels, 'test_dataset': test_dataset, 'test_labels': test_labels,", "size > maxSize: size = maxSize else: dataset = dataset[0:size] labels = labels[0:size]", "are all the modules we'll be using later. Make sure you can import", "%s. This may take a while. Please wait.' % root) tar = tarfile.open(filename)", "per pixel. def load_letter(folder, min_num_images): \"\"\"Load the data for a single letter label.\"\"\"", "'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': filtered_valid_dataset, 'valid_labels': filtered_valid_labels, 'test_dataset': filtered_test_dataset, 'test_labels': filtered_test_labels, }", "print(\"Training with \", size, \" examples:\") model = train_model(train_dataset, train_labels, size) print(\" validation", "os.path.exists(filename): print('Attempting to download:', filename) filename, _ = urlretrieve(url + filename, filename, reporthook=download_progress_hook)", "valid_labels)) print(\" test score: \", model_score(model, test_dataset, test_labels)) print(\" validation score (sanitized): \",", "+ filename + '. Can you get to it with a browser?') return", "open(filename, 'rb') as f: return pickle.load(f) # Display a random matrix with a", "test score (sanitized): \", model_score(model, filtered_test_dataset, filtered_test_labels)) for size in [50, 100, 1000,", "deviation:', np.std(dataset)) return dataset def maybe_pickle(data_folders, min_num_images_per_class, force=False): dataset_names = [] for folder", "%d folders, one per class. Found %d instead.' % ( num_classes, len(data_folders))) print(data_folders)", "make_arrays(valid_size, image_size) train_dataset, train_labels = make_arrays(train_size, image_size) vsize_per_class = valid_size // num_classes tsize_per_class", "tsize_per_class = train_size // num_classes start_v, start_t = 0, 0 end_v, end_t =", "labels, filter_dataset, similarity_epsilon): similarity = cosine_similarity(np.reshape(dataset, (dataset.shape[0],-1)), np.reshape(filter_dataset, (filter_dataset.shape[0],-1))) same_filter = np.sum(similarity ==", "= dataset[same_filter==False] filtered_labels = labels[same_filter==False] return filtered_dataset, filtered_labels, same_count, similar_count sanit_pickle_file = 'notMNIST_sanit.pickle'", "similar_count = np.sum(similar_filter) filtered_dataset = dataset[same_filter==False] filtered_labels = labels[same_filter==False] return filtered_dataset, filtered_labels, same_count,", "np.ndarray((nb_rows, img_size, img_size), dtype=np.float32) labels = np.ndarray(nb_rows, dtype=np.int32) else: dataset, labels = None,", "already present - Skipping extraction of %s.' % (root, filename)) else: print('Extracting data", "same=\", valid_test_same, \"similar=\", valid_test_similar) try: f = open(sanit_pickle_file, 'wb') save = { 'train_dataset':", "\"\"\"A hook to report the progress of a download. This is mostly intended", "save = pickle.load(f) f.close() train_dataset = save['train_dataset'] train_labels = save['train_labels'] valid_dataset = save['valid_dataset']", "labels): X = np.reshape(dataset, (dataset.shape[0],-1)) y = labels return model.score(X, y) def train(size=None):", "#IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png') image_size = 28 # Pixel width and height. pixel_depth = 255.0 #", "extraction of %s.' % (root, filename)) else: print('Extracting data for %s. This may", "levels per pixel. def load_letter(folder, min_num_images): \"\"\"Load the data for a single letter", "print('Pickling %s.' % set_filename) dataset = load_letter(folder, min_num_images_per_class) try: with open(set_filename, 'wb') as", "letter_set[vsize_per_class:end_l, :, :] train_dataset[start_t:end_t, :, :] = train_letter train_labels[start_t:end_t] = label start_t +=", "lr = LogisticRegression(n_jobs=4) lr.fit(X, y) return lr def model_score(model, dataset, labels): X =", "Pixel width and height. pixel_depth = 255.0 # Number of levels per pixel.", "try: f = open(sanit_pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset':", "folder + '.pickle' dataset_names.append(set_filename) if os.path.exists(set_filename) and not force: # You may override", "from sklearn.metrics.pairwise import cosine_similarity from urllib.request import urlretrieve import pickle import IPython #", "y) def train(size=None): if size is None: print(\"Training with all examples:\") else: print(\"Training", "classes # for name in train_datasets: # dataset = load_dataset(name) # print(name, '", "+ filename, filename, reporthook=download_progress_hook) print('\\nDownload Complete!') statinfo = os.stat(filename) if statinfo.st_size == expected_bytes:", "set_filename = folder + '.pickle' dataset_names.append(set_filename) if os.path.exists(set_filename) and not force: # You", "= folder + '.pickle' dataset_names.append(set_filename) if os.path.exists(set_filename) and not force: # You may", "= test_datasets[9] # print(smallNameJ) # smallDataJ = load_dataset(smallNameJ) # img2 = smallDataJ[0, :,", "test_labels train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels = load_datasets(pickle_file) print('Training:', train_dataset.shape, train_labels.shape) print('Validation:',", "= train_letter train_labels[start_t:end_t] = label start_t += tsize_per_class end_t += tsize_per_class except Exception", "to', pickle_file, ':', e) raise def load_datasets(pickle_file): statinfo = os.stat(pickle_file) print('Compressed pickle size:',", "root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz if os.path.isdir(root) and not force: # You", "score (sanitized): \", model_score(model, filtered_valid_dataset, filtered_valid_labels)) print(\" test score (sanitized): \", model_score(model, filtered_test_dataset,", "filtered_valid_dataset, filtered_valid_labels, filtered_test_dataset, filtered_test_labels = load_datasets(sanit_pickle_file) print('Training (sanitized):', train_dataset.shape, train_labels.shape) print('Validation (sanitized):', filtered_valid_dataset.shape,", "= load_datasets(pickle_file) print('Training:', train_dataset.shape, train_labels.shape) print('Validation:', valid_dataset.shape, valid_labels.shape) print('Testing:', test_dataset.shape, test_labels.shape) def sanitize_dataset(dataset,", "save['test_labels'] return train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels train_dataset, train_labels, valid_dataset, valid_labels, test_dataset,", "smallDataJ[0, :, :] # plt.matshow(img2, cmap=plt.cm.gray) # plt.show() # Check whether the data", ":, :] = train_letter train_labels[start_t:end_t] = label start_t += tsize_per_class end_t += tsize_per_class", "similarity_epsilon): similarity = cosine_similarity(np.reshape(dataset, (dataset.shape[0],-1)), np.reshape(filter_dataset, (filter_dataset.shape[0],-1))) same_filter = np.sum(similarity == 1, axis=1)", "valid_labels, train_dataset, train_labels # def show_images(dataset, labels, count): # for i in range(0,count):", "X = np.reshape(dataset, (dataset.shape[0],-1)) y = labels return model.score(X, y) def train(size=None): if", "test_size) indices = np.arange(train_dataset.shape[0]) np.random.shuffle(indices) train_dataset = train_dataset[indices] train_labels = train_labels[indices] try: f", "np.ndarray(nb_rows, dtype=np.int32) else: dataset, labels = None, None return dataset, labels def merge_datasets(pickle_files,", "image_size, image_size), dtype=np.float32) print(folder) num_images = 0 for image in image_files: image_file =", "plt.matshow(img1, cmap=plt.cm.gray) # plt.show() # # smallNameJ = test_datasets[9] # print(smallNameJ) # smallDataJ", "Complete!') statinfo = os.stat(filename) if statinfo.st_size == expected_bytes: print('Found and verified', filename) else:", "e: print('Unable to save data to', set_filename, ':', e) return dataset_names train_datasets =", "train_dataset = train_dataset[indices] train_labels = train_labels[indices] try: f = open(pickle_file, 'wb') save =", "\\ sanitize_dataset(valid_dataset, valid_labels, train_dataset, 0.001) print(\"training-validation: same=\", train_valid_same, \"similar=\", train_valid_similar) filtered_test_dataset, filtered_test_labels, train_test_same,", "sure you can import them # before proceeding further. # code changed to", "train_letter = letter_set[vsize_per_class:end_l, :, :] train_dataset[start_t:end_t, :, :] = train_letter train_labels[start_t:end_t] = label", "not present, and make sure it's the right size.\"\"\" if force or not", "force=True. print('%s already present - Skipping extraction of %s.' % (root, filename)) else:", "= labels[0:size] X = np.reshape(dataset, (size,-1)) y = labels lr = LogisticRegression(n_jobs=4) lr.fit(X,", "'Expected %d folders, one per class. Found %d instead.' % ( num_classes, len(data_folders)))", "filtered_valid_labels)) print(\" test score (sanitized): \", model_score(model, filtered_test_dataset, filtered_test_labels)) for size in [50,", "train_dataset, train_labels = merge_datasets( train_datasets, train_size, valid_size) _, _, test_dataset, test_labels = merge_datasets(test_datasets,", "pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as e: print('Unable to save data to',", "not force: # You may override by setting force=True. print('%s already present -", "f = open(pickle_file, 'rb') save = pickle.load(f) f.close() train_dataset = save['train_dataset'] train_labels =", "browser?') return filename train_filename = maybe_download('notMNIST_large.tar.gz', 247336696) test_filename = maybe_download('notMNIST_small.tar.gz', 8458043) num_classes =", "\", size, \" examples:\") model = train_model(train_dataset, train_labels, size) print(\" validation score: \",", "Exception('Many fewer images than expected: %d < %d' % (num_images, min_num_images)) print('Full dataset", "< %d' % (num_images, min_num_images)) print('Full dataset tensor:', dataset.shape) print('Mean:', np.mean(dataset)) print('Standard deviation:',", "dataset.shape) # # for name in test_datasets: # dataset = load_dataset(name) # print(name,", "end_l = vsize_per_class + tsize_per_class for label, pickle_file in enumerate(pickle_files): try: with open(pickle_file,", "per class. Found %d instead.' % ( num_classes, len(data_folders))) print(data_folders) return data_folders train_folders", "train_folders = maybe_extract(train_filename) test_folders = maybe_extract(test_filename) #IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png') #IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png') image_size = 28 # Pixel", "train_labels = make_arrays(train_size, image_size) vsize_per_class = valid_size // num_classes tsize_per_class = train_size //", "train_valid_similar) filtered_test_dataset, filtered_test_labels, train_test_same, train_test_similar = \\ sanitize_dataset(test_dataset, test_labels, train_dataset, 0.001) print(\"training-testing: same=\",", "progress. \"\"\" global last_percent_reported percent = int(count * blockSize * 100 / totalSize)", ":] # plt.matshow(img1, cmap=plt.cm.gray) # plt.show() # # smallNameJ = test_datasets[9] # print(smallNameJ)", "folders, one per class. Found %d instead.' % ( num_classes, len(data_folders))) print(data_folders) return", "instead.' % ( num_classes, len(data_folders))) print(data_folders) return data_folders train_folders = maybe_extract(train_filename) test_folders =", "save['train_dataset'] train_labels = save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset = save['test_dataset']", ":] # plt.matshow(img2, cmap=plt.cm.gray) # plt.show() # Check whether the data is balanced", "[] for folder in data_folders: set_filename = folder + '.pickle' dataset_names.append(set_filename) if os.path.exists(set_filename)", "':', e) raise train_dataset, train_labels, filtered_valid_dataset, filtered_valid_labels, filtered_test_dataset, filtered_test_labels = load_datasets(sanit_pickle_file) print('Training (sanitized):',", "'valid_dataset': valid_dataset, 'valid_labels': valid_labels, 'test_dataset': test_dataset, 'test_labels': test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close()", "tsize_per_class for label, pickle_file in enumerate(pickle_files): try: with open(pickle_file, 'rb') as f: letter_set", "by setting force=True. print('%s already present - Skipping pickling.' % set_filename) else: print('Pickling", "plotting inline in IPython # %matplotlib inline url = 'http://commondatastorage.googleapis.com/books1000/' last_percent_reported = None", "def train_model(dataset, labels, size=None): maxSize = dataset.shape[0] if size is None: size =", "test_labels, 3) # show_images(valid_dataset, valid_labels, 3) pickle_file = 'notMNIST.pickle' if not os.path.exists(pickle_file): train_size", ":] if num_images < min_num_images: raise Exception('Many fewer images than expected: %d <", "'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': valid_dataset, 'valid_labels': valid_labels, 'test_dataset': test_dataset, 'test_labels': test_labels, }", "urllib.request import urlretrieve import pickle import IPython # Config the matlotlib backend as", "for %s. This may take a while. Please wait.' % root) tar =", "image_files = os.listdir(folder) dataset = np.ndarray(shape=(len(image_files), image_size, image_size), dtype=np.float32) print(folder) num_images = 0", "percent % 5 == 0: sys.stdout.write(\"%s%%\" % percent) sys.stdout.flush() else: sys.stdout.write(\".\") sys.stdout.flush() last_percent_reported", "test_labels)) print(\" validation score (sanitized): \", model_score(model, filtered_valid_dataset, filtered_valid_labels)) print(\" test score (sanitized):", "os.path.isdir(os.path.join(root, d))] if len(data_folders) != num_classes: raise Exception( 'Expected %d folders, one per", "= np.sum(similarity > 1-similarity_epsilon, axis=1) > 0 same_count = np.sum(same_filter) similar_count = np.sum(similar_filter)", "print('Mean:', np.mean(dataset)) print('Standard deviation:', np.std(dataset)) return dataset def maybe_pickle(data_folders, min_num_images_per_class, force=False): dataset_names =", "letter_set[:vsize_per_class, :, :] valid_dataset[start_v:end_v, :, :] = valid_letter valid_labels[start_v:end_v] = label start_v +=", "# print(name, ' size:', dataset.shape) def make_arrays(nb_rows, img_size): if nb_rows: dataset = np.ndarray((nb_rows,", "you get to it with a browser?') return filename train_filename = maybe_download('notMNIST_large.tar.gz', 247336696)", "mostly intended for users with slow internet connections. Reports every 1% change in", "valid_dataset, valid_labels)) print(\" test score: \", model_score(model, test_dataset, test_labels)) print(\" validation score (sanitized):", "None return dataset, labels def merge_datasets(pickle_files, train_size, valid_size=0): num_classes = len(pickle_files) valid_dataset, valid_labels", "take a while. Please wait.' % root) tar = tarfile.open(filename) sys.stdout.flush() tar.extractall() tar.close()", "matplotlib.pyplot as plt import numpy as np import os import sys import tarfile", "28 # Pixel width and height. pixel_depth = 255.0 # Number of levels", "filename) else: raise Exception( 'Failed to verify ' + filename + '. Can", "try: f = open(pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset':", "image) try: image_data = (ndimage.imread(image_file).astype(float) - pixel_depth / 2) / pixel_depth if image_data.shape", "a download. This is mostly intended for users with slow internet connections. Reports", "process data from', pickle_file, ':', e) raise return valid_dataset, valid_labels, train_dataset, train_labels #", "root) tar = tarfile.open(filename) sys.stdout.flush() tar.extractall() tar.close() data_folders = [ os.path.join(root, d) for", "tar.close() data_folders = [ os.path.join(root, d) for d in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, d))]", "'Failed to verify ' + filename + '. Can you get to it", "labels = np.ndarray(nb_rows, dtype=np.int32) else: dataset, labels = None, None return dataset, labels", "label start_v += vsize_per_class end_v += vsize_per_class train_letter = letter_set[vsize_per_class:end_l, :, :] train_dataset[start_t:end_t,", "filtered_dataset, filtered_labels, same_count, similar_count sanit_pickle_file = 'notMNIST_sanit.pickle' if not os.path.exists(sanit_pickle_file): filtered_valid_dataset, filtered_valid_labels, train_valid_same,", "'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': filtered_valid_dataset, 'valid_labels': filtered_valid_labels, 'test_dataset':", "plt import numpy as np import os import sys import tarfile from IPython.display", "load_letter(folder, min_num_images_per_class) try: with open(set_filename, 'wb') as f: pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL) except Exception", "(size,-1)) y = labels lr = LogisticRegression(n_jobs=4) lr.fit(X, y) return lr def model_score(model,", "/ pixel_depth if image_data.shape != (image_size, image_size): raise Exception('Unexpected image shape: %s' %", "further. # code changed to Python3 import matplotlib import matplotlib.pyplot as plt import", "0: sys.stdout.write(\"%s%%\" % percent) sys.stdout.flush() else: sys.stdout.write(\".\") sys.stdout.flush() last_percent_reported = percent def maybe_download(filename,", "filtered_labels, same_count, similar_count sanit_pickle_file = 'notMNIST_sanit.pickle' if not os.path.exists(sanit_pickle_file): filtered_valid_dataset, filtered_valid_labels, train_valid_same, train_valid_similar", "a random matrix with a specified figure number and a grayscale colormap #", "test_dataset, test_labels train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels = load_datasets(pickle_file) print('Training:', train_dataset.shape, train_labels.shape)", "# def show_images(dataset, labels, count): # for i in range(0,count): # print(labels[i]) #", "e: print('Could not read:', image_file, ':', e, '- it\\'s ok, skipping.') dataset =", "than expected: %d < %d' % (num_images, min_num_images)) print('Full dataset tensor:', dataset.shape) print('Mean:',", "train_valid_same, \"similar=\", train_valid_similar) filtered_test_dataset, filtered_test_labels, train_test_same, train_test_similar = \\ sanitize_dataset(test_dataset, test_labels, train_dataset, 0.001)", "= dataset[0:size] labels = labels[0:size] X = np.reshape(dataset, (size,-1)) y = labels lr", "vsize_per_class = valid_size // num_classes tsize_per_class = train_size // num_classes start_v, start_t =", "'.pickle' dataset_names.append(set_filename) if os.path.exists(set_filename) and not force: # You may override by setting", "# before proceeding further. # code changed to Python3 import matplotlib import matplotlib.pyplot", "is balanced between classes # for name in train_datasets: # dataset = load_dataset(name)", "= tarfile.open(filename) sys.stdout.flush() tar.extractall() tar.close() data_folders = [ os.path.join(root, d) for d in", "= train_labels[indices] try: f = open(pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels':", "valid_dataset is not None: valid_letter = letter_set[:vsize_per_class, :, :] valid_dataset[start_v:end_v, :, :] =", "labels = labels[0:size] X = np.reshape(dataset, (size,-1)) y = labels lr = LogisticRegression(n_jobs=4)", "= 28 # Pixel width and height. pixel_depth = 255.0 # Number of", "merge_datasets(pickle_files, train_size, valid_size=0): num_classes = len(pickle_files) valid_dataset, valid_labels = make_arrays(valid_size, image_size) train_dataset, train_labels", "# Pixel width and height. pixel_depth = 255.0 # Number of levels per", "str(image_data.shape)) dataset[num_images, :, :] = image_data num_images = num_images + 1 except IOError", "# print(labels[i]) # plt.matshow(dataset[i,:,:], cmap=plt.cm.gray) # plt.show() # show_images(train_dataset, train_labels, 3) # show_images(test_dataset,", "> 1-similarity_epsilon, axis=1) > 0 same_count = np.sum(same_filter) similar_count = np.sum(similar_filter) filtered_dataset =", "except IOError as e: print('Could not read:', image_file, ':', e, '- it\\'s ok,", "raise train_dataset, train_labels, filtered_valid_dataset, filtered_valid_labels, filtered_test_dataset, filtered_test_labels = load_datasets(sanit_pickle_file) print('Training (sanitized):', train_dataset.shape, train_labels.shape)", "247336696) test_filename = maybe_download('notMNIST_small.tar.gz', 8458043) num_classes = 10 np.random.seed(133) def maybe_extract(filename, force=False): root", "This is mostly intended for users with slow internet connections. Reports every 1%", "valid_letter valid_labels[start_v:end_v] = label start_v += vsize_per_class end_v += vsize_per_class train_letter = letter_set[vsize_per_class:end_l,", "sys.stdout.flush() last_percent_reported = percent def maybe_download(filename, expected_bytes, force=False): \"\"\"Download a file if not", "dataset def maybe_pickle(data_folders, min_num_images_per_class, force=False): dataset_names = [] for folder in data_folders: set_filename", "'train_labels': train_labels, 'valid_dataset': valid_dataset, 'valid_labels': valid_labels, 'test_dataset': test_dataset, 'test_labels': test_labels, } pickle.dump(save, f,", "train_labels = save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset = save['test_dataset'] test_labels", "image_size): raise Exception('Unexpected image shape: %s' % str(image_data.shape)) dataset[num_images, :, :] = image_data", "from urllib.request import urlretrieve import pickle import IPython # Config the matlotlib backend", "as np import os import sys import tarfile from IPython.display import display, Image", "Python3 import matplotlib import matplotlib.pyplot as plt import numpy as np import os", "!= num_classes: raise Exception( 'Expected %d folders, one per class. Found %d instead.'", "# plt.show() # show_images(train_dataset, train_labels, 3) # show_images(test_dataset, test_labels, 3) # show_images(valid_dataset, valid_labels,", "tarfile from IPython.display import display, Image from scipy import ndimage from sklearn.linear_model import", "valid_labels, test_dataset, test_labels train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels = load_datasets(pickle_file) print('Training:', train_dataset.shape,", "train_labels.shape) print('Validation:', valid_dataset.shape, valid_labels.shape) print('Testing:', test_dataset.shape, test_labels.shape) def sanitize_dataset(dataset, labels, filter_dataset, similarity_epsilon): similarity", "same=\", train_test_same, \"similar=\", train_test_similar) filtered_test_dataset, filtered_test_labels, valid_test_same, valid_test_similar = \\ sanitize_dataset(filtered_test_dataset, filtered_test_labels, filtered_valid_dataset,", "= np.ndarray(shape=(len(image_files), image_size, image_size), dtype=np.float32) print(folder) num_images = 0 for image in image_files:", "(ndimage.imread(image_file).astype(float) - pixel_depth / 2) / pixel_depth if image_data.shape != (image_size, image_size): raise", "num_images = num_images + 1 except IOError as e: print('Could not read:', image_file,", "train_labels # def show_images(dataset, labels, count): # for i in range(0,count): # print(labels[i])", "test_dataset, test_labels = merge_datasets(test_datasets, test_size) indices = np.arange(train_dataset.shape[0]) np.random.shuffle(indices) train_dataset = train_dataset[indices] train_labels", "save['test_dataset'] test_labels = save['test_labels'] return train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels train_dataset, train_labels,", "'valid_labels': filtered_valid_labels, 'test_dataset': filtered_test_dataset, 'test_labels': filtered_test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception", "open(pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': valid_dataset, 'valid_labels': valid_labels,", "% (root, filename)) else: print('Extracting data for %s. This may take a while.", "similar_count sanit_pickle_file = 'notMNIST_sanit.pickle' if not os.path.exists(sanit_pickle_file): filtered_valid_dataset, filtered_valid_labels, train_valid_same, train_valid_similar = \\", "labels[0:size] X = np.reshape(dataset, (size,-1)) y = labels lr = LogisticRegression(n_jobs=4) lr.fit(X, y)", "np.random.seed(133) def maybe_extract(filename, force=False): root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz if os.path.isdir(root) and", "def load_letter(folder, min_num_images): \"\"\"Load the data for a single letter label.\"\"\" image_files =", "This may take a while. Please wait.' % root) tar = tarfile.open(filename) sys.stdout.flush()", "8458043) num_classes = 10 np.random.seed(133) def maybe_extract(filename, force=False): root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove", "0, 0 end_v, end_t = vsize_per_class, tsize_per_class end_l = vsize_per_class + tsize_per_class for", "# Check whether the data is balanced between classes # for name in", "dtype=np.int32) else: dataset, labels = None, None return dataset, labels def merge_datasets(pickle_files, train_size,", "raise Exception('Many fewer images than expected: %d < %d' % (num_images, min_num_images)) print('Full", "with open(pickle_file, 'rb') as f: letter_set = pickle.load(f) # let's shuffle the letters", "= os.listdir(folder) dataset = np.ndarray(shape=(len(image_files), image_size, image_size), dtype=np.float32) print(folder) num_images = 0 for", "f.close() except Exception as e: print('Unable to save data to', pickle_file, ':', e)", "'test_labels': filtered_test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as e: print('Unable to", "def train(size=None): if size is None: print(\"Training with all examples:\") else: print(\"Training with", "with a specified figure number and a grayscale colormap # largeNameA = train_datasets[0]", "= 200000 valid_size = 10000 test_size = 10000 valid_dataset, valid_labels, train_dataset, train_labels =", "def maybe_download(filename, expected_bytes, force=False): \"\"\"Download a file if not present, and make sure", "(num_images, min_num_images)) print('Full dataset tensor:', dataset.shape) print('Mean:', np.mean(dataset)) print('Standard deviation:', np.std(dataset)) return dataset", "f, pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable to save data to', set_filename, ':',", "else: dataset = dataset[0:size] labels = labels[0:size] X = np.reshape(dataset, (size,-1)) y =", "import LogisticRegression from sklearn.metrics.pairwise import cosine_similarity from urllib.request import urlretrieve import pickle import", "num_classes = 10 np.random.seed(133) def maybe_extract(filename, force=False): root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz", "+ '. Can you get to it with a browser?') return filename train_filename", "data_folders: set_filename = folder + '.pickle' dataset_names.append(set_filename) if os.path.exists(set_filename) and not force: #", "train_labels[indices] try: f = open(pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels,", "labels, size=None): maxSize = dataset.shape[0] if size is None: size = maxSize elif", "10 np.random.seed(133) def maybe_extract(filename, force=False): root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz if os.path.isdir(root)", "if len(data_folders) != num_classes: raise Exception( 'Expected %d folders, one per class. Found", "dataset = dataset[0:size] labels = labels[0:size] X = np.reshape(dataset, (size,-1)) y = labels", "= train_dataset[indices] train_labels = train_labels[indices] try: f = open(pickle_file, 'wb') save = {", "the matlotlib backend as plotting inline in IPython # %matplotlib inline url =", "letters to have random validation and training set np.random.shuffle(letter_set) if valid_dataset is not", "data for %s. This may take a while. Please wait.' % root) tar", "may override by setting force=True. print('%s already present - Skipping pickling.' % set_filename)", "= load_dataset(largeNameA) # img1 = largeDataA[0, :, :] # plt.matshow(img1, cmap=plt.cm.gray) # plt.show()", "np.random.shuffle(letter_set) if valid_dataset is not None: valid_letter = letter_set[:vsize_per_class, :, :] valid_dataset[start_v:end_v, :,", "show_images(test_dataset, test_labels, 3) # show_images(valid_dataset, valid_labels, 3) pickle_file = 'notMNIST.pickle' if not os.path.exists(pickle_file):", "valid_labels, train_dataset, 0.001) print(\"training-validation: same=\", train_valid_same, \"similar=\", train_valid_similar) filtered_test_dataset, filtered_test_labels, train_test_same, train_test_similar =", "test_folders = maybe_extract(test_filename) #IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png') #IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png') image_size = 28 # Pixel width and height.", "# You may override by setting force=True. print('%s already present - Skipping extraction", "size:', statinfo.st_size) f = open(pickle_file, 'rb') save = pickle.load(f) f.close() train_dataset = save['train_dataset']", ":, :] if num_images < min_num_images: raise Exception('Many fewer images than expected: %d", "'notMNIST_sanit.pickle' if not os.path.exists(sanit_pickle_file): filtered_valid_dataset, filtered_valid_labels, train_valid_same, train_valid_similar = \\ sanitize_dataset(valid_dataset, valid_labels, train_dataset,", "Exception as e: print('Unable to save data to', set_filename, ':', e) return dataset_names", "of levels per pixel. def load_letter(folder, min_num_images): \"\"\"Load the data for a single", "dataset = load_dataset(name) # print(name, ' size:', dataset.shape) # # for name in", "print('Validation:', valid_dataset.shape, valid_labels.shape) print('Testing:', test_dataset.shape, test_labels.shape) def sanitize_dataset(dataset, labels, filter_dataset, similarity_epsilon): similarity =", "filtered_test_labels, train_test_same, train_test_similar = \\ sanitize_dataset(test_dataset, test_labels, train_dataset, 0.001) print(\"training-testing: same=\", train_test_same, \"similar=\",", "import sys import tarfile from IPython.display import display, Image from scipy import ndimage", "f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as e: print('Unable to save data to', pickle_file,", "= image_data num_images = num_images + 1 except IOError as e: print('Could not", "plt.show() # show_images(train_dataset, train_labels, 3) # show_images(test_dataset, test_labels, 3) # show_images(valid_dataset, valid_labels, 3)", "= labels[same_filter==False] return filtered_dataset, filtered_labels, same_count, similar_count sanit_pickle_file = 'notMNIST_sanit.pickle' if not os.path.exists(sanit_pickle_file):", "maxSize else: dataset = dataset[0:size] labels = labels[0:size] X = np.reshape(dataset, (size,-1)) y", "train_labels.shape) print('Validation (sanitized):', filtered_valid_dataset.shape, filtered_valid_labels.shape) print('Testing (sanitized):', filtered_test_dataset.shape, filtered_test_labels.shape) def train_model(dataset, labels, size=None):", "report the progress of a download. This is mostly intended for users with", "e) raise return valid_dataset, valid_labels, train_dataset, train_labels # def show_images(dataset, labels, count): #", "valid_labels, test_dataset, test_labels = load_datasets(pickle_file) print('Training:', train_dataset.shape, train_labels.shape) print('Validation:', valid_dataset.shape, valid_labels.shape) print('Testing:', test_dataset.shape,", "min_num_images_per_class, force=False): dataset_names = [] for folder in data_folders: set_filename = folder +", "present - Skipping pickling.' % set_filename) else: print('Pickling %s.' % set_filename) dataset =", "maybe_download(filename, expected_bytes, force=False): \"\"\"Download a file if not present, and make sure it's", "def make_arrays(nb_rows, img_size): if nb_rows: dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32) labels =", "img_size, img_size), dtype=np.float32) labels = np.ndarray(nb_rows, dtype=np.int32) else: dataset, labels = None, None", "train_dataset[start_t:end_t, :, :] = train_letter train_labels[start_t:end_t] = label start_t += tsize_per_class end_t +=", "sanit_pickle_file = 'notMNIST_sanit.pickle' if not os.path.exists(sanit_pickle_file): filtered_valid_dataset, filtered_valid_labels, train_valid_same, train_valid_similar = \\ sanitize_dataset(valid_dataset,", "label start_t += tsize_per_class end_t += tsize_per_class except Exception as e: print('Unable to", "test_dataset, 'test_labels': test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as e: print('Unable", "model_score(model, valid_dataset, valid_labels)) print(\" test score: \", model_score(model, test_dataset, test_labels)) print(\" validation score", "pickle_file in enumerate(pickle_files): try: with open(pickle_file, 'rb') as f: letter_set = pickle.load(f) #", "\"similar=\", train_test_similar) filtered_test_dataset, filtered_test_labels, valid_test_same, valid_test_similar = \\ sanitize_dataset(filtered_test_dataset, filtered_test_labels, filtered_valid_dataset, 0.001) print(\"validation-testing:", "pickle import IPython # Config the matlotlib backend as plotting inline in IPython", "setting force=True. print('%s already present - Skipping pickling.' % set_filename) else: print('Pickling %s.'", "import numpy as np import os import sys import tarfile from IPython.display import", "present, and make sure it's the right size.\"\"\" if force or not os.path.exists(filename):", "while. Please wait.' % root) tar = tarfile.open(filename) sys.stdout.flush() tar.extractall() tar.close() data_folders =", "similarity = cosine_similarity(np.reshape(dataset, (dataset.shape[0],-1)), np.reshape(filter_dataset, (filter_dataset.shape[0],-1))) same_filter = np.sum(similarity == 1, axis=1) >", "elif size > maxSize: size = maxSize else: dataset = dataset[0:size] labels =", "if image_data.shape != (image_size, image_size): raise Exception('Unexpected image shape: %s' % str(image_data.shape)) dataset[num_images,", "statinfo.st_size == expected_bytes: print('Found and verified', filename) else: raise Exception( 'Failed to verify", "random matrix with a specified figure number and a grayscale colormap # largeNameA", "end_t = vsize_per_class, tsize_per_class end_l = vsize_per_class + tsize_per_class for label, pickle_file in", "model_score(model, dataset, labels): X = np.reshape(dataset, (dataset.shape[0],-1)) y = labels return model.score(X, y)", "% str(image_data.shape)) dataset[num_images, :, :] = image_data num_images = num_images + 1 except", "= maybe_extract(test_filename) #IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png') #IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png') image_size = 28 # Pixel width and height. pixel_depth", "download. This is mostly intended for users with slow internet connections. Reports every", "save data to', set_filename, ':', e) return dataset_names train_datasets = maybe_pickle(train_folders, 45000) test_datasets", "print(data_folders) return data_folders train_folders = maybe_extract(train_filename) test_folders = maybe_extract(test_filename) #IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png') #IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png') image_size =", "= train_datasets[0] # print(largeNameA) # largeDataA = load_dataset(largeNameA) # img1 = largeDataA[0, :,", "# # smallNameJ = test_datasets[9] # print(smallNameJ) # smallDataJ = load_dataset(smallNameJ) # img2", "+= vsize_per_class end_v += vsize_per_class train_letter = letter_set[vsize_per_class:end_l, :, :] train_dataset[start_t:end_t, :, :]", "statinfo.st_size) f = open(pickle_file, 'rb') save = pickle.load(f) f.close() train_dataset = save['train_dataset'] train_labels", "These are all the modules we'll be using later. Make sure you can", "train_labels, valid_dataset, valid_labels, test_dataset, test_labels train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels = load_datasets(pickle_file)", "= load_dataset(name) # print(name, ' size:', dataset.shape) def make_arrays(nb_rows, img_size): if nb_rows: dataset", "maybe_pickle(data_folders, min_num_images_per_class, force=False): dataset_names = [] for folder in data_folders: set_filename = folder", "tar.extractall() tar.close() data_folders = [ os.path.join(root, d) for d in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root,", "len(pickle_files) valid_dataset, valid_labels = make_arrays(valid_size, image_size) train_dataset, train_labels = make_arrays(train_size, image_size) vsize_per_class =", "valid_labels[start_v:end_v] = label start_v += vsize_per_class end_v += vsize_per_class train_letter = letter_set[vsize_per_class:end_l, :,", "smallNameJ = test_datasets[9] # print(smallNameJ) # smallDataJ = load_dataset(smallNameJ) # img2 = smallDataJ[0,", "np.reshape(dataset, (size,-1)) y = labels lr = LogisticRegression(n_jobs=4) lr.fit(X, y) return lr def", "return model.score(X, y) def train(size=None): if size is None: print(\"Training with all examples:\")", "\"\"\" global last_percent_reported percent = int(count * blockSize * 100 / totalSize) if", "to save data to', pickle_file, ':', e) raise def load_datasets(pickle_file): statinfo = os.stat(pickle_file)", "image_file = os.path.join(folder, image) try: image_data = (ndimage.imread(image_file).astype(float) - pixel_depth / 2) /", "(sanitized):', filtered_test_dataset.shape, filtered_test_labels.shape) def train_model(dataset, labels, size=None): maxSize = dataset.shape[0] if size is", "largeNameA = train_datasets[0] # print(largeNameA) # largeDataA = load_dataset(largeNameA) # img1 = largeDataA[0,", "test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as e: print('Unable to save", "print(\"training-validation: same=\", train_valid_same, \"similar=\", train_valid_similar) filtered_test_dataset, filtered_test_labels, train_test_same, train_test_similar = \\ sanitize_dataset(test_dataset, test_labels,", "force=False): dataset_names = [] for folder in data_folders: set_filename = folder + '.pickle'", "= maybe_download('notMNIST_large.tar.gz', 247336696) test_filename = maybe_download('notMNIST_small.tar.gz', 8458043) num_classes = 10 np.random.seed(133) def maybe_extract(filename,", "= np.sum(same_filter) similar_count = np.sum(similar_filter) filtered_dataset = dataset[same_filter==False] filtered_labels = labels[same_filter==False] return filtered_dataset,", "in IPython # %matplotlib inline url = 'http://commondatastorage.googleapis.com/books1000/' last_percent_reported = None def download_progress_hook(count,", "image_size = 28 # Pixel width and height. pixel_depth = 255.0 # Number", "= os.path.join(folder, image) try: image_data = (ndimage.imread(image_file).astype(float) - pixel_depth / 2) / pixel_depth", "last_percent_reported percent = int(count * blockSize * 100 / totalSize) if last_percent_reported !=", "(image_size, image_size): raise Exception('Unexpected image shape: %s' % str(image_data.shape)) dataset[num_images, :, :] =", "override by setting force=True. print('%s already present - Skipping pickling.' % set_filename) else:", "e: print('Unable to process data from', pickle_file, ':', e) raise return valid_dataset, valid_labels,", "\\ sanitize_dataset(test_dataset, test_labels, train_dataset, 0.001) print(\"training-testing: same=\", train_test_same, \"similar=\", train_test_similar) filtered_test_dataset, filtered_test_labels, valid_test_same,", "a browser?') return filename train_filename = maybe_download('notMNIST_large.tar.gz', 247336696) test_filename = maybe_download('notMNIST_small.tar.gz', 8458043) num_classes", "data to', set_filename, ':', e) return dataset_names train_datasets = maybe_pickle(train_folders, 45000) test_datasets =", "IPython # %matplotlib inline url = 'http://commondatastorage.googleapis.com/books1000/' last_percent_reported = None def download_progress_hook(count, blockSize,", "sanitize_dataset(filtered_test_dataset, filtered_test_labels, filtered_valid_dataset, 0.001) print(\"validation-testing: same=\", valid_test_same, \"similar=\", valid_test_similar) try: f = open(sanit_pickle_file,", "= os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz if os.path.isdir(root) and not force: # You may", "if size is None: size = maxSize elif size > maxSize: size =", "as e: print('Unable to save data to', set_filename, ':', e) return dataset_names train_datasets", "print('\\nDownload Complete!') statinfo = os.stat(filename) if statinfo.st_size == expected_bytes: print('Found and verified', filename)", "test_datasets[9] # print(smallNameJ) # smallDataJ = load_dataset(smallNameJ) # img2 = smallDataJ[0, :, :]", "\"similar=\", train_valid_similar) filtered_test_dataset, filtered_test_labels, train_test_same, train_test_similar = \\ sanitize_dataset(test_dataset, test_labels, train_dataset, 0.001) print(\"training-testing:", "d in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, d))] if len(data_folders) != num_classes: raise Exception( 'Expected", "#IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png') #IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png') image_size = 28 # Pixel width and height. pixel_depth = 255.0", "= save['train_dataset'] train_labels = save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset =", "is None: print(\"Training with all examples:\") else: print(\"Training with \", size, \" examples:\")", "plt.show() # Check whether the data is balanced between classes # for name", "dataset = load_letter(folder, min_num_images_per_class) try: with open(set_filename, 'wb') as f: pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL)", "statinfo = os.stat(pickle_file) print('Compressed pickle size:', statinfo.st_size) f = open(pickle_file, 'rb') save =", "lr.fit(X, y) return lr def model_score(model, dataset, labels): X = np.reshape(dataset, (dataset.shape[0],-1)) y", "# print(largeNameA) # largeDataA = load_dataset(largeNameA) # img1 = largeDataA[0, :, :] #", "start_t += tsize_per_class end_t += tsize_per_class except Exception as e: print('Unable to process", "' size:', dataset.shape) # # for name in test_datasets: # dataset = load_dataset(name)", "// num_classes tsize_per_class = train_size // num_classes start_v, start_t = 0, 0 end_v,", "# img2 = smallDataJ[0, :, :] # plt.matshow(img2, cmap=plt.cm.gray) # plt.show() # Check", "print('Validation (sanitized):', filtered_valid_dataset.shape, filtered_valid_labels.shape) print('Testing (sanitized):', filtered_test_dataset.shape, filtered_test_labels.shape) def train_model(dataset, labels, size=None): maxSize", "(dataset.shape[0],-1)) y = labels return model.score(X, y) def train(size=None): if size is None:", "+ '.pickle' dataset_names.append(set_filename) if os.path.exists(set_filename) and not force: # You may override by", "= np.ndarray(nb_rows, dtype=np.int32) else: dataset, labels = None, None return dataset, labels def", "dataset = dataset[0:num_images, :, :] if num_images < min_num_images: raise Exception('Many fewer images", "train_dataset = save['train_dataset'] train_labels = save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset", "filtered_valid_dataset, filtered_valid_labels, train_valid_same, train_valid_similar = \\ sanitize_dataset(valid_dataset, valid_labels, train_dataset, 0.001) print(\"training-validation: same=\", train_valid_same,", "if percent % 5 == 0: sys.stdout.write(\"%s%%\" % percent) sys.stdout.flush() else: sys.stdout.write(\".\") sys.stdout.flush()", "valid_dataset, valid_labels, test_dataset, test_labels = load_datasets(pickle_file) print('Training:', train_dataset.shape, train_labels.shape) print('Validation:', valid_dataset.shape, valid_labels.shape) print('Testing:',", "# largeDataA = load_dataset(largeNameA) # img1 = largeDataA[0, :, :] # plt.matshow(img1, cmap=plt.cm.gray)", "filename)) else: print('Extracting data for %s. This may take a while. Please wait.'", "filename) filename, _ = urlretrieve(url + filename, filename, reporthook=download_progress_hook) print('\\nDownload Complete!') statinfo =", "None: print(\"Training with all examples:\") else: print(\"Training with \", size, \" examples:\") model", "filtered_test_labels, valid_test_same, valid_test_similar = \\ sanitize_dataset(filtered_test_dataset, filtered_test_labels, filtered_valid_dataset, 0.001) print(\"validation-testing: same=\", valid_test_same, \"similar=\",", "= load_dataset(name) # print(name, ' size:', dataset.shape) # # for name in test_datasets:", "3) # show_images(valid_dataset, valid_labels, 3) pickle_file = 'notMNIST.pickle' if not os.path.exists(pickle_file): train_size =", "- Skipping extraction of %s.' % (root, filename)) else: print('Extracting data for %s.", "progress of a download. This is mostly intended for users with slow internet", "'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': valid_dataset, 'valid_labels': valid_labels, 'test_dataset':", "2) / pixel_depth if image_data.shape != (image_size, image_size): raise Exception('Unexpected image shape: %s'", "min_num_images: raise Exception('Many fewer images than expected: %d < %d' % (num_images, min_num_images))", "int(count * blockSize * 100 / totalSize) if last_percent_reported != percent: if percent", "raise Exception('Unexpected image shape: %s' % str(image_data.shape)) dataset[num_images, :, :] = image_data num_images", "train_valid_similar = \\ sanitize_dataset(valid_dataset, valid_labels, train_dataset, 0.001) print(\"training-validation: same=\", train_valid_same, \"similar=\", train_valid_similar) filtered_test_dataset,", "urlretrieve import pickle import IPython # Config the matlotlib backend as plotting inline", "f.close() train_dataset = save['train_dataset'] train_labels = save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels']", "'rb') as f: letter_set = pickle.load(f) # let's shuffle the letters to have", "maybe_extract(filename, force=False): root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz if os.path.isdir(root) and not force:", "vsize_per_class train_letter = letter_set[vsize_per_class:end_l, :, :] train_dataset[start_t:end_t, :, :] = train_letter train_labels[start_t:end_t] =", "pickle_file = 'notMNIST.pickle' if not os.path.exists(pickle_file): train_size = 200000 valid_size = 10000 test_size", "image_data.shape != (image_size, image_size): raise Exception('Unexpected image shape: %s' % str(image_data.shape)) dataset[num_images, :,", "filtered_valid_dataset.shape, filtered_valid_labels.shape) print('Testing (sanitized):', filtered_test_dataset.shape, filtered_test_labels.shape) def train_model(dataset, labels, size=None): maxSize = dataset.shape[0]", "matlotlib backend as plotting inline in IPython # %matplotlib inline url = 'http://commondatastorage.googleapis.com/books1000/'", "= 10000 valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets( train_datasets, train_size, valid_size) _, _,", "= train_model(train_dataset, train_labels, size) print(\" validation score: \", model_score(model, valid_dataset, valid_labels)) print(\" test", "else: raise Exception( 'Failed to verify ' + filename + '. Can you", "for label, pickle_file in enumerate(pickle_files): try: with open(pickle_file, 'rb') as f: letter_set =", "change in download progress. \"\"\" global last_percent_reported percent = int(count * blockSize *", "print(name, ' size:', dataset.shape) # # for name in test_datasets: # dataset =", "(sanitized):', filtered_valid_dataset.shape, filtered_valid_labels.shape) print('Testing (sanitized):', filtered_test_dataset.shape, filtered_test_labels.shape) def train_model(dataset, labels, size=None): maxSize =", "examples:\") else: print(\"Training with \", size, \" examples:\") model = train_model(train_dataset, train_labels, size)", "# smallDataJ = load_dataset(smallNameJ) # img2 = smallDataJ[0, :, :] # plt.matshow(img2, cmap=plt.cm.gray)", "np.ndarray(shape=(len(image_files), image_size, image_size), dtype=np.float32) print(folder) num_images = 0 for image in image_files: image_file", "10000 valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets( train_datasets, train_size, valid_size) _, _, test_dataset,", "data for a single letter label.\"\"\" image_files = os.listdir(folder) dataset = np.ndarray(shape=(len(image_files), image_size,", "for users with slow internet connections. Reports every 1% change in download progress.", "= percent def maybe_download(filename, expected_bytes, force=False): \"\"\"Download a file if not present, and", "return filename train_filename = maybe_download('notMNIST_large.tar.gz', 247336696) test_filename = maybe_download('notMNIST_small.tar.gz', 8458043) num_classes = 10", "- pixel_depth / 2) / pixel_depth if image_data.shape != (image_size, image_size): raise Exception('Unexpected", "train_size, valid_size=0): num_classes = len(pickle_files) valid_dataset, valid_labels = make_arrays(valid_size, image_size) train_dataset, train_labels =", "may take a while. Please wait.' % root) tar = tarfile.open(filename) sys.stdout.flush() tar.extractall()", "= 0 for image in image_files: image_file = os.path.join(folder, image) try: image_data =", "!= percent: if percent % 5 == 0: sys.stdout.write(\"%s%%\" % percent) sys.stdout.flush() else:", "filename + '. Can you get to it with a browser?') return filename", "pixel. def load_letter(folder, min_num_images): \"\"\"Load the data for a single letter label.\"\"\" image_files", "label.\"\"\" image_files = os.listdir(folder) dataset = np.ndarray(shape=(len(image_files), image_size, image_size), dtype=np.float32) print(folder) num_images =", "num_images + 1 except IOError as e: print('Could not read:', image_file, ':', e,", "'wb') as f: pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable to save", "return pickle.load(f) # Display a random matrix with a specified figure number and", "filtered_test_dataset, 'test_labels': filtered_test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as e: print('Unable", "\" examples:\") model = train_model(train_dataset, train_labels, size) print(\" validation score: \", model_score(model, valid_dataset,", "maybe_pickle(test_folders, 1800) def load_dataset(filename): with open(filename, 'rb') as f: return pickle.load(f) # Display", "'notMNIST.pickle' if not os.path.exists(pickle_file): train_size = 200000 valid_size = 10000 test_size = 10000", "it's the right size.\"\"\" if force or not os.path.exists(filename): print('Attempting to download:', filename)", "make_arrays(nb_rows, img_size): if nb_rows: dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32) labels = np.ndarray(nb_rows,", "image in image_files: image_file = os.path.join(folder, image) try: image_data = (ndimage.imread(image_file).astype(float) - pixel_depth", "0.001) print(\"training-validation: same=\", train_valid_same, \"similar=\", train_valid_similar) filtered_test_dataset, filtered_test_labels, train_test_same, train_test_similar = \\ sanitize_dataset(test_dataset,", "as e: print('Unable to save data to', pickle_file, ':', e) raise train_dataset, train_labels,", "== 1, axis=1) > 0 similar_filter = np.sum(similarity > 1-similarity_epsilon, axis=1) > 0", "size) print(\" validation score: \", model_score(model, valid_dataset, valid_labels)) print(\" test score: \", model_score(model,", "labels def merge_datasets(pickle_files, train_size, valid_size=0): num_classes = len(pickle_files) valid_dataset, valid_labels = make_arrays(valid_size, image_size)", "= LogisticRegression(n_jobs=4) lr.fit(X, y) return lr def model_score(model, dataset, labels): X = np.reshape(dataset,", "f = open(pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': valid_dataset,", "e) return dataset_names train_datasets = maybe_pickle(train_folders, 45000) test_datasets = maybe_pickle(test_folders, 1800) def load_dataset(filename):", "valid_dataset[start_v:end_v, :, :] = valid_letter valid_labels[start_v:end_v] = label start_v += vsize_per_class end_v +=", "not os.path.exists(sanit_pickle_file): filtered_valid_dataset, filtered_valid_labels, train_valid_same, train_valid_similar = \\ sanitize_dataset(valid_dataset, valid_labels, train_dataset, 0.001) print(\"training-validation:", "override by setting force=True. print('%s already present - Skipping extraction of %s.' %", ":, :] train_dataset[start_t:end_t, :, :] = train_letter train_labels[start_t:end_t] = label start_t += tsize_per_class", "in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, d))] if len(data_folders) != num_classes: raise Exception( 'Expected %d", "folder in data_folders: set_filename = folder + '.pickle' dataset_names.append(set_filename) if os.path.exists(set_filename) and not", "filtered_valid_dataset, filtered_valid_labels)) print(\" test score (sanitized): \", model_score(model, filtered_test_dataset, filtered_test_labels)) for size in", "load_datasets(pickle_file): statinfo = os.stat(pickle_file) print('Compressed pickle size:', statinfo.st_size) f = open(pickle_file, 'rb') save", "dtype=np.float32) labels = np.ndarray(nb_rows, dtype=np.int32) else: dataset, labels = None, None return dataset,", "200000 valid_size = 10000 test_size = 10000 valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets(", "open(pickle_file, 'rb') save = pickle.load(f) f.close() train_dataset = save['train_dataset'] train_labels = save['train_labels'] valid_dataset", "> maxSize: size = maxSize else: dataset = dataset[0:size] labels = labels[0:size] X", "class. Found %d instead.' % ( num_classes, len(data_folders))) print(data_folders) return data_folders train_folders =", "> 0 similar_filter = np.sum(similarity > 1-similarity_epsilon, axis=1) > 0 same_count = np.sum(same_filter)", "start_v += vsize_per_class end_v += vsize_per_class train_letter = letter_set[vsize_per_class:end_l, :, :] train_dataset[start_t:end_t, :,", "test_labels = save['test_labels'] return train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels train_dataset, train_labels, valid_dataset,", "fewer images than expected: %d < %d' % (num_images, min_num_images)) print('Full dataset tensor:',", "load_dataset(name) # print(name, ' size:', dataset.shape) def make_arrays(nb_rows, img_size): if nb_rows: dataset =", "# smallNameJ = test_datasets[9] # print(smallNameJ) # smallDataJ = load_dataset(smallNameJ) # img2 =", "name in test_datasets: # dataset = load_dataset(name) # print(name, ' size:', dataset.shape) def", "= merge_datasets(test_datasets, test_size) indices = np.arange(train_dataset.shape[0]) np.random.shuffle(indices) train_dataset = train_dataset[indices] train_labels = train_labels[indices]", "train_test_similar = \\ sanitize_dataset(test_dataset, test_labels, train_dataset, 0.001) print(\"training-testing: same=\", train_test_same, \"similar=\", train_test_similar) filtered_test_dataset,", "later. Make sure you can import them # before proceeding further. # code", "to process data from', pickle_file, ':', e) raise return valid_dataset, valid_labels, train_dataset, train_labels", "score: \", model_score(model, valid_dataset, valid_labels)) print(\" test score: \", model_score(model, test_dataset, test_labels)) print(\"", "= None, None return dataset, labels def merge_datasets(pickle_files, train_size, valid_size=0): num_classes = len(pickle_files)", "end_v, end_t = vsize_per_class, tsize_per_class end_l = vsize_per_class + tsize_per_class for label, pickle_file", "'train_labels': train_labels, 'valid_dataset': filtered_valid_dataset, 'valid_labels': filtered_valid_labels, 'test_dataset': filtered_test_dataset, 'test_labels': filtered_test_labels, } pickle.dump(save, f,", "def merge_datasets(pickle_files, train_size, valid_size=0): num_classes = len(pickle_files) valid_dataset, valid_labels = make_arrays(valid_size, image_size) train_dataset,", "show_images(dataset, labels, count): # for i in range(0,count): # print(labels[i]) # plt.matshow(dataset[i,:,:], cmap=plt.cm.gray)", "save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset = save['test_dataset'] test_labels = save['test_labels'] return train_dataset, train_labels,", "expected_bytes: print('Found and verified', filename) else: raise Exception( 'Failed to verify ' +", "end_t += tsize_per_class except Exception as e: print('Unable to process data from', pickle_file,", "= label start_t += tsize_per_class end_t += tsize_per_class except Exception as e: print('Unable", "pickle_file, ':', e) raise def load_datasets(pickle_file): statinfo = os.stat(pickle_file) print('Compressed pickle size:', statinfo.st_size)", "def model_score(model, dataset, labels): X = np.reshape(dataset, (dataset.shape[0],-1)) y = labels return model.score(X,", "name in train_datasets: # dataset = load_dataset(name) # print(name, ' size:', dataset.shape) #", "if force or not os.path.exists(filename): print('Attempting to download:', filename) filename, _ = urlretrieve(url", "= os.stat(pickle_file) print('Compressed pickle size:', statinfo.st_size) f = open(pickle_file, 'rb') save = pickle.load(f)", "slow internet connections. Reports every 1% change in download progress. \"\"\" global last_percent_reported", "train_labels, 'valid_dataset': filtered_valid_dataset, 'valid_labels': filtered_valid_labels, 'test_dataset': filtered_test_dataset, 'test_labels': filtered_test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL)", "dataset[num_images, :, :] = image_data num_images = num_images + 1 except IOError as", "np.sum(similarity > 1-similarity_epsilon, axis=1) > 0 same_count = np.sum(same_filter) similar_count = np.sum(similar_filter) filtered_dataset", ":, :] # plt.matshow(img2, cmap=plt.cm.gray) # plt.show() # Check whether the data is", "train_model(dataset, labels, size=None): maxSize = dataset.shape[0] if size is None: size = maxSize", "labels return model.score(X, y) def train(size=None): if size is None: print(\"Training with all", "in enumerate(pickle_files): try: with open(pickle_file, 'rb') as f: letter_set = pickle.load(f) # let's", "# You may override by setting force=True. print('%s already present - Skipping pickling.'", "min_num_images)) print('Full dataset tensor:', dataset.shape) print('Mean:', np.mean(dataset)) print('Standard deviation:', np.std(dataset)) return dataset def", "valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset = save['test_dataset'] test_labels = save['test_labels'] return", "Exception as e: print('Unable to save data to', pickle_file, ':', e) raise train_dataset,", "print(\" test score: \", model_score(model, test_dataset, test_labels)) print(\" validation score (sanitized): \", model_score(model,", "in download progress. \"\"\" global last_percent_reported percent = int(count * blockSize * 100", "import matplotlib import matplotlib.pyplot as plt import numpy as np import os import", "pixel_depth = 255.0 # Number of levels per pixel. def load_letter(folder, min_num_images): \"\"\"Load", "print('Unable to process data from', pickle_file, ':', e) raise return valid_dataset, valid_labels, train_dataset,", "'test_dataset': filtered_test_dataset, 'test_labels': filtered_test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as e:", "size, \" examples:\") model = train_model(train_dataset, train_labels, size) print(\" validation score: \", model_score(model,", "print(folder) num_images = 0 for image in image_files: image_file = os.path.join(folder, image) try:", "\", model_score(model, valid_dataset, valid_labels)) print(\" test score: \", model_score(model, test_dataset, test_labels)) print(\" validation", "IOError as e: print('Could not read:', image_file, ':', e, '- it\\'s ok, skipping.')", "filtered_valid_dataset, 0.001) print(\"validation-testing: same=\", valid_test_same, \"similar=\", valid_test_similar) try: f = open(sanit_pickle_file, 'wb') save", "have random validation and training set np.random.shuffle(letter_set) if valid_dataset is not None: valid_letter", "return data_folders train_folders = maybe_extract(train_filename) test_folders = maybe_extract(test_filename) #IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png') #IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png') image_size = 28", "before proceeding further. # code changed to Python3 import matplotlib import matplotlib.pyplot as", "import display, Image from scipy import ndimage from sklearn.linear_model import LogisticRegression from sklearn.metrics.pairwise", "height. pixel_depth = 255.0 # Number of levels per pixel. def load_letter(folder, min_num_images):", "= train_size // num_classes start_v, start_t = 0, 0 end_v, end_t = vsize_per_class,", ":, :] valid_dataset[start_v:end_v, :, :] = valid_letter valid_labels[start_v:end_v] = label start_v += vsize_per_class", "test_datasets: # dataset = load_dataset(name) # print(name, ' size:', dataset.shape) def make_arrays(nb_rows, img_size):", "print('Compressed pickle size:', statinfo.st_size) f = open(pickle_file, 'rb') save = pickle.load(f) f.close() train_dataset", "\"\"\"Download a file if not present, and make sure it's the right size.\"\"\"", "it\\'s ok, skipping.') dataset = dataset[0:num_images, :, :] if num_images < min_num_images: raise", "not None: valid_letter = letter_set[:vsize_per_class, :, :] valid_dataset[start_v:end_v, :, :] = valid_letter valid_labels[start_v:end_v]", "None, None return dataset, labels def merge_datasets(pickle_files, train_size, valid_size=0): num_classes = len(pickle_files) valid_dataset,", "print('Unable to save data to', pickle_file, ':', e) raise train_dataset, train_labels, filtered_valid_dataset, filtered_valid_labels,", "dataset.shape) print('Mean:', np.mean(dataset)) print('Standard deviation:', np.std(dataset)) return dataset def maybe_pickle(data_folders, min_num_images_per_class, force=False): dataset_names", "download_progress_hook(count, blockSize, totalSize): \"\"\"A hook to report the progress of a download. This", "model = train_model(train_dataset, train_labels, size) print(\" validation score: \", model_score(model, valid_dataset, valid_labels)) print(\"", "# dataset = load_dataset(name) # print(name, ' size:', dataset.shape) # # for name", "e) raise def load_datasets(pickle_file): statinfo = os.stat(pickle_file) print('Compressed pickle size:', statinfo.st_size) f =", "print(labels[i]) # plt.matshow(dataset[i,:,:], cmap=plt.cm.gray) # plt.show() # show_images(train_dataset, train_labels, 3) # show_images(test_dataset, test_labels,", "train_filename = maybe_download('notMNIST_large.tar.gz', 247336696) test_filename = maybe_download('notMNIST_small.tar.gz', 8458043) num_classes = 10 np.random.seed(133) def", "vsize_per_class + tsize_per_class for label, pickle_file in enumerate(pickle_files): try: with open(pickle_file, 'rb') as", "for i in range(0,count): # print(labels[i]) # plt.matshow(dataset[i,:,:], cmap=plt.cm.gray) # plt.show() # show_images(train_dataset,", "train_dataset.shape, train_labels.shape) print('Validation (sanitized):', filtered_valid_dataset.shape, filtered_valid_labels.shape) print('Testing (sanitized):', filtered_test_dataset.shape, filtered_test_labels.shape) def train_model(dataset, labels,", "import tarfile from IPython.display import display, Image from scipy import ndimage from sklearn.linear_model", "print('Extracting data for %s. This may take a while. Please wait.' % root)", "Skipping pickling.' % set_filename) else: print('Pickling %s.' % set_filename) dataset = load_letter(folder, min_num_images_per_class)", "ok, skipping.') dataset = dataset[0:num_images, :, :] if num_images < min_num_images: raise Exception('Many", "# for name in train_datasets: # dataset = load_dataset(name) # print(name, ' size:',", "'rb') save = pickle.load(f) f.close() train_dataset = save['train_dataset'] train_labels = save['train_labels'] valid_dataset =", "= np.reshape(dataset, (dataset.shape[0],-1)) y = labels return model.score(X, y) def train(size=None): if size", "Image from scipy import ndimage from sklearn.linear_model import LogisticRegression from sklearn.metrics.pairwise import cosine_similarity", "45000) test_datasets = maybe_pickle(test_folders, 1800) def load_dataset(filename): with open(filename, 'rb') as f: return", "from', pickle_file, ':', e) raise return valid_dataset, valid_labels, train_dataset, train_labels # def show_images(dataset,", "Exception('Unexpected image shape: %s' % str(image_data.shape)) dataset[num_images, :, :] = image_data num_images =", "= vsize_per_class + tsize_per_class for label, pickle_file in enumerate(pickle_files): try: with open(pickle_file, 'rb')", "= valid_letter valid_labels[start_v:end_v] = label start_v += vsize_per_class end_v += vsize_per_class train_letter =", "= [] for folder in data_folders: set_filename = folder + '.pickle' dataset_names.append(set_filename) if", "num_classes tsize_per_class = train_size // num_classes start_v, start_t = 0, 0 end_v, end_t", "valid_labels, 'test_dataset': test_dataset, 'test_labels': test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as", "filename, _ = urlretrieve(url + filename, filename, reporthook=download_progress_hook) print('\\nDownload Complete!') statinfo = os.stat(filename)", "100 / totalSize) if last_percent_reported != percent: if percent % 5 == 0:", "dataset.shape[0] if size is None: size = maxSize elif size > maxSize: size", "colormap # largeNameA = train_datasets[0] # print(largeNameA) # largeDataA = load_dataset(largeNameA) # img1", "% percent) sys.stdout.flush() else: sys.stdout.write(\".\") sys.stdout.flush() last_percent_reported = percent def maybe_download(filename, expected_bytes, force=False):", "return dataset def maybe_pickle(data_folders, min_num_images_per_class, force=False): dataset_names = [] for folder in data_folders:", "letter_set = pickle.load(f) # let's shuffle the letters to have random validation and", "load_dataset(largeNameA) # img1 = largeDataA[0, :, :] # plt.matshow(img1, cmap=plt.cm.gray) # plt.show() #", "images than expected: %d < %d' % (num_images, min_num_images)) print('Full dataset tensor:', dataset.shape)", "to have random validation and training set np.random.shuffle(letter_set) if valid_dataset is not None:", "% ( num_classes, len(data_folders))) print(data_folders) return data_folders train_folders = maybe_extract(train_filename) test_folders = maybe_extract(test_filename)", "the data for a single letter label.\"\"\" image_files = os.listdir(folder) dataset = np.ndarray(shape=(len(image_files),", "'rb') as f: return pickle.load(f) # Display a random matrix with a specified", "the progress of a download. This is mostly intended for users with slow", "sys.stdout.write(\"%s%%\" % percent) sys.stdout.flush() else: sys.stdout.write(\".\") sys.stdout.flush() last_percent_reported = percent def maybe_download(filename, expected_bytes,", "Exception( 'Failed to verify ' + filename + '. Can you get to", "in data_folders: set_filename = folder + '.pickle' dataset_names.append(set_filename) if os.path.exists(set_filename) and not force:", "Reports every 1% change in download progress. \"\"\" global last_percent_reported percent = int(count", "data to', pickle_file, ':', e) raise train_dataset, train_labels, filtered_valid_dataset, filtered_valid_labels, filtered_test_dataset, filtered_test_labels =", "= maybe_pickle(train_folders, 45000) test_datasets = maybe_pickle(test_folders, 1800) def load_dataset(filename): with open(filename, 'rb') as", "from scipy import ndimage from sklearn.linear_model import LogisticRegression from sklearn.metrics.pairwise import cosine_similarity from", "0 same_count = np.sum(same_filter) similar_count = np.sum(similar_filter) filtered_dataset = dataset[same_filter==False] filtered_labels = labels[same_filter==False]", "examples:\") model = train_model(train_dataset, train_labels, size) print(\" validation score: \", model_score(model, valid_dataset, valid_labels))", "image_data = (ndimage.imread(image_file).astype(float) - pixel_depth / 2) / pixel_depth if image_data.shape != (image_size,", "num_classes, len(data_folders))) print(data_folders) return data_folders train_folders = maybe_extract(train_filename) test_folders = maybe_extract(test_filename) #IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png') #IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png')", "label, pickle_file in enumerate(pickle_files): try: with open(pickle_file, 'rb') as f: letter_set = pickle.load(f)", "image shape: %s' % str(image_data.shape)) dataset[num_images, :, :] = image_data num_images = num_images", "%s.' % set_filename) dataset = load_letter(folder, min_num_images_per_class) try: with open(set_filename, 'wb') as f:", "shuffle the letters to have random validation and training set np.random.shuffle(letter_set) if valid_dataset", "f = open(sanit_pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': filtered_valid_dataset,", "/ totalSize) if last_percent_reported != percent: if percent % 5 == 0: sys.stdout.write(\"%s%%\"", "= smallDataJ[0, :, :] # plt.matshow(img2, cmap=plt.cm.gray) # plt.show() # Check whether the", "filtered_test_labels)) for size in [50, 100, 1000, 5000]: train(size) # training on all", "train_datasets = maybe_pickle(train_folders, 45000) test_datasets = maybe_pickle(test_folders, 1800) def load_dataset(filename): with open(filename, 'rb')", "width and height. pixel_depth = 255.0 # Number of levels per pixel. def", "maybe_extract(test_filename) #IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png') #IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png') image_size = 28 # Pixel width and height. pixel_depth =", "to report the progress of a download. This is mostly intended for users", "%d' % (num_images, min_num_images)) print('Full dataset tensor:', dataset.shape) print('Mean:', np.mean(dataset)) print('Standard deviation:', np.std(dataset))", "and a grayscale colormap # largeNameA = train_datasets[0] # print(largeNameA) # largeDataA =", "changed to Python3 import matplotlib import matplotlib.pyplot as plt import numpy as np", "Please wait.' % root) tar = tarfile.open(filename) sys.stdout.flush() tar.extractall() tar.close() data_folders = [", "# dataset = load_dataset(name) # print(name, ' size:', dataset.shape) def make_arrays(nb_rows, img_size): if", "print(name, ' size:', dataset.shape) def make_arrays(nb_rows, img_size): if nb_rows: dataset = np.ndarray((nb_rows, img_size,", "1, axis=1) > 0 similar_filter = np.sum(similarity > 1-similarity_epsilon, axis=1) > 0 same_count", "train_dataset, 0.001) print(\"training-validation: same=\", train_valid_same, \"similar=\", train_valid_similar) filtered_test_dataset, filtered_test_labels, train_test_same, train_test_similar = \\", "model_score(model, filtered_valid_dataset, filtered_valid_labels)) print(\" test score (sanitized): \", model_score(model, filtered_test_dataset, filtered_test_labels)) for size", "- Skipping pickling.' % set_filename) else: print('Pickling %s.' % set_filename) dataset = load_letter(folder,", "':', e, '- it\\'s ok, skipping.') dataset = dataset[0:num_images, :, :] if num_images", "open(set_filename, 'wb') as f: pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable to", "last_percent_reported = percent def maybe_download(filename, expected_bytes, force=False): \"\"\"Download a file if not present,", "def load_datasets(pickle_file): statinfo = os.stat(pickle_file) print('Compressed pickle size:', statinfo.st_size) f = open(pickle_file, 'rb')", "0.001) print(\"validation-testing: same=\", valid_test_same, \"similar=\", valid_test_similar) try: f = open(sanit_pickle_file, 'wb') save =", "np.random.shuffle(indices) train_dataset = train_dataset[indices] train_labels = train_labels[indices] try: f = open(pickle_file, 'wb') save", "You may override by setting force=True. print('%s already present - Skipping extraction of", "os.path.exists(pickle_file): train_size = 200000 valid_size = 10000 test_size = 10000 valid_dataset, valid_labels, train_dataset,", "to verify ' + filename + '. Can you get to it with", "dataset_names train_datasets = maybe_pickle(train_folders, 45000) test_datasets = maybe_pickle(test_folders, 1800) def load_dataset(filename): with open(filename,", "to it with a browser?') return filename train_filename = maybe_download('notMNIST_large.tar.gz', 247336696) test_filename =", "# Number of levels per pixel. def load_letter(folder, min_num_images): \"\"\"Load the data for", "merge_datasets( train_datasets, train_size, valid_size) _, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size) indices =", "test_dataset, test_labels = load_datasets(pickle_file) print('Training:', train_dataset.shape, train_labels.shape) print('Validation:', valid_dataset.shape, valid_labels.shape) print('Testing:', test_dataset.shape, test_labels.shape)", "expected_bytes, force=False): \"\"\"Download a file if not present, and make sure it's the", "maxSize = dataset.shape[0] if size is None: size = maxSize elif size >", "test_labels.shape) def sanitize_dataset(dataset, labels, filter_dataset, similarity_epsilon): similarity = cosine_similarity(np.reshape(dataset, (dataset.shape[0],-1)), np.reshape(filter_dataset, (filter_dataset.shape[0],-1))) same_filter", "set_filename, ':', e) return dataset_names train_datasets = maybe_pickle(train_folders, 45000) test_datasets = maybe_pickle(test_folders, 1800)", "for d in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, d))] if len(data_folders) != num_classes: raise Exception(", "image_data num_images = num_images + 1 except IOError as e: print('Could not read:',", "train_model(train_dataset, train_labels, size) print(\" validation score: \", model_score(model, valid_dataset, valid_labels)) print(\" test score:", "test score: \", model_score(model, test_dataset, test_labels)) print(\" validation score (sanitized): \", model_score(model, filtered_valid_dataset,", "pickle.load(f) f.close() train_dataset = save['train_dataset'] train_labels = save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels =", "train_dataset, 'train_labels': train_labels, 'valid_dataset': filtered_valid_dataset, 'valid_labels': filtered_valid_labels, 'test_dataset': filtered_test_dataset, 'test_labels': filtered_test_labels, } pickle.dump(save,", "0 end_v, end_t = vsize_per_class, tsize_per_class end_l = vsize_per_class + tsize_per_class for label,", "filtered_valid_labels, train_valid_same, train_valid_similar = \\ sanitize_dataset(valid_dataset, valid_labels, train_dataset, 0.001) print(\"training-validation: same=\", train_valid_same, \"similar=\",", "image_size) vsize_per_class = valid_size // num_classes tsize_per_class = train_size // num_classes start_v, start_t", "size=None): maxSize = dataset.shape[0] if size is None: size = maxSize elif size", "len(data_folders) != num_classes: raise Exception( 'Expected %d folders, one per class. Found %d", "valid_test_same, \"similar=\", valid_test_similar) try: f = open(sanit_pickle_file, 'wb') save = { 'train_dataset': train_dataset,", "min_num_images_per_class) try: with open(set_filename, 'wb') as f: pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL) except Exception as", "vsize_per_class end_v += vsize_per_class train_letter = letter_set[vsize_per_class:end_l, :, :] train_dataset[start_t:end_t, :, :] =", "blockSize, totalSize): \"\"\"A hook to report the progress of a download. This is", "tsize_per_class except Exception as e: print('Unable to process data from', pickle_file, ':', e)", "if not present, and make sure it's the right size.\"\"\" if force or", "(root, filename)) else: print('Extracting data for %s. This may take a while. Please", "verify ' + filename + '. Can you get to it with a", "skipping.') dataset = dataset[0:num_images, :, :] if num_images < min_num_images: raise Exception('Many fewer", "to save data to', set_filename, ':', e) return dataset_names train_datasets = maybe_pickle(train_folders, 45000)", "filtered_valid_labels, 'test_dataset': filtered_test_dataset, 'test_labels': filtered_test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as", "dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32) labels = np.ndarray(nb_rows, dtype=np.int32) else: dataset, labels", "force=False): root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz if os.path.isdir(root) and not force: #", "# plt.matshow(img1, cmap=plt.cm.gray) # plt.show() # # smallNameJ = test_datasets[9] # print(smallNameJ) #", "= load_dataset(smallNameJ) # img2 = smallDataJ[0, :, :] # plt.matshow(img2, cmap=plt.cm.gray) # plt.show()", "connections. Reports every 1% change in download progress. \"\"\" global last_percent_reported percent =", "for name in train_datasets: # dataset = load_dataset(name) # print(name, ' size:', dataset.shape)", "' + filename + '. Can you get to it with a browser?')", "= make_arrays(valid_size, image_size) train_dataset, train_labels = make_arrays(train_size, image_size) vsize_per_class = valid_size // num_classes", "sys.stdout.flush() tar.extractall() tar.close() data_folders = [ os.path.join(root, d) for d in sorted(os.listdir(root)) if", "letter label.\"\"\" image_files = os.listdir(folder) dataset = np.ndarray(shape=(len(image_files), image_size, image_size), dtype=np.float32) print(folder) num_images", "display, Image from scipy import ndimage from sklearn.linear_model import LogisticRegression from sklearn.metrics.pairwise import", "not read:', image_file, ':', e, '- it\\'s ok, skipping.') dataset = dataset[0:num_images, :,", "dataset = load_dataset(name) # print(name, ' size:', dataset.shape) def make_arrays(nb_rows, img_size): if nb_rows:", "_, test_dataset, test_labels = merge_datasets(test_datasets, test_size) indices = np.arange(train_dataset.shape[0]) np.random.shuffle(indices) train_dataset = train_dataset[indices]", "train_datasets: # dataset = load_dataset(name) # print(name, ' size:', dataset.shape) # # for", "filtered_test_dataset.shape, filtered_test_labels.shape) def train_model(dataset, labels, size=None): maxSize = dataset.shape[0] if size is None:", "similar_filter = np.sum(similarity > 1-similarity_epsilon, axis=1) > 0 same_count = np.sum(same_filter) similar_count =", "load_datasets(sanit_pickle_file) print('Training (sanitized):', train_dataset.shape, train_labels.shape) print('Validation (sanitized):', filtered_valid_dataset.shape, filtered_valid_labels.shape) print('Testing (sanitized):', filtered_test_dataset.shape, filtered_test_labels.shape)", "= np.arange(train_dataset.shape[0]) np.random.shuffle(indices) train_dataset = train_dataset[indices] train_labels = train_labels[indices] try: f = open(pickle_file,", "is not None: valid_letter = letter_set[:vsize_per_class, :, :] valid_dataset[start_v:end_v, :, :] = valid_letter", "= 255.0 # Number of levels per pixel. def load_letter(folder, min_num_images): \"\"\"Load the", "filtered_test_labels = load_datasets(sanit_pickle_file) print('Training (sanitized):', train_dataset.shape, train_labels.shape) print('Validation (sanitized):', filtered_valid_dataset.shape, filtered_valid_labels.shape) print('Testing (sanitized):',", "1800) def load_dataset(filename): with open(filename, 'rb') as f: return pickle.load(f) # Display a", "start_v, start_t = 0, 0 end_v, end_t = vsize_per_class, tsize_per_class end_l = vsize_per_class", "10000 test_size = 10000 valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets( train_datasets, train_size, valid_size)", "valid_dataset, valid_labels, train_dataset, train_labels # def show_images(dataset, labels, count): # for i in", "(filter_dataset.shape[0],-1))) same_filter = np.sum(similarity == 1, axis=1) > 0 similar_filter = np.sum(similarity >", "# plt.show() # Check whether the data is balanced between classes # for", "the right size.\"\"\" if force or not os.path.exists(filename): print('Attempting to download:', filename) filename,", "print('%s already present - Skipping extraction of %s.' % (root, filename)) else: print('Extracting", "LogisticRegression from sklearn.metrics.pairwise import cosine_similarity from urllib.request import urlretrieve import pickle import IPython", "for name in test_datasets: # dataset = load_dataset(name) # print(name, ' size:', dataset.shape)", "':', e) raise return valid_dataset, valid_labels, train_dataset, train_labels # def show_images(dataset, labels, count):", "'http://commondatastorage.googleapis.com/books1000/' last_percent_reported = None def download_progress_hook(count, blockSize, totalSize): \"\"\"A hook to report the", "= save['test_dataset'] test_labels = save['test_labels'] return train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels train_dataset,", "same_count = np.sum(same_filter) similar_count = np.sum(similar_filter) filtered_dataset = dataset[same_filter==False] filtered_labels = labels[same_filter==False] return", "filtered_test_dataset, filtered_test_labels, valid_test_same, valid_test_similar = \\ sanitize_dataset(filtered_test_dataset, filtered_test_labels, filtered_valid_dataset, 0.001) print(\"validation-testing: same=\", valid_test_same,", "= load_datasets(sanit_pickle_file) print('Training (sanitized):', train_dataset.shape, train_labels.shape) print('Validation (sanitized):', filtered_valid_dataset.shape, filtered_valid_labels.shape) print('Testing (sanitized):', filtered_test_dataset.shape,", "dataset[0:size] labels = labels[0:size] X = np.reshape(dataset, (size,-1)) y = labels lr =", "f: pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable to save data to',", "= int(count * blockSize * 100 / totalSize) if last_percent_reported != percent: if", "def maybe_extract(filename, force=False): root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz if os.path.isdir(root) and not", "else: sys.stdout.write(\".\") sys.stdout.flush() last_percent_reported = percent def maybe_download(filename, expected_bytes, force=False): \"\"\"Download a file", "single letter label.\"\"\" image_files = os.listdir(folder) dataset = np.ndarray(shape=(len(image_files), image_size, image_size), dtype=np.float32) print(folder)", "a grayscale colormap # largeNameA = train_datasets[0] # print(largeNameA) # largeDataA = load_dataset(largeNameA)", "np.reshape(dataset, (dataset.shape[0],-1)) y = labels return model.score(X, y) def train(size=None): if size is", "filtered_labels = labels[same_filter==False] return filtered_dataset, filtered_labels, same_count, similar_count sanit_pickle_file = 'notMNIST_sanit.pickle' if not", "as e: print('Could not read:', image_file, ':', e, '- it\\'s ok, skipping.') dataset", "print('%s already present - Skipping pickling.' % set_filename) else: print('Pickling %s.' % set_filename)", "f: return pickle.load(f) # Display a random matrix with a specified figure number", "# print(name, ' size:', dataset.shape) # # for name in test_datasets: # dataset", "raise return valid_dataset, valid_labels, train_dataset, train_labels # def show_images(dataset, labels, count): # for", "same=\", train_valid_same, \"similar=\", train_valid_similar) filtered_test_dataset, filtered_test_labels, train_test_same, train_test_similar = \\ sanitize_dataset(test_dataset, test_labels, train_dataset,", "Check whether the data is balanced between classes # for name in train_datasets:", "# plt.matshow(dataset[i,:,:], cmap=plt.cm.gray) # plt.show() # show_images(train_dataset, train_labels, 3) # show_images(test_dataset, test_labels, 3)", "= save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset = save['test_dataset'] test_labels = save['test_labels'] return train_dataset,", "totalSize) if last_percent_reported != percent: if percent % 5 == 0: sys.stdout.write(\"%s%%\" %", "# # for name in test_datasets: # dataset = load_dataset(name) # print(name, '", "to', pickle_file, ':', e) raise train_dataset, train_labels, filtered_valid_dataset, filtered_valid_labels, filtered_test_dataset, filtered_test_labels = load_datasets(sanit_pickle_file)", "%d < %d' % (num_images, min_num_images)) print('Full dataset tensor:', dataset.shape) print('Mean:', np.mean(dataset)) print('Standard", "same_filter = np.sum(similarity == 1, axis=1) > 0 similar_filter = np.sum(similarity > 1-similarity_epsilon,", "pickle.load(f) # let's shuffle the letters to have random validation and training set", "Make sure you can import them # before proceeding further. # code changed", "sanitize_dataset(test_dataset, test_labels, train_dataset, 0.001) print(\"training-testing: same=\", train_test_same, \"similar=\", train_test_similar) filtered_test_dataset, filtered_test_labels, valid_test_same, valid_test_similar", "same_count, similar_count sanit_pickle_file = 'notMNIST_sanit.pickle' if not os.path.exists(sanit_pickle_file): filtered_valid_dataset, filtered_valid_labels, train_valid_same, train_valid_similar =", "size:', dataset.shape) # # for name in test_datasets: # dataset = load_dataset(name) #", "filtered_test_labels.shape) def train_model(dataset, labels, size=None): maxSize = dataset.shape[0] if size is None: size", "download progress. \"\"\" global last_percent_reported percent = int(count * blockSize * 100 /", "make_arrays(train_size, image_size) vsize_per_class = valid_size // num_classes tsize_per_class = train_size // num_classes start_v,", "os.stat(pickle_file) print('Compressed pickle size:', statinfo.st_size) f = open(pickle_file, 'rb') save = pickle.load(f) f.close()", "1-similarity_epsilon, axis=1) > 0 same_count = np.sum(same_filter) similar_count = np.sum(similar_filter) filtered_dataset = dataset[same_filter==False]", "test_filename = maybe_download('notMNIST_small.tar.gz', 8458043) num_classes = 10 np.random.seed(133) def maybe_extract(filename, force=False): root =", "= maxSize elif size > maxSize: size = maxSize else: dataset = dataset[0:size]", "+= vsize_per_class train_letter = letter_set[vsize_per_class:end_l, :, :] train_dataset[start_t:end_t, :, :] = train_letter train_labels[start_t:end_t]", "all the modules we'll be using later. Make sure you can import them", "a file if not present, and make sure it's the right size.\"\"\" if", "maybe_download('notMNIST_small.tar.gz', 8458043) num_classes = 10 np.random.seed(133) def maybe_extract(filename, force=False): root = os.path.splitext(os.path.splitext(filename)[0])[0] #", "if os.path.isdir(root) and not force: # You may override by setting force=True. print('%s", "scipy import ndimage from sklearn.linear_model import LogisticRegression from sklearn.metrics.pairwise import cosine_similarity from urllib.request", "return filtered_dataset, filtered_labels, same_count, similar_count sanit_pickle_file = 'notMNIST_sanit.pickle' if not os.path.exists(sanit_pickle_file): filtered_valid_dataset, filtered_valid_labels,", "filtered_test_dataset, filtered_test_labels)) for size in [50, 100, 1000, 5000]: train(size) # training on", "':', e) return dataset_names train_datasets = maybe_pickle(train_folders, 45000) test_datasets = maybe_pickle(test_folders, 1800) def", "with a browser?') return filename train_filename = maybe_download('notMNIST_large.tar.gz', 247336696) test_filename = maybe_download('notMNIST_small.tar.gz', 8458043)", "num_images < min_num_images: raise Exception('Many fewer images than expected: %d < %d' %", "os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz if os.path.isdir(root) and not force: # You may override", "indices = np.arange(train_dataset.shape[0]) np.random.shuffle(indices) train_dataset = train_dataset[indices] train_labels = train_labels[indices] try: f =", "= np.sum(similarity == 1, axis=1) > 0 similar_filter = np.sum(similarity > 1-similarity_epsilon, axis=1)", "model_score(model, test_dataset, test_labels)) print(\" validation score (sanitized): \", model_score(model, filtered_valid_dataset, filtered_valid_labels)) print(\" test", "sys import tarfile from IPython.display import display, Image from scipy import ndimage from", "we'll be using later. Make sure you can import them # before proceeding", "= os.stat(filename) if statinfo.st_size == expected_bytes: print('Found and verified', filename) else: raise Exception(", "filtered_test_dataset, filtered_test_labels = load_datasets(sanit_pickle_file) print('Training (sanitized):', train_dataset.shape, train_labels.shape) print('Validation (sanitized):', filtered_valid_dataset.shape, filtered_valid_labels.shape) print('Testing", "valid_labels.shape) print('Testing:', test_dataset.shape, test_labels.shape) def sanitize_dataset(dataset, labels, filter_dataset, similarity_epsilon): similarity = cosine_similarity(np.reshape(dataset, (dataset.shape[0],-1)),", "os.listdir(folder) dataset = np.ndarray(shape=(len(image_files), image_size, image_size), dtype=np.float32) print(folder) num_images = 0 for image", "as f: letter_set = pickle.load(f) # let's shuffle the letters to have random", "load_dataset(filename): with open(filename, 'rb') as f: return pickle.load(f) # Display a random matrix", "print('Training:', train_dataset.shape, train_labels.shape) print('Validation:', valid_dataset.shape, valid_labels.shape) print('Testing:', test_dataset.shape, test_labels.shape) def sanitize_dataset(dataset, labels, filter_dataset,", "pixel_depth if image_data.shape != (image_size, image_size): raise Exception('Unexpected image shape: %s' % str(image_data.shape))", "image_size) train_dataset, train_labels = make_arrays(train_size, image_size) vsize_per_class = valid_size // num_classes tsize_per_class =", "force: # You may override by setting force=True. print('%s already present - Skipping", "load_dataset(name) # print(name, ' size:', dataset.shape) # # for name in test_datasets: #", "set np.random.shuffle(letter_set) if valid_dataset is not None: valid_letter = letter_set[:vsize_per_class, :, :] valid_dataset[start_v:end_v,", "def show_images(dataset, labels, count): # for i in range(0,count): # print(labels[i]) # plt.matshow(dataset[i,:,:],", "to download:', filename) filename, _ = urlretrieve(url + filename, filename, reporthook=download_progress_hook) print('\\nDownload Complete!')", "set_filename) else: print('Pickling %s.' % set_filename) dataset = load_letter(folder, min_num_images_per_class) try: with open(set_filename,", "train_size // num_classes start_v, start_t = 0, 0 end_v, end_t = vsize_per_class, tsize_per_class", "test_size = 10000 valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets( train_datasets, train_size, valid_size) _,", "already present - Skipping pickling.' % set_filename) else: print('Pickling %s.' % set_filename) dataset", ":] valid_dataset[start_v:end_v, :, :] = valid_letter valid_labels[start_v:end_v] = label start_v += vsize_per_class end_v", "filter_dataset, similarity_epsilon): similarity = cosine_similarity(np.reshape(dataset, (dataset.shape[0],-1)), np.reshape(filter_dataset, (filter_dataset.shape[0],-1))) same_filter = np.sum(similarity == 1,", "d) for d in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, d))] if len(data_folders) != num_classes: raise", "train_dataset, 0.001) print(\"training-testing: same=\", train_test_same, \"similar=\", train_test_similar) filtered_test_dataset, filtered_test_labels, valid_test_same, valid_test_similar = \\", "print('Standard deviation:', np.std(dataset)) return dataset def maybe_pickle(data_folders, min_num_images_per_class, force=False): dataset_names = [] for", "if last_percent_reported != percent: if percent % 5 == 0: sys.stdout.write(\"%s%%\" % percent)", "= urlretrieve(url + filename, filename, reporthook=download_progress_hook) print('\\nDownload Complete!') statinfo = os.stat(filename) if statinfo.st_size", "print(\" validation score (sanitized): \", model_score(model, filtered_valid_dataset, filtered_valid_labels)) print(\" test score (sanitized): \",", "save data to', pickle_file, ':', e) raise train_dataset, train_labels, filtered_valid_dataset, filtered_valid_labels, filtered_test_dataset, filtered_test_labels", "tarfile.open(filename) sys.stdout.flush() tar.extractall() tar.close() data_folders = [ os.path.join(root, d) for d in sorted(os.listdir(root))", "percent) sys.stdout.flush() else: sys.stdout.write(\".\") sys.stdout.flush() last_percent_reported = percent def maybe_download(filename, expected_bytes, force=False): \"\"\"Download", "255.0 # Number of levels per pixel. def load_letter(folder, min_num_images): \"\"\"Load the data", "None def download_progress_hook(count, blockSize, totalSize): \"\"\"A hook to report the progress of a", "train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels =", "right size.\"\"\" if force or not os.path.exists(filename): print('Attempting to download:', filename) filename, _", "sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, d))] if len(data_folders) != num_classes: raise Exception( 'Expected %d folders,", "train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels = load_datasets(pickle_file) print('Training:', train_dataset.shape, train_labels.shape) print('Validation:', valid_dataset.shape,", "0 similar_filter = np.sum(similarity > 1-similarity_epsilon, axis=1) > 0 same_count = np.sum(same_filter) similar_count", "sure it's the right size.\"\"\" if force or not os.path.exists(filename): print('Attempting to download:',", "Display a random matrix with a specified figure number and a grayscale colormap", "f: letter_set = pickle.load(f) # let's shuffle the letters to have random validation", "figure number and a grayscale colormap # largeNameA = train_datasets[0] # print(largeNameA) #", "global last_percent_reported percent = int(count * blockSize * 100 / totalSize) if last_percent_reported", "in test_datasets: # dataset = load_dataset(name) # print(name, ' size:', dataset.shape) def make_arrays(nb_rows,", "setting force=True. print('%s already present - Skipping extraction of %s.' % (root, filename))", "IPython # Config the matlotlib backend as plotting inline in IPython # %matplotlib", "it with a browser?') return filename train_filename = maybe_download('notMNIST_large.tar.gz', 247336696) test_filename = maybe_download('notMNIST_small.tar.gz',", "save['valid_labels'] test_dataset = save['test_dataset'] test_labels = save['test_labels'] return train_dataset, train_labels, valid_dataset, valid_labels, test_dataset,", "data_folders train_folders = maybe_extract(train_filename) test_folders = maybe_extract(test_filename) #IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png') #IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png') image_size = 28 #", "from IPython.display import display, Image from scipy import ndimage from sklearn.linear_model import LogisticRegression", "set_filename) dataset = load_letter(folder, min_num_images_per_class) try: with open(set_filename, 'wb') as f: pickle.dump(dataset, f,", "if not os.path.exists(sanit_pickle_file): filtered_valid_dataset, filtered_valid_labels, train_valid_same, train_valid_similar = \\ sanitize_dataset(valid_dataset, valid_labels, train_dataset, 0.001)", "valid_test_same, valid_test_similar = \\ sanitize_dataset(filtered_test_dataset, filtered_test_labels, filtered_valid_dataset, 0.001) print(\"validation-testing: same=\", valid_test_same, \"similar=\", valid_test_similar)", "train(size=None): if size is None: print(\"Training with all examples:\") else: print(\"Training with \",", "= \\ sanitize_dataset(valid_dataset, valid_labels, train_dataset, 0.001) print(\"training-validation: same=\", train_valid_same, \"similar=\", train_valid_similar) filtered_test_dataset, filtered_test_labels,", "+ 1 except IOError as e: print('Could not read:', image_file, ':', e, '-", "def maybe_pickle(data_folders, min_num_images_per_class, force=False): dataset_names = [] for folder in data_folders: set_filename =", "valid_labels = make_arrays(valid_size, image_size) train_dataset, train_labels = make_arrays(train_size, image_size) vsize_per_class = valid_size //", "= 10 np.random.seed(133) def maybe_extract(filename, force=False): root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz if", "pickle.load(f) # Display a random matrix with a specified figure number and a", "= maybe_extract(train_filename) test_folders = maybe_extract(test_filename) #IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png') #IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png') image_size = 28 # Pixel width", "'valid_dataset': filtered_valid_dataset, 'valid_labels': filtered_valid_labels, 'test_dataset': filtered_test_dataset, 'test_labels': filtered_test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close()", "= save['test_labels'] return train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels train_dataset, train_labels, valid_dataset, valid_labels,", "with \", size, \" examples:\") model = train_model(train_dataset, train_labels, size) print(\" validation score:", "sklearn.metrics.pairwise import cosine_similarity from urllib.request import urlretrieve import pickle import IPython # Config", "every 1% change in download progress. \"\"\" global last_percent_reported percent = int(count *", "tensor:', dataset.shape) print('Mean:', np.mean(dataset)) print('Standard deviation:', np.std(dataset)) return dataset def maybe_pickle(data_folders, min_num_images_per_class, force=False):", "5 == 0: sys.stdout.write(\"%s%%\" % percent) sys.stdout.flush() else: sys.stdout.write(\".\") sys.stdout.flush() last_percent_reported = percent", "largeDataA = load_dataset(largeNameA) # img1 = largeDataA[0, :, :] # plt.matshow(img1, cmap=plt.cm.gray) #", "data to', pickle_file, ':', e) raise def load_datasets(pickle_file): statinfo = os.stat(pickle_file) print('Compressed pickle", "model.score(X, y) def train(size=None): if size is None: print(\"Training with all examples:\") else:", "except Exception as e: print('Unable to process data from', pickle_file, ':', e) raise", "pickle_file, ':', e) raise return valid_dataset, valid_labels, train_dataset, train_labels # def show_images(dataset, labels,", "cmap=plt.cm.gray) # plt.show() # Check whether the data is balanced between classes #", "# %matplotlib inline url = 'http://commondatastorage.googleapis.com/books1000/' last_percent_reported = None def download_progress_hook(count, blockSize, totalSize):", "0 for image in image_files: image_file = os.path.join(folder, image) try: image_data = (ndimage.imread(image_file).astype(float)", "'valid_labels': valid_labels, 'test_dataset': test_dataset, 'test_labels': test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception", "= np.sum(similar_filter) filtered_dataset = dataset[same_filter==False] filtered_labels = labels[same_filter==False] return filtered_dataset, filtered_labels, same_count, similar_count", "read:', image_file, ':', e, '- it\\'s ok, skipping.') dataset = dataset[0:num_images, :, :]", "/ 2) / pixel_depth if image_data.shape != (image_size, image_size): raise Exception('Unexpected image shape:", "%s' % str(image_data.shape)) dataset[num_images, :, :] = image_data num_images = num_images + 1", "users with slow internet connections. Reports every 1% change in download progress. \"\"\"", "= maybe_download('notMNIST_small.tar.gz', 8458043) num_classes = 10 np.random.seed(133) def maybe_extract(filename, force=False): root = os.path.splitext(os.path.splitext(filename)[0])[0]", "shape: %s' % str(image_data.shape)) dataset[num_images, :, :] = image_data num_images = num_images +", "# code changed to Python3 import matplotlib import matplotlib.pyplot as plt import numpy", "# show_images(train_dataset, train_labels, 3) # show_images(test_dataset, test_labels, 3) # show_images(valid_dataset, valid_labels, 3) pickle_file", "print('Unable to save data to', pickle_file, ':', e) raise def load_datasets(pickle_file): statinfo =", "labels, count): # for i in range(0,count): # print(labels[i]) # plt.matshow(dataset[i,:,:], cmap=plt.cm.gray) #", "labels[same_filter==False] return filtered_dataset, filtered_labels, same_count, similar_count sanit_pickle_file = 'notMNIST_sanit.pickle' if not os.path.exists(sanit_pickle_file): filtered_valid_dataset,", "train_labels = train_labels[indices] try: f = open(pickle_file, 'wb') save = { 'train_dataset': train_dataset,", "3) pickle_file = 'notMNIST.pickle' if not os.path.exists(pickle_file): train_size = 200000 valid_size = 10000", "percent: if percent % 5 == 0: sys.stdout.write(\"%s%%\" % percent) sys.stdout.flush() else: sys.stdout.write(\".\")", "pickling.' % set_filename) else: print('Pickling %s.' % set_filename) dataset = load_letter(folder, min_num_images_per_class) try:", "= label start_v += vsize_per_class end_v += vsize_per_class train_letter = letter_set[vsize_per_class:end_l, :, :]", "np.sum(similar_filter) filtered_dataset = dataset[same_filter==False] filtered_labels = labels[same_filter==False] return filtered_dataset, filtered_labels, same_count, similar_count sanit_pickle_file", "os.path.join(folder, image) try: image_data = (ndimage.imread(image_file).astype(float) - pixel_depth / 2) / pixel_depth if", "= open(pickle_file, 'rb') save = pickle.load(f) f.close() train_dataset = save['train_dataset'] train_labels = save['train_labels']", "train_dataset[indices] train_labels = train_labels[indices] try: f = open(pickle_file, 'wb') save = { 'train_dataset':", "d))] if len(data_folders) != num_classes: raise Exception( 'Expected %d folders, one per class.", "None: size = maxSize elif size > maxSize: size = maxSize else: dataset", "and height. pixel_depth = 255.0 # Number of levels per pixel. def load_letter(folder,", "== expected_bytes: print('Found and verified', filename) else: raise Exception( 'Failed to verify '", "and training set np.random.shuffle(letter_set) if valid_dataset is not None: valid_letter = letter_set[:vsize_per_class, :,", "dataset[0:num_images, :, :] if num_images < min_num_images: raise Exception('Many fewer images than expected:", "test_dataset = save['test_dataset'] test_labels = save['test_labels'] return train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels", "dataset_names.append(set_filename) if os.path.exists(set_filename) and not force: # You may override by setting force=True.", "= \\ sanitize_dataset(filtered_test_dataset, filtered_test_labels, filtered_valid_dataset, 0.001) print(\"validation-testing: same=\", valid_test_same, \"similar=\", valid_test_similar) try: f", "load_letter(folder, min_num_images): \"\"\"Load the data for a single letter label.\"\"\" image_files = os.listdir(folder)", "cmap=plt.cm.gray) # plt.show() # # smallNameJ = test_datasets[9] # print(smallNameJ) # smallDataJ =", "if nb_rows: dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32) labels = np.ndarray(nb_rows, dtype=np.int32) else:", "print('Could not read:', image_file, ':', e, '- it\\'s ok, skipping.') dataset = dataset[0:num_images,", "save data to', pickle_file, ':', e) raise def load_datasets(pickle_file): statinfo = os.stat(pickle_file) print('Compressed", "LogisticRegression(n_jobs=4) lr.fit(X, y) return lr def model_score(model, dataset, labels): X = np.reshape(dataset, (dataset.shape[0],-1))", "in train_datasets: # dataset = load_dataset(name) # print(name, ' size:', dataset.shape) # #", "load_dataset(smallNameJ) # img2 = smallDataJ[0, :, :] # plt.matshow(img2, cmap=plt.cm.gray) # plt.show() #", ":, :] = image_data num_images = num_images + 1 except IOError as e:", "save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': valid_dataset, 'valid_labels': valid_labels, 'test_dataset': test_dataset,", "(sanitized): \", model_score(model, filtered_valid_dataset, filtered_valid_labels)) print(\" test score (sanitized): \", model_score(model, filtered_test_dataset, filtered_test_labels))", "balanced between classes # for name in train_datasets: # dataset = load_dataset(name) #", "model_score(model, filtered_test_dataset, filtered_test_labels)) for size in [50, 100, 1000, 5000]: train(size) # training", "i in range(0,count): # print(labels[i]) # plt.matshow(dataset[i,:,:], cmap=plt.cm.gray) # plt.show() # show_images(train_dataset, train_labels,", "number and a grayscale colormap # largeNameA = train_datasets[0] # print(largeNameA) # largeDataA", "train_datasets[0] # print(largeNameA) # largeDataA = load_dataset(largeNameA) # img1 = largeDataA[0, :, :]", "= pickle.load(f) # let's shuffle the letters to have random validation and training", "e) raise train_dataset, train_labels, filtered_valid_dataset, filtered_valid_labels, filtered_test_dataset, filtered_test_labels = load_datasets(sanit_pickle_file) print('Training (sanitized):', train_dataset.shape,", "validation score (sanitized): \", model_score(model, filtered_valid_dataset, filtered_valid_labels)) print(\" test score (sanitized): \", model_score(model,", "wait.' % root) tar = tarfile.open(filename) sys.stdout.flush() tar.extractall() tar.close() data_folders = [ os.path.join(root,", "to save data to', pickle_file, ':', e) raise train_dataset, train_labels, filtered_valid_dataset, filtered_valid_labels, filtered_test_dataset,", "# for name in test_datasets: # dataset = load_dataset(name) # print(name, ' size:',", "open(sanit_pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': filtered_valid_dataset, 'valid_labels': filtered_valid_labels,", "one per class. Found %d instead.' % ( num_classes, len(data_folders))) print(data_folders) return data_folders", "e: print('Unable to save data to', pickle_file, ':', e) raise train_dataset, train_labels, filtered_valid_dataset,", "= num_images + 1 except IOError as e: print('Could not read:', image_file, ':',", "pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable to save data to', set_filename, ':', e)", "os.path.exists(sanit_pickle_file): filtered_valid_dataset, filtered_valid_labels, train_valid_same, train_valid_similar = \\ sanitize_dataset(valid_dataset, valid_labels, train_dataset, 0.001) print(\"training-validation: same=\",", "\", model_score(model, filtered_test_dataset, filtered_test_labels)) for size in [50, 100, 1000, 5000]: train(size) #", "raise def load_datasets(pickle_file): statinfo = os.stat(pickle_file) print('Compressed pickle size:', statinfo.st_size) f = open(pickle_file,", "dataset, labels = None, None return dataset, labels def merge_datasets(pickle_files, train_size, valid_size=0): num_classes", "blockSize * 100 / totalSize) if last_percent_reported != percent: if percent % 5", "img1 = largeDataA[0, :, :] # plt.matshow(img1, cmap=plt.cm.gray) # plt.show() # # smallNameJ", "size:', dataset.shape) def make_arrays(nb_rows, img_size): if nb_rows: dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32)", "not os.path.exists(pickle_file): train_size = 200000 valid_size = 10000 test_size = 10000 valid_dataset, valid_labels,", "for size in [50, 100, 1000, 5000]: train(size) # training on all examples:", "and make sure it's the right size.\"\"\" if force or not os.path.exists(filename): print('Attempting", "image_size), dtype=np.float32) print(folder) num_images = 0 for image in image_files: image_file = os.path.join(folder,", "data is balanced between classes # for name in train_datasets: # dataset =", "print(\" test score (sanitized): \", model_score(model, filtered_test_dataset, filtered_test_labels)) for size in [50, 100,", "import urlretrieve import pickle import IPython # Config the matlotlib backend as plotting", "pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable to save data to', set_filename,", "// num_classes start_v, start_t = 0, 0 end_v, end_t = vsize_per_class, tsize_per_class end_l", "train_test_same, \"similar=\", train_test_similar) filtered_test_dataset, filtered_test_labels, valid_test_same, valid_test_similar = \\ sanitize_dataset(filtered_test_dataset, filtered_test_labels, filtered_valid_dataset, 0.001)", "= cosine_similarity(np.reshape(dataset, (dataset.shape[0],-1)), np.reshape(filter_dataset, (filter_dataset.shape[0],-1))) same_filter = np.sum(similarity == 1, axis=1) > 0", "X = np.reshape(dataset, (size,-1)) y = labels lr = LogisticRegression(n_jobs=4) lr.fit(X, y) return", "return lr def model_score(model, dataset, labels): X = np.reshape(dataset, (dataset.shape[0],-1)) y = labels", ":] = train_letter train_labels[start_t:end_t] = label start_t += tsize_per_class end_t += tsize_per_class except", "filtered_test_dataset, filtered_test_labels, train_test_same, train_test_similar = \\ sanitize_dataset(test_dataset, test_labels, train_dataset, 0.001) print(\"training-testing: same=\", train_test_same,", "'. Can you get to it with a browser?') return filename train_filename =", "show_images(train_dataset, train_labels, 3) # show_images(test_dataset, test_labels, 3) # show_images(valid_dataset, valid_labels, 3) pickle_file =", "= { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': filtered_valid_dataset, 'valid_labels': filtered_valid_labels, 'test_dataset': filtered_test_dataset, 'test_labels':", ":, :] # plt.matshow(img1, cmap=plt.cm.gray) # plt.show() # # smallNameJ = test_datasets[9] #", "urlretrieve(url + filename, filename, reporthook=download_progress_hook) print('\\nDownload Complete!') statinfo = os.stat(filename) if statinfo.st_size ==", "# plt.matshow(img2, cmap=plt.cm.gray) # plt.show() # Check whether the data is balanced between", "if not os.path.exists(pickle_file): train_size = 200000 valid_size = 10000 test_size = 10000 valid_dataset,", "else: print('Extracting data for %s. This may take a while. Please wait.' %", "cosine_similarity from urllib.request import urlretrieve import pickle import IPython # Config the matlotlib", "maybe_extract(train_filename) test_folders = maybe_extract(test_filename) #IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png') #IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png') image_size = 28 # Pixel width and", "axis=1) > 0 similar_filter = np.sum(similarity > 1-similarity_epsilon, axis=1) > 0 same_count =", "force=False): \"\"\"Download a file if not present, and make sure it's the right", "filtered_test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as e: print('Unable to save", "plt.matshow(img2, cmap=plt.cm.gray) # plt.show() # Check whether the data is balanced between classes", "pickle size:', statinfo.st_size) f = open(pickle_file, 'rb') save = pickle.load(f) f.close() train_dataset =", "with open(filename, 'rb') as f: return pickle.load(f) # Display a random matrix with", "intended for users with slow internet connections. Reports every 1% change in download", "num_classes: raise Exception( 'Expected %d folders, one per class. Found %d instead.' %", "dataset[same_filter==False] filtered_labels = labels[same_filter==False] return filtered_dataset, filtered_labels, same_count, similar_count sanit_pickle_file = 'notMNIST_sanit.pickle' if", "%s.' % (root, filename)) else: print('Extracting data for %s. This may take a", "if valid_dataset is not None: valid_letter = letter_set[:vsize_per_class, :, :] valid_dataset[start_v:end_v, :, :]", ":, :] = valid_letter valid_labels[start_v:end_v] = label start_v += vsize_per_class end_v += vsize_per_class", "sanitize_dataset(valid_dataset, valid_labels, train_dataset, 0.001) print(\"training-validation: same=\", train_valid_same, \"similar=\", train_valid_similar) filtered_test_dataset, filtered_test_labels, train_test_same, train_test_similar", "all examples:\") else: print(\"Training with \", size, \" examples:\") model = train_model(train_dataset, train_labels,", "Number of levels per pixel. def load_letter(folder, min_num_images): \"\"\"Load the data for a", "train_size = 200000 valid_size = 10000 test_size = 10000 valid_dataset, valid_labels, train_dataset, train_labels", "\", model_score(model, filtered_valid_dataset, filtered_valid_labels)) print(\" test score (sanitized): \", model_score(model, filtered_test_dataset, filtered_test_labels)) for", "dataset = np.ndarray(shape=(len(image_files), image_size, image_size), dtype=np.float32) print(folder) num_images = 0 for image in", "e: print('Unable to save data to', pickle_file, ':', e) raise def load_datasets(pickle_file): statinfo", "return dataset_names train_datasets = maybe_pickle(train_folders, 45000) test_datasets = maybe_pickle(test_folders, 1800) def load_dataset(filename): with", "cmap=plt.cm.gray) # plt.show() # show_images(train_dataset, train_labels, 3) # show_images(test_dataset, test_labels, 3) # show_images(valid_dataset,", "\"similar=\", valid_test_similar) try: f = open(sanit_pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels':", "labels lr = LogisticRegression(n_jobs=4) lr.fit(X, y) return lr def model_score(model, dataset, labels): X", "if size is None: print(\"Training with all examples:\") else: print(\"Training with \", size,", "valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets( train_datasets, train_size, valid_size) _, _, test_dataset, test_labels", "< min_num_images: raise Exception('Many fewer images than expected: %d < %d' % (num_images,", "dataset tensor:', dataset.shape) print('Mean:', np.mean(dataset)) print('Standard deviation:', np.std(dataset)) return dataset def maybe_pickle(data_folders, min_num_images_per_class,", "+ tsize_per_class for label, pickle_file in enumerate(pickle_files): try: with open(pickle_file, 'rb') as f:", "} pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as e: print('Unable to save data", "for image in image_files: image_file = os.path.join(folder, image) try: image_data = (ndimage.imread(image_file).astype(float) -", "sys.stdout.write(\".\") sys.stdout.flush() last_percent_reported = percent def maybe_download(filename, expected_bytes, force=False): \"\"\"Download a file if", "sanitize_dataset(dataset, labels, filter_dataset, similarity_epsilon): similarity = cosine_similarity(np.reshape(dataset, (dataset.shape[0],-1)), np.reshape(filter_dataset, (filter_dataset.shape[0],-1))) same_filter = np.sum(similarity", "* blockSize * 100 / totalSize) if last_percent_reported != percent: if percent %", "os.path.exists(set_filename) and not force: # You may override by setting force=True. print('%s already", "= largeDataA[0, :, :] # plt.matshow(img1, cmap=plt.cm.gray) # plt.show() # # smallNameJ =", "= \\ sanitize_dataset(test_dataset, test_labels, train_dataset, 0.001) print(\"training-testing: same=\", train_test_same, \"similar=\", train_test_similar) filtered_test_dataset, filtered_test_labels,", "num_classes start_v, start_t = 0, 0 end_v, end_t = vsize_per_class, tsize_per_class end_l =", "{ 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': filtered_valid_dataset, 'valid_labels': filtered_valid_labels, 'test_dataset': filtered_test_dataset, 'test_labels': filtered_test_labels,", "pickle.HIGHEST_PROTOCOL) f.close() except Exception as e: print('Unable to save data to', pickle_file, ':',", "print('Found and verified', filename) else: raise Exception( 'Failed to verify ' + filename", "save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': filtered_valid_dataset, 'valid_labels': filtered_valid_labels, 'test_dataset': filtered_test_dataset,", "as e: print('Unable to save data to', pickle_file, ':', e) raise def load_datasets(pickle_file):", "score (sanitized): \", model_score(model, filtered_test_dataset, filtered_test_labels)) for size in [50, 100, 1000, 5000]:", "percent = int(count * blockSize * 100 / totalSize) if last_percent_reported != percent:", "_, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size) indices = np.arange(train_dataset.shape[0]) np.random.shuffle(indices) train_dataset =", "img2 = smallDataJ[0, :, :] # plt.matshow(img2, cmap=plt.cm.gray) # plt.show() # Check whether", "specified figure number and a grayscale colormap # largeNameA = train_datasets[0] # print(largeNameA)", "= maybe_pickle(test_folders, 1800) def load_dataset(filename): with open(filename, 'rb') as f: return pickle.load(f) #", "show_images(valid_dataset, valid_labels, 3) pickle_file = 'notMNIST.pickle' if not os.path.exists(pickle_file): train_size = 200000 valid_size", "num_classes = len(pickle_files) valid_dataset, valid_labels = make_arrays(valid_size, image_size) train_dataset, train_labels = make_arrays(train_size, image_size)", "= (ndimage.imread(image_file).astype(float) - pixel_depth / 2) / pixel_depth if image_data.shape != (image_size, image_size):", "= load_letter(folder, min_num_images_per_class) try: with open(set_filename, 'wb') as f: pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL) except", "tsize_per_class end_t += tsize_per_class except Exception as e: print('Unable to process data from',", "numpy as np import os import sys import tarfile from IPython.display import display,", "may override by setting force=True. print('%s already present - Skipping extraction of %s.'", "np.arange(train_dataset.shape[0]) np.random.shuffle(indices) train_dataset = train_dataset[indices] train_labels = train_labels[indices] try: f = open(pickle_file, 'wb')", "y = labels return model.score(X, y) def train(size=None): if size is None: print(\"Training", "train_labels, 'valid_dataset': valid_dataset, 'valid_labels': valid_labels, 'test_dataset': test_dataset, 'test_labels': test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL)", "download:', filename) filename, _ = urlretrieve(url + filename, filename, reporthook=download_progress_hook) print('\\nDownload Complete!') statinfo", "% root) tar = tarfile.open(filename) sys.stdout.flush() tar.extractall() tar.close() data_folders = [ os.path.join(root, d)", "= dataset[0:num_images, :, :] if num_images < min_num_images: raise Exception('Many fewer images than", "(sanitized): \", model_score(model, filtered_test_dataset, filtered_test_labels)) for size in [50, 100, 1000, 5000]: train(size)", "tsize_per_class end_l = vsize_per_class + tsize_per_class for label, pickle_file in enumerate(pickle_files): try: with", "last_percent_reported = None def download_progress_hook(count, blockSize, totalSize): \"\"\"A hook to report the progress", "modules we'll be using later. Make sure you can import them # before", "be using later. Make sure you can import them # before proceeding further.", "image_file, ':', e, '- it\\'s ok, skipping.') dataset = dataset[0:num_images, :, :] if", "totalSize): \"\"\"A hook to report the progress of a download. This is mostly", "print(\"validation-testing: same=\", valid_test_same, \"similar=\", valid_test_similar) try: f = open(sanit_pickle_file, 'wb') save = {", "count): # for i in range(0,count): # print(labels[i]) # plt.matshow(dataset[i,:,:], cmap=plt.cm.gray) # plt.show()", "a specified figure number and a grayscale colormap # largeNameA = train_datasets[0] #", "= 0, 0 end_v, end_t = vsize_per_class, tsize_per_class end_l = vsize_per_class + tsize_per_class", "url = 'http://commondatastorage.googleapis.com/books1000/' last_percent_reported = None def download_progress_hook(count, blockSize, totalSize): \"\"\"A hook to", "%d instead.' % ( num_classes, len(data_folders))) print(data_folders) return data_folders train_folders = maybe_extract(train_filename) test_folders", "train_labels = merge_datasets( train_datasets, train_size, valid_size) _, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size)", "smallDataJ = load_dataset(smallNameJ) # img2 = smallDataJ[0, :, :] # plt.matshow(img2, cmap=plt.cm.gray) #", "axis=1) > 0 same_count = np.sum(same_filter) similar_count = np.sum(similar_filter) filtered_dataset = dataset[same_filter==False] filtered_labels", "else: print(\"Training with \", size, \" examples:\") model = train_model(train_dataset, train_labels, size) print(\"", "* 100 / totalSize) if last_percent_reported != percent: if percent % 5 ==", "= dataset.shape[0] if size is None: size = maxSize elif size > maxSize:", "valid_dataset, valid_labels, test_dataset, test_labels train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels = load_datasets(pickle_file) print('Training:',", "num_images = 0 for image in image_files: image_file = os.path.join(folder, image) try: image_data", "filtered_valid_labels, filtered_test_dataset, filtered_test_labels = load_datasets(sanit_pickle_file) print('Training (sanitized):', train_dataset.shape, train_labels.shape) print('Validation (sanitized):', filtered_valid_dataset.shape, filtered_valid_labels.shape)", "= 'http://commondatastorage.googleapis.com/books1000/' last_percent_reported = None def download_progress_hook(count, blockSize, totalSize): \"\"\"A hook to report", "print(\"training-testing: same=\", train_test_same, \"similar=\", train_test_similar) filtered_test_dataset, filtered_test_labels, valid_test_same, valid_test_similar = \\ sanitize_dataset(filtered_test_dataset, filtered_test_labels,", "between classes # for name in train_datasets: # dataset = load_dataset(name) # print(name,", "training set np.random.shuffle(letter_set) if valid_dataset is not None: valid_letter = letter_set[:vsize_per_class, :, :]", "train_dataset, train_labels, filtered_valid_dataset, filtered_valid_labels, filtered_test_dataset, filtered_test_labels = load_datasets(sanit_pickle_file) print('Training (sanitized):', train_dataset.shape, train_labels.shape) print('Validation", "else: print('Pickling %s.' % set_filename) dataset = load_letter(folder, min_num_images_per_class) try: with open(set_filename, 'wb')", "try: image_data = (ndimage.imread(image_file).astype(float) - pixel_depth / 2) / pixel_depth if image_data.shape !=", "= open(pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'valid_dataset': valid_dataset, 'valid_labels':", "dataset.shape) def make_arrays(nb_rows, img_size): if nb_rows: dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32) labels", "reporthook=download_progress_hook) print('\\nDownload Complete!') statinfo = os.stat(filename) if statinfo.st_size == expected_bytes: print('Found and verified',", "merge_datasets(test_datasets, test_size) indices = np.arange(train_dataset.shape[0]) np.random.shuffle(indices) train_dataset = train_dataset[indices] train_labels = train_labels[indices] try:", "cosine_similarity(np.reshape(dataset, (dataset.shape[0],-1)), np.reshape(filter_dataset, (filter_dataset.shape[0],-1))) same_filter = np.sum(similarity == 1, axis=1) > 0 similar_filter", "to Python3 import matplotlib import matplotlib.pyplot as plt import numpy as np import", "random validation and training set np.random.shuffle(letter_set) if valid_dataset is not None: valid_letter =", "= maxSize else: dataset = dataset[0:size] labels = labels[0:size] X = np.reshape(dataset, (size,-1))", "dtype=np.float32) print(folder) num_images = 0 for image in image_files: image_file = os.path.join(folder, image)", "= labels lr = LogisticRegression(n_jobs=4) lr.fit(X, y) return lr def model_score(model, dataset, labels):", "train_labels, size) print(\" validation score: \", model_score(model, valid_dataset, valid_labels)) print(\" test score: \",", "def load_dataset(filename): with open(filename, 'rb') as f: return pickle.load(f) # Display a random", "% set_filename) else: print('Pickling %s.' % set_filename) dataset = load_letter(folder, min_num_images_per_class) try: with", "train_labels, valid_dataset, valid_labels, test_dataset, test_labels = load_datasets(pickle_file) print('Training:', train_dataset.shape, train_labels.shape) print('Validation:', valid_dataset.shape, valid_labels.shape)", "+= tsize_per_class end_t += tsize_per_class except Exception as e: print('Unable to process data", "lr def model_score(model, dataset, labels): X = np.reshape(dataset, (dataset.shape[0],-1)) y = labels return", "1% change in download progress. \"\"\" global last_percent_reported percent = int(count * blockSize", "them # before proceeding further. # code changed to Python3 import matplotlib import", "valid_size = 10000 test_size = 10000 valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets( train_datasets,", "( num_classes, len(data_folders))) print(data_folders) return data_folders train_folders = maybe_extract(train_filename) test_folders = maybe_extract(test_filename) #IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png')", "grayscale colormap # largeNameA = train_datasets[0] # print(largeNameA) # largeDataA = load_dataset(largeNameA) #", "return valid_dataset, valid_labels, train_dataset, train_labels # def show_images(dataset, labels, count): # for i", "nb_rows: dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32) labels = np.ndarray(nb_rows, dtype=np.int32) else: dataset,", "= pickle.load(f) f.close() train_dataset = save['train_dataset'] train_labels = save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels", "valid_size) _, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size) indices = np.arange(train_dataset.shape[0]) np.random.shuffle(indices) train_dataset", "# Config the matlotlib backend as plotting inline in IPython # %matplotlib inline", "# plt.show() # # smallNameJ = test_datasets[9] # print(smallNameJ) # smallDataJ = load_dataset(smallNameJ)", "return dataset, labels def merge_datasets(pickle_files, train_size, valid_size=0): num_classes = len(pickle_files) valid_dataset, valid_labels =", "+= tsize_per_class except Exception as e: print('Unable to process data from', pickle_file, ':',", "print(\" validation score: \", model_score(model, valid_dataset, valid_labels)) print(\" test score: \", model_score(model, test_dataset,", "def download_progress_hook(count, blockSize, totalSize): \"\"\"A hook to report the progress of a download.", "Can you get to it with a browser?') return filename train_filename = maybe_download('notMNIST_large.tar.gz',", "import pickle import IPython # Config the matlotlib backend as plotting inline in", "sys.stdout.flush() else: sys.stdout.write(\".\") sys.stdout.flush() last_percent_reported = percent def maybe_download(filename, expected_bytes, force=False): \"\"\"Download a", "filename, reporthook=download_progress_hook) print('\\nDownload Complete!') statinfo = os.stat(filename) if statinfo.st_size == expected_bytes: print('Found and", "Found %d instead.' % ( num_classes, len(data_folders))) print(data_folders) return data_folders train_folders = maybe_extract(train_filename)", "for folder in data_folders: set_filename = folder + '.pickle' dataset_names.append(set_filename) if os.path.exists(set_filename) and", "try: with open(set_filename, 'wb') as f: pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL) except Exception as e:", "of a download. This is mostly intended for users with slow internet connections.", "return train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels", "'test_dataset': test_dataset, 'test_labels': test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as e:", "validation and training set np.random.shuffle(letter_set) if valid_dataset is not None: valid_letter = letter_set[:vsize_per_class,", "filtered_valid_labels.shape) print('Testing (sanitized):', filtered_test_dataset.shape, filtered_test_labels.shape) def train_model(dataset, labels, size=None): maxSize = dataset.shape[0] if", "np.mean(dataset)) print('Standard deviation:', np.std(dataset)) return dataset def maybe_pickle(data_folders, min_num_images_per_class, force=False): dataset_names = []", "# img1 = largeDataA[0, :, :] # plt.matshow(img1, cmap=plt.cm.gray) # plt.show() # #", "3) # show_images(test_dataset, test_labels, 3) # show_images(valid_dataset, valid_labels, 3) pickle_file = 'notMNIST.pickle' if", "print('Unable to save data to', set_filename, ':', e) return dataset_names train_datasets = maybe_pickle(train_folders,", "np.std(dataset)) return dataset def maybe_pickle(data_folders, min_num_images_per_class, force=False): dataset_names = [] for folder in", "test_labels = load_datasets(pickle_file) print('Training:', train_dataset.shape, train_labels.shape) print('Validation:', valid_dataset.shape, valid_labels.shape) print('Testing:', test_dataset.shape, test_labels.shape) def", "filtered_valid_dataset, 'valid_labels': filtered_valid_labels, 'test_dataset': filtered_test_dataset, 'test_labels': filtered_test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except", "> 0 same_count = np.sum(same_filter) similar_count = np.sum(similar_filter) filtered_dataset = dataset[same_filter==False] filtered_labels =", "size is None: size = maxSize elif size > maxSize: size = maxSize", "or not os.path.exists(filename): print('Attempting to download:', filename) filename, _ = urlretrieve(url + filename,", "in image_files: image_file = os.path.join(folder, image) try: image_data = (ndimage.imread(image_file).astype(float) - pixel_depth /", "matplotlib import matplotlib.pyplot as plt import numpy as np import os import sys", "# Display a random matrix with a specified figure number and a grayscale", "= 10000 test_size = 10000 valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets( train_datasets, train_size,", "min_num_images): \"\"\"Load the data for a single letter label.\"\"\" image_files = os.listdir(folder) dataset", "for a single letter label.\"\"\" image_files = os.listdir(folder) dataset = np.ndarray(shape=(len(image_files), image_size, image_size),", "os.path.join(root, d) for d in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, d))] if len(data_folders) != num_classes:", "# largeNameA = train_datasets[0] # print(largeNameA) # largeDataA = load_dataset(largeNameA) # img1 =", "(sanitized):', train_dataset.shape, train_labels.shape) print('Validation (sanitized):', filtered_valid_dataset.shape, filtered_valid_labels.shape) print('Testing (sanitized):', filtered_test_dataset.shape, filtered_test_labels.shape) def train_model(dataset,", "except Exception as e: print('Unable to save data to', set_filename, ':', e) return", "= letter_set[vsize_per_class:end_l, :, :] train_dataset[start_t:end_t, :, :] = train_letter train_labels[start_t:end_t] = label start_t", "score: \", model_score(model, test_dataset, test_labels)) print(\" validation score (sanitized): \", model_score(model, filtered_valid_dataset, filtered_valid_labels))", "'test_labels': test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as e: print('Unable to", "= vsize_per_class, tsize_per_class end_l = vsize_per_class + tsize_per_class for label, pickle_file in enumerate(pickle_files):", "valid_letter = letter_set[:vsize_per_class, :, :] valid_dataset[start_v:end_v, :, :] = valid_letter valid_labels[start_v:end_v] = label", "can import them # before proceeding further. # code changed to Python3 import", "y) return lr def model_score(model, dataset, labels): X = np.reshape(dataset, (dataset.shape[0],-1)) y =", "if num_images < min_num_images: raise Exception('Many fewer images than expected: %d < %d'", "vsize_per_class, tsize_per_class end_l = vsize_per_class + tsize_per_class for label, pickle_file in enumerate(pickle_files): try:", "valid_dataset, 'valid_labels': valid_labels, 'test_dataset': test_dataset, 'test_labels': test_labels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except", "if statinfo.st_size == expected_bytes: print('Found and verified', filename) else: raise Exception( 'Failed to", "valid_test_similar = \\ sanitize_dataset(filtered_test_dataset, filtered_test_labels, filtered_valid_dataset, 0.001) print(\"validation-testing: same=\", valid_test_same, \"similar=\", valid_test_similar) try:", "train_test_same, train_test_similar = \\ sanitize_dataset(test_dataset, test_labels, train_dataset, 0.001) print(\"training-testing: same=\", train_test_same, \"similar=\", train_test_similar)", "print('Attempting to download:', filename) filename, _ = urlretrieve(url + filename, filename, reporthook=download_progress_hook) print('\\nDownload", "train_test_similar) filtered_test_dataset, filtered_test_labels, valid_test_same, valid_test_similar = \\ sanitize_dataset(filtered_test_dataset, filtered_test_labels, filtered_valid_dataset, 0.001) print(\"validation-testing: same=\",", "test_dataset, test_labels)) print(\" validation score (sanitized): \", model_score(model, filtered_valid_dataset, filtered_valid_labels)) print(\" test score", "is mostly intended for users with slow internet connections. Reports every 1% change", "dataset, labels def merge_datasets(pickle_files, train_size, valid_size=0): num_classes = len(pickle_files) valid_dataset, valid_labels = make_arrays(valid_size,", "valid_size=0): num_classes = len(pickle_files) valid_dataset, valid_labels = make_arrays(valid_size, image_size) train_dataset, train_labels = make_arrays(train_size,", "valid_labels, 3) pickle_file = 'notMNIST.pickle' if not os.path.exists(pickle_file): train_size = 200000 valid_size =", "of %s.' % (root, filename)) else: print('Extracting data for %s. This may take", "train_labels, 3) # show_images(test_dataset, test_labels, 3) # show_images(valid_dataset, valid_labels, 3) pickle_file = 'notMNIST.pickle'", "present - Skipping extraction of %s.' % (root, filename)) else: print('Extracting data for", "IPython.display import display, Image from scipy import ndimage from sklearn.linear_model import LogisticRegression from", "as e: print('Unable to process data from', pickle_file, ':', e) raise return valid_dataset,", "np.sum(similarity == 1, axis=1) > 0 similar_filter = np.sum(similarity > 1-similarity_epsilon, axis=1) >", "= [ os.path.join(root, d) for d in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, d))] if len(data_folders)", "enumerate(pickle_files): try: with open(pickle_file, 'rb') as f: letter_set = pickle.load(f) # let's shuffle", "import them # before proceeding further. # code changed to Python3 import matplotlib", "% 5 == 0: sys.stdout.write(\"%s%%\" % percent) sys.stdout.flush() else: sys.stdout.write(\".\") sys.stdout.flush() last_percent_reported =", "save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset = save['test_dataset'] test_labels = save['test_labels']", "maybe_download('notMNIST_large.tar.gz', 247336696) test_filename = maybe_download('notMNIST_small.tar.gz', 8458043) num_classes = 10 np.random.seed(133) def maybe_extract(filename, force=False):", "= letter_set[:vsize_per_class, :, :] valid_dataset[start_v:end_v, :, :] = valid_letter valid_labels[start_v:end_v] = label start_v", "test_dataset.shape, test_labels.shape) def sanitize_dataset(dataset, labels, filter_dataset, similarity_epsilon): similarity = cosine_similarity(np.reshape(dataset, (dataset.shape[0],-1)), np.reshape(filter_dataset, (filter_dataset.shape[0],-1)))", "maxSize elif size > maxSize: size = maxSize else: dataset = dataset[0:size] labels", "make sure it's the right size.\"\"\" if force or not os.path.exists(filename): print('Attempting to", "= 'notMNIST.pickle' if not os.path.exists(pickle_file): train_size = 200000 valid_size = 10000 test_size =", "os.stat(filename) if statinfo.st_size == expected_bytes: print('Found and verified', filename) else: raise Exception( 'Failed", "train_valid_same, train_valid_similar = \\ sanitize_dataset(valid_dataset, valid_labels, train_dataset, 0.001) print(\"training-validation: same=\", train_valid_same, \"similar=\", train_valid_similar)", "open(pickle_file, 'rb') as f: letter_set = pickle.load(f) # let's shuffle the letters to", "Exception as e: print('Unable to process data from', pickle_file, ':', e) raise return", "except Exception as e: print('Unable to save data to', pickle_file, ':', e) raise", "import IPython # Config the matlotlib backend as plotting inline in IPython #", "range(0,count): # print(labels[i]) # plt.matshow(dataset[i,:,:], cmap=plt.cm.gray) # plt.show() # show_images(train_dataset, train_labels, 3) #", "pixel_depth / 2) / pixel_depth if image_data.shape != (image_size, image_size): raise Exception('Unexpected image", "1 except IOError as e: print('Could not read:', image_file, ':', e, '- it\\'s", "test_labels = merge_datasets(test_datasets, test_size) indices = np.arange(train_dataset.shape[0]) np.random.shuffle(indices) train_dataset = train_dataset[indices] train_labels =", "test_datasets = maybe_pickle(test_folders, 1800) def load_dataset(filename): with open(filename, 'rb') as f: return pickle.load(f)", "\", model_score(model, test_dataset, test_labels)) print(\" validation score (sanitized): \", model_score(model, filtered_valid_dataset, filtered_valid_labels)) print(\"", "valid_dataset, valid_labels = make_arrays(valid_size, image_size) train_dataset, train_labels = make_arrays(train_size, image_size) vsize_per_class = valid_size", "def sanitize_dataset(dataset, labels, filter_dataset, similarity_epsilon): similarity = cosine_similarity(np.reshape(dataset, (dataset.shape[0],-1)), np.reshape(filter_dataset, (filter_dataset.shape[0],-1))) same_filter =", "' size:', dataset.shape) def make_arrays(nb_rows, img_size): if nb_rows: dataset = np.ndarray((nb_rows, img_size, img_size),", "with all examples:\") else: print(\"Training with \", size, \" examples:\") model = train_model(train_dataset,", "whether the data is balanced between classes # for name in train_datasets: #", "raise Exception( 'Failed to verify ' + filename + '. Can you get", "# These are all the modules we'll be using later. Make sure you", "img_size), dtype=np.float32) labels = np.ndarray(nb_rows, dtype=np.int32) else: dataset, labels = None, None return", "you can import them # before proceeding further. # code changed to Python3", "import ndimage from sklearn.linear_model import LogisticRegression from sklearn.metrics.pairwise import cosine_similarity from urllib.request import", "train_dataset.shape, train_labels.shape) print('Validation:', valid_dataset.shape, valid_labels.shape) print('Testing:', test_dataset.shape, test_labels.shape) def sanitize_dataset(dataset, labels, filter_dataset, similarity_epsilon):", "filtered_dataset = dataset[same_filter==False] filtered_labels = labels[same_filter==False] return filtered_dataset, filtered_labels, same_count, similar_count sanit_pickle_file =", "print('Full dataset tensor:', dataset.shape) print('Mean:', np.mean(dataset)) print('Standard deviation:', np.std(dataset)) return dataset def maybe_pickle(data_folders,", ":] = image_data num_images = num_images + 1 except IOError as e: print('Could", "print('Testing:', test_dataset.shape, test_labels.shape) def sanitize_dataset(dataset, labels, filter_dataset, similarity_epsilon): similarity = cosine_similarity(np.reshape(dataset, (dataset.shape[0],-1)), np.reshape(filter_dataset,", "y = labels lr = LogisticRegression(n_jobs=4) lr.fit(X, y) return lr def model_score(model, dataset,", "\\ sanitize_dataset(filtered_test_dataset, filtered_test_labels, filtered_valid_dataset, 0.001) print(\"validation-testing: same=\", valid_test_same, \"similar=\", valid_test_similar) try: f =", "= make_arrays(train_size, image_size) vsize_per_class = valid_size // num_classes tsize_per_class = train_size // num_classes", "and not force: # You may override by setting force=True. print('%s already present", "train_dataset, train_labels # def show_images(dataset, labels, count): # for i in range(0,count): #", "= np.reshape(dataset, (size,-1)) y = labels lr = LogisticRegression(n_jobs=4) lr.fit(X, y) return lr", "import matplotlib.pyplot as plt import numpy as np import os import sys import", "hook to report the progress of a download. This is mostly intended for", "file if not present, and make sure it's the right size.\"\"\" if force", "os.path.isdir(root) and not force: # You may override by setting force=True. print('%s already", "a while. Please wait.' % root) tar = tarfile.open(filename) sys.stdout.flush() tar.extractall() tar.close() data_folders", "start_t = 0, 0 end_v, end_t = vsize_per_class, tsize_per_class end_l = vsize_per_class +", "_ = urlretrieve(url + filename, filename, reporthook=download_progress_hook) print('\\nDownload Complete!') statinfo = os.stat(filename) if", "validation score: \", model_score(model, valid_dataset, valid_labels)) print(\" test score: \", model_score(model, test_dataset, test_labels))", "labels = None, None return dataset, labels def merge_datasets(pickle_files, train_size, valid_size=0): num_classes =", "proceeding further. # code changed to Python3 import matplotlib import matplotlib.pyplot as plt", "using later. Make sure you can import them # before proceeding further. #", "try: with open(pickle_file, 'rb') as f: letter_set = pickle.load(f) # let's shuffle the", "# print(smallNameJ) # smallDataJ = load_dataset(smallNameJ) # img2 = smallDataJ[0, :, :] #", "0.001) print(\"training-testing: same=\", train_test_same, \"similar=\", train_test_similar) filtered_test_dataset, filtered_test_labels, valid_test_same, valid_test_similar = \\ sanitize_dataset(filtered_test_dataset,", "train_dataset, train_labels = make_arrays(train_size, image_size) vsize_per_class = valid_size // num_classes tsize_per_class = train_size", "data from', pickle_file, ':', e) raise return valid_dataset, valid_labels, train_dataset, train_labels # def", "Skipping extraction of %s.' % (root, filename)) else: print('Extracting data for %s. This", "len(data_folders))) print(data_folders) return data_folders train_folders = maybe_extract(train_filename) test_folders = maybe_extract(test_filename) #IPython.display.display_png('notMNIST_large/B/MDEtMDEtMDAudHRm.png') #IPython.display.display_png('notMNIST_large/J/Nng3b2N0IEFsdGVybmF0ZSBSZWd1bGFyLnR0Zg==.png') image_size", "= save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset = save['test_dataset'] test_labels =", "as plt import numpy as np import os import sys import tarfile from", "with slow internet connections. Reports every 1% change in download progress. \"\"\" global", "size is None: print(\"Training with all examples:\") else: print(\"Training with \", size, \"", "= labels return model.score(X, y) def train(size=None): if size is None: print(\"Training with", "as plotting inline in IPython # %matplotlib inline url = 'http://commondatastorage.googleapis.com/books1000/' last_percent_reported =", "Exception as e: print('Unable to save data to', pickle_file, ':', e) raise def", "maybe_pickle(train_folders, 45000) test_datasets = maybe_pickle(test_folders, 1800) def load_dataset(filename): with open(filename, 'rb') as f:", "size = maxSize else: dataset = dataset[0:size] labels = labels[0:size] X = np.reshape(dataset,", "and verified', filename) else: raise Exception( 'Failed to verify ' + filename +", "to', set_filename, ':', e) return dataset_names train_datasets = maybe_pickle(train_folders, 45000) test_datasets = maybe_pickle(test_folders,", "matrix with a specified figure number and a grayscale colormap # largeNameA =", "= save['valid_labels'] test_dataset = save['test_dataset'] test_labels = save['test_labels'] return train_dataset, train_labels, valid_dataset, valid_labels,", "as f: return pickle.load(f) # Display a random matrix with a specified figure", "= 'notMNIST_sanit.pickle' if not os.path.exists(sanit_pickle_file): filtered_valid_dataset, filtered_valid_labels, train_valid_same, train_valid_similar = \\ sanitize_dataset(valid_dataset, valid_labels,", "# let's shuffle the letters to have random validation and training set np.random.shuffle(letter_set)" ]
[ "Pololu protocol: 0xAA, device number, 0x33; Reference \"Get Error Flags Halting\" page 34", "time.sleep (cycle_delay) ser.write([init_cmd, jrk_id, read_current_cmd]) time.sleep (0.01) checkCurrent = ord(ser.read()) ser.write([init_cmd, jrk_id, read_feedback_cmd])", "= \"\\xA7\" get_error_cmd = \"\\x33\" # For my John Deere tractor steering: 2400", "left # clear error bits and read the register; Pololu protocol: 0xAA, device", "5) & ord(\"\\x7F\") ser.write([init_cmd, jrk_id, lowByte, highByte]) time.sleep (0.01) for i in range(1,", "scroll #stdout.flush() # used with the statement above target_delta = abs(target-scaled_feedback) print (\"", "used with the statement above target_delta = abs(target-scaled_feedback) print (\" target: %s feedback:", "print(\"connected to: \" + ser.portstr + \" for sending commands to JRK\") init_cmd", "ser.write([init_cmd, jrk_id, get_error_cmd]) time.sleep(0.1) cycle_delay = .1 for target in [2048, 4094, 1024,", "read_current_cmd = \"\\x8F\" read_scaled_feedback = \"\\xA7\" get_error_cmd = \"\\x33\" # For my John", "stdout print(\"starting jrk_simple_test\") ser = serial.Serial( \"/dev/ttyACM0\", 9600) # input to the JRK", "# For my John Deere tractor steering: 2400 full right; 1450 straight; 450", "is at %s of 4095, interation %s\" % (target, checkFeedback, i)) # use", "from sys import stdout print(\"starting jrk_simple_test\") ser = serial.Serial( \"/dev/ttyACM0\", 9600) # input", "# use this if you don't want the values to scroll #stdout.flush() #", "init_cmd = \"\\xAA\" jrk_id = \"\\x0B\" set_target_cmd = \"\\xC0\" stop_cmd = \"\\xFF\" read_feedback_cmd", "full left # clear error bits and read the register; Pololu protocol: 0xAA,", "up\") ser.write([init_cmd, jrk_id, get_error_cmd]) time.sleep(0.1) cycle_delay = .1 for target in [2048, 4094,", "\"\\xAA\" jrk_id = \"\\x0B\" set_target_cmd = \"\\xC0\" stop_cmd = \"\\xFF\" read_feedback_cmd = \"\\xA5\"", "(0.01) for i in range(1, 30): time.sleep (cycle_delay) ser.write([init_cmd, jrk_id, read_current_cmd]) time.sleep (0.01)", "cycle_delay = .1 for target in [2048, 4094, 1024, 0]: lowByte = (target", "(target, checkFeedback, i)) # use this if you don't want the values to", "jrk_id = \"\\x0B\" set_target_cmd = \"\\xC0\" stop_cmd = \"\\xFF\" read_feedback_cmd = \"\\xA5\" read_current_cmd", "steering: 2400 full right; 1450 straight; 450 full left # clear error bits", "1450 straight; 450 full left # clear error bits and read the register;", "if you don't want the values to scroll #stdout.flush() # used with the", "jrk_id, get_error_cmd]) time.sleep(0.1) cycle_delay = .1 for target in [2048, 4094, 1024, 0]:", "errors on start up\") ser.write([init_cmd, jrk_id, get_error_cmd]) time.sleep(0.1) cycle_delay = .1 for target", "ord(\"\\x1F\")) | ord(set_target_cmd) highByte = (target >> 5) & ord(\"\\x7F\") ser.write([init_cmd, jrk_id, lowByte,", "for sending commands to JRK\") init_cmd = \"\\xAA\" jrk_id = \"\\x0B\" set_target_cmd =", "print (\" target: %s feedback: %s scaled feedback: %s current: %s delta: %s", "to the JRK controller for sending it commands print(\"connected to: \" + ser.portstr", "= \"\\xA5\" read_current_cmd = \"\\x8F\" read_scaled_feedback = \"\\xA7\" get_error_cmd = \"\\x33\" # For", "clear error bits and read the register; Pololu protocol: 0xAA, device number, 0x33;", "above target_delta = abs(target-scaled_feedback) print (\" target: %s feedback: %s scaled feedback: %s", "(\" target: %s feedback: %s scaled feedback: %s current: %s delta: %s interation", "tractor steering: 2400 full right; 1450 straight; 450 full left # clear error", "commands to JRK\") init_cmd = \"\\xAA\" jrk_id = \"\\x0B\" set_target_cmd = \"\\xC0\" stop_cmd", "30): time.sleep (cycle_delay) ser.write([init_cmd, jrk_id, read_current_cmd]) time.sleep (0.01) checkCurrent = ord(ser.read()) ser.write([init_cmd, jrk_id,", "the statement above target_delta = abs(target-scaled_feedback) print (\" target: %s feedback: %s scaled", "values to scroll #stdout.flush() # used with the statement above target_delta = abs(target-scaled_feedback)", "= (ord(ser.read()) | ord(ser.read())<<8) #stdout.write (\" \\r target: %s feedback is at %s", "feedback is at %s of 4095, interation %s\" % (target, checkFeedback, i)) #", "= \"\\x0B\" set_target_cmd = \"\\xC0\" stop_cmd = \"\\xFF\" read_feedback_cmd = \"\\xA5\" read_current_cmd =", "you don't want the values to scroll #stdout.flush() # used with the statement", "34 of manual print(\"Clearing errors on start up\") ser.write([init_cmd, jrk_id, get_error_cmd]) time.sleep(0.1) cycle_delay", "+ ser.portstr + \" for sending commands to JRK\") init_cmd = \"\\xAA\" jrk_id", "time.sleep (0.01) checkFeedback = (ord(ser.read()) | ord(ser.read())<<8) time.sleep (0.01) ser.write([init_cmd, jrk_id, read_scaled_feedback]) time.sleep", "delta: %s interation %s\" % (target, checkFeedback, scaled_feedback, checkCurrent, target_delta, i)) ser.write(stop_cmd) print", "of manual print(\"Clearing errors on start up\") ser.write([init_cmd, jrk_id, get_error_cmd]) time.sleep(0.1) cycle_delay =", "%s current: %s delta: %s interation %s\" % (target, checkFeedback, scaled_feedback, checkCurrent, target_delta,", "= .1 for target in [2048, 4094, 1024, 0]: lowByte = (target &", "2400 full right; 1450 straight; 450 full left # clear error bits and", "use this if you don't want the values to scroll #stdout.flush() # used", "controller for sending it commands print(\"connected to: \" + ser.portstr + \" for", "\"\\x0B\" set_target_cmd = \"\\xC0\" stop_cmd = \"\\xFF\" read_feedback_cmd = \"\\xA5\" read_current_cmd = \"\\x8F\"", "read_scaled_feedback = \"\\xA7\" get_error_cmd = \"\\x33\" # For my John Deere tractor steering:", "Reference \"Get Error Flags Halting\" page 34 of manual print(\"Clearing errors on start", "jrk_id, read_current_cmd]) time.sleep (0.01) checkCurrent = ord(ser.read()) ser.write([init_cmd, jrk_id, read_feedback_cmd]) time.sleep (0.01) checkFeedback", "ser.write([init_cmd, jrk_id, read_feedback_cmd]) time.sleep (0.01) checkFeedback = (ord(ser.read()) | ord(ser.read())<<8) time.sleep (0.01) ser.write([init_cmd,", "feedback: %s scaled feedback: %s current: %s delta: %s interation %s\" % (target,", "device number, 0x33; Reference \"Get Error Flags Halting\" page 34 of manual print(\"Clearing", "(ord(ser.read()) | ord(ser.read())<<8) time.sleep (0.01) ser.write([init_cmd, jrk_id, read_scaled_feedback]) time.sleep (0.01) scaled_feedback = (ord(ser.read())", "Deere tractor steering: 2400 full right; 1450 straight; 450 full left # clear", "ser.write([init_cmd, jrk_id, read_scaled_feedback]) time.sleep (0.01) scaled_feedback = (ord(ser.read()) | ord(ser.read())<<8) #stdout.write (\" \\r", "sending it commands print(\"connected to: \" + ser.portstr + \" for sending commands", ">> 5) & ord(\"\\x7F\") ser.write([init_cmd, jrk_id, lowByte, highByte]) time.sleep (0.01) for i in", "straight; 450 full left # clear error bits and read the register; Pololu", "JRK\") init_cmd = \"\\xAA\" jrk_id = \"\\x0B\" set_target_cmd = \"\\xC0\" stop_cmd = \"\\xFF\"", "ord(set_target_cmd) highByte = (target >> 5) & ord(\"\\x7F\") ser.write([init_cmd, jrk_id, lowByte, highByte]) time.sleep", "= abs(target-scaled_feedback) print (\" target: %s feedback: %s scaled feedback: %s current: %s", "range(1, 30): time.sleep (cycle_delay) ser.write([init_cmd, jrk_id, read_current_cmd]) time.sleep (0.01) checkCurrent = ord(ser.read()) ser.write([init_cmd,", "jrk_id, read_feedback_cmd]) time.sleep (0.01) checkFeedback = (ord(ser.read()) | ord(ser.read())<<8) time.sleep (0.01) ser.write([init_cmd, jrk_id,", "= \"\\x8F\" read_scaled_feedback = \"\\xA7\" get_error_cmd = \"\\x33\" # For my John Deere", "get_error_cmd = \"\\x33\" # For my John Deere tractor steering: 2400 full right;", "my John Deere tractor steering: 2400 full right; 1450 straight; 450 full left", "John Deere tractor steering: 2400 full right; 1450 straight; 450 full left #", "+ \" for sending commands to JRK\") init_cmd = \"\\xAA\" jrk_id = \"\\x0B\"", "0x33; Reference \"Get Error Flags Halting\" page 34 of manual print(\"Clearing errors on", "= \"\\x33\" # For my John Deere tractor steering: 2400 full right; 1450", "import serial import time from sys import stdout print(\"starting jrk_simple_test\") ser = serial.Serial(", "target in [2048, 4094, 1024, 0]: lowByte = (target & ord(\"\\x1F\")) | ord(set_target_cmd)", "time from sys import stdout print(\"starting jrk_simple_test\") ser = serial.Serial( \"/dev/ttyACM0\", 9600) #", "interation %s\" % (target, checkFeedback, i)) # use this if you don't want", "[2048, 4094, 1024, 0]: lowByte = (target & ord(\"\\x1F\")) | ord(set_target_cmd) highByte =", "= (target & ord(\"\\x1F\")) | ord(set_target_cmd) highByte = (target >> 5) & ord(\"\\x7F\")", "\\r target: %s feedback is at %s of 4095, interation %s\" % (target,", "read_feedback_cmd]) time.sleep (0.01) checkFeedback = (ord(ser.read()) | ord(ser.read())<<8) time.sleep (0.01) ser.write([init_cmd, jrk_id, read_scaled_feedback])", "time.sleep (0.01) checkCurrent = ord(ser.read()) ser.write([init_cmd, jrk_id, read_feedback_cmd]) time.sleep (0.01) checkFeedback = (ord(ser.read())", "i)) # use this if you don't want the values to scroll #stdout.flush()", "abs(target-scaled_feedback) print (\" target: %s feedback: %s scaled feedback: %s current: %s delta:", "commands print(\"connected to: \" + ser.portstr + \" for sending commands to JRK\")", "#stdout.flush() # used with the statement above target_delta = abs(target-scaled_feedback) print (\" target:", "read_feedback_cmd = \"\\xA5\" read_current_cmd = \"\\x8F\" read_scaled_feedback = \"\\xA7\" get_error_cmd = \"\\x33\" #", "\" + ser.portstr + \" for sending commands to JRK\") init_cmd = \"\\xAA\"", "& ord(\"\\x1F\")) | ord(set_target_cmd) highByte = (target >> 5) & ord(\"\\x7F\") ser.write([init_cmd, jrk_id,", ".1 for target in [2048, 4094, 1024, 0]: lowByte = (target & ord(\"\\x1F\"))", "interation %s\" % (target, checkFeedback, scaled_feedback, checkCurrent, target_delta, i)) ser.write(stop_cmd) print (\"- Finished.\")", "error bits and read the register; Pololu protocol: 0xAA, device number, 0x33; Reference", "450 full left # clear error bits and read the register; Pololu protocol:", "0xAA, device number, 0x33; Reference \"Get Error Flags Halting\" page 34 of manual", "= ord(ser.read()) ser.write([init_cmd, jrk_id, read_feedback_cmd]) time.sleep (0.01) checkFeedback = (ord(ser.read()) | ord(ser.read())<<8) time.sleep", "of 4095, interation %s\" % (target, checkFeedback, i)) # use this if you", "%s delta: %s interation %s\" % (target, checkFeedback, scaled_feedback, checkCurrent, target_delta, i)) ser.write(stop_cmd)", "= \"\\xAA\" jrk_id = \"\\x0B\" set_target_cmd = \"\\xC0\" stop_cmd = \"\\xFF\" read_feedback_cmd =", "ord(ser.read()) ser.write([init_cmd, jrk_id, read_feedback_cmd]) time.sleep (0.01) checkFeedback = (ord(ser.read()) | ord(ser.read())<<8) time.sleep (0.01)", "target_delta = abs(target-scaled_feedback) print (\" target: %s feedback: %s scaled feedback: %s current:", "%s interation %s\" % (target, checkFeedback, scaled_feedback, checkCurrent, target_delta, i)) ser.write(stop_cmd) print (\"-", "& ord(\"\\x7F\") ser.write([init_cmd, jrk_id, lowByte, highByte]) time.sleep (0.01) for i in range(1, 30):", "ser.write([init_cmd, jrk_id, read_current_cmd]) time.sleep (0.01) checkCurrent = ord(ser.read()) ser.write([init_cmd, jrk_id, read_feedback_cmd]) time.sleep (0.01)", "stop_cmd = \"\\xFF\" read_feedback_cmd = \"\\xA5\" read_current_cmd = \"\\x8F\" read_scaled_feedback = \"\\xA7\" get_error_cmd", "| ord(ser.read())<<8) time.sleep (0.01) ser.write([init_cmd, jrk_id, read_scaled_feedback]) time.sleep (0.01) scaled_feedback = (ord(ser.read()) |", "(0.01) checkCurrent = ord(ser.read()) ser.write([init_cmd, jrk_id, read_feedback_cmd]) time.sleep (0.01) checkFeedback = (ord(ser.read()) |", "checkFeedback = (ord(ser.read()) | ord(ser.read())<<8) time.sleep (0.01) ser.write([init_cmd, jrk_id, read_scaled_feedback]) time.sleep (0.01) scaled_feedback", "read_current_cmd]) time.sleep (0.01) checkCurrent = ord(ser.read()) ser.write([init_cmd, jrk_id, read_feedback_cmd]) time.sleep (0.01) checkFeedback =", "read_scaled_feedback]) time.sleep (0.01) scaled_feedback = (ord(ser.read()) | ord(ser.read())<<8) #stdout.write (\" \\r target: %s", "(0.01) ser.write([init_cmd, jrk_id, read_scaled_feedback]) time.sleep (0.01) scaled_feedback = (ord(ser.read()) | ord(ser.read())<<8) #stdout.write (\"", "jrk_simple_test\") ser = serial.Serial( \"/dev/ttyACM0\", 9600) # input to the JRK controller for", "print(\"Clearing errors on start up\") ser.write([init_cmd, jrk_id, get_error_cmd]) time.sleep(0.1) cycle_delay = .1 for", "ser.write([init_cmd, jrk_id, lowByte, highByte]) time.sleep (0.01) for i in range(1, 30): time.sleep (cycle_delay)", "for sending it commands print(\"connected to: \" + ser.portstr + \" for sending", "this if you don't want the values to scroll #stdout.flush() # used with", "JRK controller for sending it commands print(\"connected to: \" + ser.portstr + \"", "(target & ord(\"\\x1F\")) | ord(set_target_cmd) highByte = (target >> 5) & ord(\"\\x7F\") ser.write([init_cmd,", "the values to scroll #stdout.flush() # used with the statement above target_delta =", "ord(ser.read())<<8) #stdout.write (\" \\r target: %s feedback is at %s of 4095, interation", "current: %s delta: %s interation %s\" % (target, checkFeedback, scaled_feedback, checkCurrent, target_delta, i))", "i in range(1, 30): time.sleep (cycle_delay) ser.write([init_cmd, jrk_id, read_current_cmd]) time.sleep (0.01) checkCurrent =", "% (target, checkFeedback, i)) # use this if you don't want the values", "%s feedback: %s scaled feedback: %s current: %s delta: %s interation %s\" %", "target: %s feedback is at %s of 4095, interation %s\" % (target, checkFeedback,", "= \"\\xFF\" read_feedback_cmd = \"\\xA5\" read_current_cmd = \"\\x8F\" read_scaled_feedback = \"\\xA7\" get_error_cmd =", "(cycle_delay) ser.write([init_cmd, jrk_id, read_current_cmd]) time.sleep (0.01) checkCurrent = ord(ser.read()) ser.write([init_cmd, jrk_id, read_feedback_cmd]) time.sleep", "\"\\xFF\" read_feedback_cmd = \"\\xA5\" read_current_cmd = \"\\x8F\" read_scaled_feedback = \"\\xA7\" get_error_cmd = \"\\x33\"", "%s feedback is at %s of 4095, interation %s\" % (target, checkFeedback, i))", "ser = serial.Serial( \"/dev/ttyACM0\", 9600) # input to the JRK controller for sending", "start up\") ser.write([init_cmd, jrk_id, get_error_cmd]) time.sleep(0.1) cycle_delay = .1 for target in [2048,", "sending commands to JRK\") init_cmd = \"\\xAA\" jrk_id = \"\\x0B\" set_target_cmd = \"\\xC0\"", "\"\\x8F\" read_scaled_feedback = \"\\xA7\" get_error_cmd = \"\\x33\" # For my John Deere tractor", "time.sleep (0.01) scaled_feedback = (ord(ser.read()) | ord(ser.read())<<8) #stdout.write (\" \\r target: %s feedback", "#stdout.write (\" \\r target: %s feedback is at %s of 4095, interation %s\"", "= (target >> 5) & ord(\"\\x7F\") ser.write([init_cmd, jrk_id, lowByte, highByte]) time.sleep (0.01) for", "%s of 4095, interation %s\" % (target, checkFeedback, i)) # use this if", "\"\\xA5\" read_current_cmd = \"\\x8F\" read_scaled_feedback = \"\\xA7\" get_error_cmd = \"\\x33\" # For my", "don't want the values to scroll #stdout.flush() # used with the statement above", "register; Pololu protocol: 0xAA, device number, 0x33; Reference \"Get Error Flags Halting\" page", "highByte = (target >> 5) & ord(\"\\x7F\") ser.write([init_cmd, jrk_id, lowByte, highByte]) time.sleep (0.01)", "target: %s feedback: %s scaled feedback: %s current: %s delta: %s interation %s\"", "it commands print(\"connected to: \" + ser.portstr + \" for sending commands to", "Error Flags Halting\" page 34 of manual print(\"Clearing errors on start up\") ser.write([init_cmd,", "ser.portstr + \" for sending commands to JRK\") init_cmd = \"\\xAA\" jrk_id =", "(0.01) checkFeedback = (ord(ser.read()) | ord(ser.read())<<8) time.sleep (0.01) ser.write([init_cmd, jrk_id, read_scaled_feedback]) time.sleep (0.01)", "for target in [2048, 4094, 1024, 0]: lowByte = (target & ord(\"\\x1F\")) |", "sys import stdout print(\"starting jrk_simple_test\") ser = serial.Serial( \"/dev/ttyACM0\", 9600) # input to", "\"Get Error Flags Halting\" page 34 of manual print(\"Clearing errors on start up\")", "= \"\\xC0\" stop_cmd = \"\\xFF\" read_feedback_cmd = \"\\xA5\" read_current_cmd = \"\\x8F\" read_scaled_feedback =", "4094, 1024, 0]: lowByte = (target & ord(\"\\x1F\")) | ord(set_target_cmd) highByte = (target", "\"\\xA7\" get_error_cmd = \"\\x33\" # For my John Deere tractor steering: 2400 full", "protocol: 0xAA, device number, 0x33; Reference \"Get Error Flags Halting\" page 34 of", "import time from sys import stdout print(\"starting jrk_simple_test\") ser = serial.Serial( \"/dev/ttyACM0\", 9600)", "statement above target_delta = abs(target-scaled_feedback) print (\" target: %s feedback: %s scaled feedback:", "0]: lowByte = (target & ord(\"\\x1F\")) | ord(set_target_cmd) highByte = (target >> 5)", "for i in range(1, 30): time.sleep (cycle_delay) ser.write([init_cmd, jrk_id, read_current_cmd]) time.sleep (0.01) checkCurrent", "| ord(ser.read())<<8) #stdout.write (\" \\r target: %s feedback is at %s of 4095,", "# used with the statement above target_delta = abs(target-scaled_feedback) print (\" target: %s", "\"\\x33\" # For my John Deere tractor steering: 2400 full right; 1450 straight;", "import stdout print(\"starting jrk_simple_test\") ser = serial.Serial( \"/dev/ttyACM0\", 9600) # input to the", "checkCurrent = ord(ser.read()) ser.write([init_cmd, jrk_id, read_feedback_cmd]) time.sleep (0.01) checkFeedback = (ord(ser.read()) | ord(ser.read())<<8)", "ord(ser.read())<<8) time.sleep (0.01) ser.write([init_cmd, jrk_id, read_scaled_feedback]) time.sleep (0.01) scaled_feedback = (ord(ser.read()) | ord(ser.read())<<8)", "input to the JRK controller for sending it commands print(\"connected to: \" +", "python import serial import time from sys import stdout print(\"starting jrk_simple_test\") ser =", "manual print(\"Clearing errors on start up\") ser.write([init_cmd, jrk_id, get_error_cmd]) time.sleep(0.1) cycle_delay = .1", "scaled feedback: %s current: %s delta: %s interation %s\" % (target, checkFeedback, scaled_feedback,", "\"\\xC0\" stop_cmd = \"\\xFF\" read_feedback_cmd = \"\\xA5\" read_current_cmd = \"\\x8F\" read_scaled_feedback = \"\\xA7\"", "lowByte, highByte]) time.sleep (0.01) for i in range(1, 30): time.sleep (cycle_delay) ser.write([init_cmd, jrk_id,", "# clear error bits and read the register; Pololu protocol: 0xAA, device number,", "checkFeedback, i)) # use this if you don't want the values to scroll", "ord(\"\\x7F\") ser.write([init_cmd, jrk_id, lowByte, highByte]) time.sleep (0.01) for i in range(1, 30): time.sleep", "1024, 0]: lowByte = (target & ord(\"\\x1F\")) | ord(set_target_cmd) highByte = (target >>", "highByte]) time.sleep (0.01) for i in range(1, 30): time.sleep (cycle_delay) ser.write([init_cmd, jrk_id, read_current_cmd])", "right; 1450 straight; 450 full left # clear error bits and read the", "serial.Serial( \"/dev/ttyACM0\", 9600) # input to the JRK controller for sending it commands", "read the register; Pololu protocol: 0xAA, device number, 0x33; Reference \"Get Error Flags", "want the values to scroll #stdout.flush() # used with the statement above target_delta", "(target >> 5) & ord(\"\\x7F\") ser.write([init_cmd, jrk_id, lowByte, highByte]) time.sleep (0.01) for i", "\" for sending commands to JRK\") init_cmd = \"\\xAA\" jrk_id = \"\\x0B\" set_target_cmd", "print(\"starting jrk_simple_test\") ser = serial.Serial( \"/dev/ttyACM0\", 9600) # input to the JRK controller", "full right; 1450 straight; 450 full left # clear error bits and read", "to: \" + ser.portstr + \" for sending commands to JRK\") init_cmd =", "\"/dev/ttyACM0\", 9600) # input to the JRK controller for sending it commands print(\"connected", "| ord(set_target_cmd) highByte = (target >> 5) & ord(\"\\x7F\") ser.write([init_cmd, jrk_id, lowByte, highByte])", "the JRK controller for sending it commands print(\"connected to: \" + ser.portstr +", "jrk_id, lowByte, highByte]) time.sleep (0.01) for i in range(1, 30): time.sleep (cycle_delay) ser.write([init_cmd,", "number, 0x33; Reference \"Get Error Flags Halting\" page 34 of manual print(\"Clearing errors", "at %s of 4095, interation %s\" % (target, checkFeedback, i)) # use this", "the register; Pololu protocol: 0xAA, device number, 0x33; Reference \"Get Error Flags Halting\"", "set_target_cmd = \"\\xC0\" stop_cmd = \"\\xFF\" read_feedback_cmd = \"\\xA5\" read_current_cmd = \"\\x8F\" read_scaled_feedback", "to JRK\") init_cmd = \"\\xAA\" jrk_id = \"\\x0B\" set_target_cmd = \"\\xC0\" stop_cmd =", "lowByte = (target & ord(\"\\x1F\")) | ord(set_target_cmd) highByte = (target >> 5) &", "scaled_feedback = (ord(ser.read()) | ord(ser.read())<<8) #stdout.write (\" \\r target: %s feedback is at", "For my John Deere tractor steering: 2400 full right; 1450 straight; 450 full", "bits and read the register; Pololu protocol: 0xAA, device number, 0x33; Reference \"Get", "time.sleep (0.01) for i in range(1, 30): time.sleep (cycle_delay) ser.write([init_cmd, jrk_id, read_current_cmd]) time.sleep", "page 34 of manual print(\"Clearing errors on start up\") ser.write([init_cmd, jrk_id, get_error_cmd]) time.sleep(0.1)", "4095, interation %s\" % (target, checkFeedback, i)) # use this if you don't", "on start up\") ser.write([init_cmd, jrk_id, get_error_cmd]) time.sleep(0.1) cycle_delay = .1 for target in", "(ord(ser.read()) | ord(ser.read())<<8) #stdout.write (\" \\r target: %s feedback is at %s of", "in [2048, 4094, 1024, 0]: lowByte = (target & ord(\"\\x1F\")) | ord(set_target_cmd) highByte", "= (ord(ser.read()) | ord(ser.read())<<8) time.sleep (0.01) ser.write([init_cmd, jrk_id, read_scaled_feedback]) time.sleep (0.01) scaled_feedback =", "= serial.Serial( \"/dev/ttyACM0\", 9600) # input to the JRK controller for sending it", "(0.01) scaled_feedback = (ord(ser.read()) | ord(ser.read())<<8) #stdout.write (\" \\r target: %s feedback is", "%s\" % (target, checkFeedback, scaled_feedback, checkCurrent, target_delta, i)) ser.write(stop_cmd) print (\"- Finished.\") ser.write(stop_cmd)", "to scroll #stdout.flush() # used with the statement above target_delta = abs(target-scaled_feedback) print", "(\" \\r target: %s feedback is at %s of 4095, interation %s\" %", "Flags Halting\" page 34 of manual print(\"Clearing errors on start up\") ser.write([init_cmd, jrk_id,", "jrk_id, read_scaled_feedback]) time.sleep (0.01) scaled_feedback = (ord(ser.read()) | ord(ser.read())<<8) #stdout.write (\" \\r target:", "get_error_cmd]) time.sleep(0.1) cycle_delay = .1 for target in [2048, 4094, 1024, 0]: lowByte", "and read the register; Pololu protocol: 0xAA, device number, 0x33; Reference \"Get Error", "feedback: %s current: %s delta: %s interation %s\" % (target, checkFeedback, scaled_feedback, checkCurrent,", "serial import time from sys import stdout print(\"starting jrk_simple_test\") ser = serial.Serial( \"/dev/ttyACM0\",", "%s\" % (target, checkFeedback, i)) # use this if you don't want the", "time.sleep (0.01) ser.write([init_cmd, jrk_id, read_scaled_feedback]) time.sleep (0.01) scaled_feedback = (ord(ser.read()) | ord(ser.read())<<8) #stdout.write", "#!/usr/bin/env python import serial import time from sys import stdout print(\"starting jrk_simple_test\") ser", "in range(1, 30): time.sleep (cycle_delay) ser.write([init_cmd, jrk_id, read_current_cmd]) time.sleep (0.01) checkCurrent = ord(ser.read())", "%s scaled feedback: %s current: %s delta: %s interation %s\" % (target, checkFeedback,", "with the statement above target_delta = abs(target-scaled_feedback) print (\" target: %s feedback: %s", "Halting\" page 34 of manual print(\"Clearing errors on start up\") ser.write([init_cmd, jrk_id, get_error_cmd])", "# input to the JRK controller for sending it commands print(\"connected to: \"", "time.sleep(0.1) cycle_delay = .1 for target in [2048, 4094, 1024, 0]: lowByte =", "9600) # input to the JRK controller for sending it commands print(\"connected to:" ]
[ "for token in Filter.__iter__(self): if reached_max_length and nesting_level == 0: return if token['type']", "'\\n', description_cleaner.clean(txt) ).strip() ) class ProcessShortDescription(Filter): max_length = 200 def __iter__(self): current_length =", "Filter PARAGRAPH_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'li'] STYLE_TAGS = ['strong', 'em']", "unescape from bleach.sanitizer import Cleaner from html5lib.filters.base import Filter PARAGRAPH_TAGS = ['p', 'h1',", "0 for token in Filter.__iter__(self): if reached_max_length and nesting_level == 0: return if", "token in Filter.__iter__(self): if token['type'] == 'StartTag': continue if token['type'] in ['EndTag','EmptyTag']: token", "from bleach.sanitizer import Cleaner from html5lib.filters.base import Filter PARAGRAPH_TAGS = ['p', 'h1', 'h2',", "def __iter__(self): for token in Filter.__iter__(self): if token['type'] == 'StartTag': continue if token['type']", "+ ['br'], filters = [ProcessDescription], strip = True ) newline_re = re.compile('\\n{2,}') def", "-*- coding: utf-8 -*- import re from html import unescape from bleach.sanitizer import", "def process_description(txt): return unescape( newline_re.sub( '\\n', description_cleaner.clean(txt) ).strip() ) class ProcessShortDescription(Filter): max_length =", "if reached_max_length: continue total_length = current_length + len(token['data']) if total_length > self.max_length: reached_max_length", "yield token short_description_cleaner = Cleaner( tags = PARAGRAPH_TAGS + STYLE_TAGS, filters = [ProcessShortDescription],", "import Cleaner from html5lib.filters.base import Filter PARAGRAPH_TAGS = ['p', 'h1', 'h2', 'h3', 'h4',", "'p' if token['type'] == 'EndTag': nesting_level -= 1 if token['type'] == 'StartTag': nesting_level", "yield token description_cleaner = Cleaner( tags = PARAGRAPH_TAGS + ['br'], filters = [ProcessDescription],", "+ STYLE_TAGS, filters = [ProcessShortDescription], strip = True ) def process_short_description(txt): return short_description_cleaner.clean(txt)", "'SpaceCharacters']: if reached_max_length: continue total_length = current_length + len(token['data']) if total_length > self.max_length:", "= total_length yield token short_description_cleaner = Cleaner( tags = PARAGRAPH_TAGS + STYLE_TAGS, filters", "STYLE_TAGS = ['strong', 'em'] class ProcessDescription(Filter): def __iter__(self): for token in Filter.__iter__(self): if", "token short_description_cleaner = Cleaner( tags = PARAGRAPH_TAGS + STYLE_TAGS, filters = [ProcessShortDescription], strip", "PARAGRAPH_TAGS + STYLE_TAGS, filters = [ProcessShortDescription], strip = True ) def process_short_description(txt): return", "token = {'type': 'Characters', 'data': '\\n'} yield token description_cleaner = Cleaner( tags =", "strip = True ) newline_re = re.compile('\\n{2,}') def process_description(txt): return unescape( newline_re.sub( '\\n',", "= Cleaner( tags = PARAGRAPH_TAGS + STYLE_TAGS, filters = [ProcessShortDescription], strip = True", "= {'type': 'Characters', 'data': '\\n'} yield token description_cleaner = Cleaner( tags = PARAGRAPH_TAGS", "def __iter__(self): current_length = 0 reached_max_length = False nesting_level = 0 for token", "== 'StartTag': nesting_level += 1 if token['type'] in ['Characters', 'SpaceCharacters']: if reached_max_length: continue", "['strong', 'em'] class ProcessDescription(Filter): def __iter__(self): for token in Filter.__iter__(self): if token['type'] ==", "token['name'] in PARAGRAPH_TAGS: token['name'] = 'p' if token['type'] == 'EndTag': nesting_level -= 1", "tags = PARAGRAPH_TAGS + ['br'], filters = [ProcessDescription], strip = True ) newline_re", "token['type'] in ['EndTag','EmptyTag']: token = {'type': 'Characters', 'data': '\\n'} yield token description_cleaner =", "'em'] class ProcessDescription(Filter): def __iter__(self): for token in Filter.__iter__(self): if token['type'] == 'StartTag':", "token['name'] = 'p' if token['type'] == 'EndTag': nesting_level -= 1 if token['type'] ==", ").strip() ) class ProcessShortDescription(Filter): max_length = 200 def __iter__(self): current_length = 0 reached_max_length", "= True ) newline_re = re.compile('\\n{2,}') def process_description(txt): return unescape( newline_re.sub( '\\n', description_cleaner.clean(txt)", "['br'], filters = [ProcessDescription], strip = True ) newline_re = re.compile('\\n{2,}') def process_description(txt):", "total_length > self.max_length: reached_max_length = True token['data'] = token['data'][:self.max_length-current_length] + '...' token['type'] =", "Filter.__iter__(self): if reached_max_length and nesting_level == 0: return if token['type'] in ['StartTag','EndTag'] and", "+ len(token['data']) if total_length > self.max_length: reached_max_length = True token['data'] = token['data'][:self.max_length-current_length] +", "total_length yield token short_description_cleaner = Cleaner( tags = PARAGRAPH_TAGS + STYLE_TAGS, filters =", ") newline_re = re.compile('\\n{2,}') def process_description(txt): return unescape( newline_re.sub( '\\n', description_cleaner.clean(txt) ).strip() )", ") class ProcessShortDescription(Filter): max_length = 200 def __iter__(self): current_length = 0 reached_max_length =", "= ['strong', 'em'] class ProcessDescription(Filter): def __iter__(self): for token in Filter.__iter__(self): if token['type']", "['Characters', 'SpaceCharacters']: if reached_max_length: continue total_length = current_length + len(token['data']) if total_length >", "= Cleaner( tags = PARAGRAPH_TAGS + ['br'], filters = [ProcessDescription], strip = True", "= True token['data'] = token['data'][:self.max_length-current_length] + '...' token['type'] = 'Characters' current_length = total_length", "+ '...' token['type'] = 'Characters' current_length = total_length yield token short_description_cleaner = Cleaner(", "self.max_length: reached_max_length = True token['data'] = token['data'][:self.max_length-current_length] + '...' token['type'] = 'Characters' current_length", "if token['type'] == 'StartTag': continue if token['type'] in ['EndTag','EmptyTag']: token = {'type': 'Characters',", "Filter.__iter__(self): if token['type'] == 'StartTag': continue if token['type'] in ['EndTag','EmptyTag']: token = {'type':", "tags = PARAGRAPH_TAGS + STYLE_TAGS, filters = [ProcessShortDescription], strip = True ) def", "description_cleaner = Cleaner( tags = PARAGRAPH_TAGS + ['br'], filters = [ProcessDescription], strip =", "reached_max_length = False nesting_level = 0 for token in Filter.__iter__(self): if reached_max_length and", "import Filter PARAGRAPH_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'li'] STYLE_TAGS = ['strong',", "if total_length > self.max_length: reached_max_length = True token['data'] = token['data'][:self.max_length-current_length] + '...' token['type']", "description_cleaner.clean(txt) ).strip() ) class ProcessShortDescription(Filter): max_length = 200 def __iter__(self): current_length = 0", "'StartTag': nesting_level += 1 if token['type'] in ['Characters', 'SpaceCharacters']: if reached_max_length: continue total_length", "'li'] STYLE_TAGS = ['strong', 'em'] class ProcessDescription(Filter): def __iter__(self): for token in Filter.__iter__(self):", "= token['data'][:self.max_length-current_length] + '...' token['type'] = 'Characters' current_length = total_length yield token short_description_cleaner", "== 'EndTag': nesting_level -= 1 if token['type'] == 'StartTag': nesting_level += 1 if", "+= 1 if token['type'] in ['Characters', 'SpaceCharacters']: if reached_max_length: continue total_length = current_length", "unescape( newline_re.sub( '\\n', description_cleaner.clean(txt) ).strip() ) class ProcessShortDescription(Filter): max_length = 200 def __iter__(self):", "True token['data'] = token['data'][:self.max_length-current_length] + '...' token['type'] = 'Characters' current_length = total_length yield", "if token['type'] == 'EndTag': nesting_level -= 1 if token['type'] == 'StartTag': nesting_level +=", "token['type'] == 'StartTag': continue if token['type'] in ['EndTag','EmptyTag']: token = {'type': 'Characters', 'data':", "and token['name'] in PARAGRAPH_TAGS: token['name'] = 'p' if token['type'] == 'EndTag': nesting_level -=", "False nesting_level = 0 for token in Filter.__iter__(self): if reached_max_length and nesting_level ==", "Cleaner( tags = PARAGRAPH_TAGS + STYLE_TAGS, filters = [ProcessShortDescription], strip = True )", "'h2', 'h3', 'h4', 'li'] STYLE_TAGS = ['strong', 'em'] class ProcessDescription(Filter): def __iter__(self): for", "return if token['type'] in ['StartTag','EndTag'] and token['name'] in PARAGRAPH_TAGS: token['name'] = 'p' if", "0 reached_max_length = False nesting_level = 0 for token in Filter.__iter__(self): if reached_max_length", "PARAGRAPH_TAGS: token['name'] = 'p' if token['type'] == 'EndTag': nesting_level -= 1 if token['type']", "= PARAGRAPH_TAGS + ['br'], filters = [ProcessDescription], strip = True ) newline_re =", "True ) newline_re = re.compile('\\n{2,}') def process_description(txt): return unescape( newline_re.sub( '\\n', description_cleaner.clean(txt) ).strip()", "ProcessDescription(Filter): def __iter__(self): for token in Filter.__iter__(self): if token['type'] == 'StartTag': continue if", "[ProcessDescription], strip = True ) newline_re = re.compile('\\n{2,}') def process_description(txt): return unescape( newline_re.sub(", "nesting_level -= 1 if token['type'] == 'StartTag': nesting_level += 1 if token['type'] in", "for token in Filter.__iter__(self): if token['type'] == 'StartTag': continue if token['type'] in ['EndTag','EmptyTag']:", "reached_max_length = True token['data'] = token['data'][:self.max_length-current_length] + '...' token['type'] = 'Characters' current_length =", "> self.max_length: reached_max_length = True token['data'] = token['data'][:self.max_length-current_length] + '...' token['type'] = 'Characters'", "# -*- coding: utf-8 -*- import re from html import unescape from bleach.sanitizer", "in ['StartTag','EndTag'] and token['name'] in PARAGRAPH_TAGS: token['name'] = 'p' if token['type'] == 'EndTag':", "-= 1 if token['type'] == 'StartTag': nesting_level += 1 if token['type'] in ['Characters',", "__iter__(self): for token in Filter.__iter__(self): if token['type'] == 'StartTag': continue if token['type'] in", "token['type'] in ['Characters', 'SpaceCharacters']: if reached_max_length: continue total_length = current_length + len(token['data']) if", "'h4', 'li'] STYLE_TAGS = ['strong', 'em'] class ProcessDescription(Filter): def __iter__(self): for token in", "0: return if token['type'] in ['StartTag','EndTag'] and token['name'] in PARAGRAPH_TAGS: token['name'] = 'p'", "import unescape from bleach.sanitizer import Cleaner from html5lib.filters.base import Filter PARAGRAPH_TAGS = ['p',", "current_length = total_length yield token short_description_cleaner = Cleaner( tags = PARAGRAPH_TAGS + STYLE_TAGS,", "class ProcessShortDescription(Filter): max_length = 200 def __iter__(self): current_length = 0 reached_max_length = False", "'Characters', 'data': '\\n'} yield token description_cleaner = Cleaner( tags = PARAGRAPH_TAGS + ['br'],", "'\\n'} yield token description_cleaner = Cleaner( tags = PARAGRAPH_TAGS + ['br'], filters =", "class ProcessDescription(Filter): def __iter__(self): for token in Filter.__iter__(self): if token['type'] == 'StartTag': continue", "<filename>src/cardapp/utils.py # -*- coding: utf-8 -*- import re from html import unescape from", "token['type'] == 'StartTag': nesting_level += 1 if token['type'] in ['Characters', 'SpaceCharacters']: if reached_max_length:", "'h1', 'h2', 'h3', 'h4', 'li'] STYLE_TAGS = ['strong', 'em'] class ProcessDescription(Filter): def __iter__(self):", "return unescape( newline_re.sub( '\\n', description_cleaner.clean(txt) ).strip() ) class ProcessShortDescription(Filter): max_length = 200 def", "current_length = 0 reached_max_length = False nesting_level = 0 for token in Filter.__iter__(self):", "in Filter.__iter__(self): if reached_max_length and nesting_level == 0: return if token['type'] in ['StartTag','EndTag']", "'...' token['type'] = 'Characters' current_length = total_length yield token short_description_cleaner = Cleaner( tags", "utf-8 -*- import re from html import unescape from bleach.sanitizer import Cleaner from", "token description_cleaner = Cleaner( tags = PARAGRAPH_TAGS + ['br'], filters = [ProcessDescription], strip", "total_length = current_length + len(token['data']) if total_length > self.max_length: reached_max_length = True token['data']", "in PARAGRAPH_TAGS: token['name'] = 'p' if token['type'] == 'EndTag': nesting_level -= 1 if", "current_length + len(token['data']) if total_length > self.max_length: reached_max_length = True token['data'] = token['data'][:self.max_length-current_length]", "['p', 'h1', 'h2', 'h3', 'h4', 'li'] STYLE_TAGS = ['strong', 'em'] class ProcessDescription(Filter): def", "= 0 for token in Filter.__iter__(self): if reached_max_length and nesting_level == 0: return", "len(token['data']) if total_length > self.max_length: reached_max_length = True token['data'] = token['data'][:self.max_length-current_length] + '...'", "bleach.sanitizer import Cleaner from html5lib.filters.base import Filter PARAGRAPH_TAGS = ['p', 'h1', 'h2', 'h3',", "1 if token['type'] == 'StartTag': nesting_level += 1 if token['type'] in ['Characters', 'SpaceCharacters']:", "= 200 def __iter__(self): current_length = 0 reached_max_length = False nesting_level = 0", "reached_max_length and nesting_level == 0: return if token['type'] in ['StartTag','EndTag'] and token['name'] in", "continue if token['type'] in ['EndTag','EmptyTag']: token = {'type': 'Characters', 'data': '\\n'} yield token", "newline_re = re.compile('\\n{2,}') def process_description(txt): return unescape( newline_re.sub( '\\n', description_cleaner.clean(txt) ).strip() ) class", "'EndTag': nesting_level -= 1 if token['type'] == 'StartTag': nesting_level += 1 if token['type']", "token in Filter.__iter__(self): if reached_max_length and nesting_level == 0: return if token['type'] in", "token['type'] == 'EndTag': nesting_level -= 1 if token['type'] == 'StartTag': nesting_level += 1", "in ['Characters', 'SpaceCharacters']: if reached_max_length: continue total_length = current_length + len(token['data']) if total_length", "in Filter.__iter__(self): if token['type'] == 'StartTag': continue if token['type'] in ['EndTag','EmptyTag']: token =", "['EndTag','EmptyTag']: token = {'type': 'Characters', 'data': '\\n'} yield token description_cleaner = Cleaner( tags", "newline_re.sub( '\\n', description_cleaner.clean(txt) ).strip() ) class ProcessShortDescription(Filter): max_length = 200 def __iter__(self): current_length", "= re.compile('\\n{2,}') def process_description(txt): return unescape( newline_re.sub( '\\n', description_cleaner.clean(txt) ).strip() ) class ProcessShortDescription(Filter):", "max_length = 200 def __iter__(self): current_length = 0 reached_max_length = False nesting_level =", "if token['type'] == 'StartTag': nesting_level += 1 if token['type'] in ['Characters', 'SpaceCharacters']: if", "== 0: return if token['type'] in ['StartTag','EndTag'] and token['name'] in PARAGRAPH_TAGS: token['name'] =", "token['type'] in ['StartTag','EndTag'] and token['name'] in PARAGRAPH_TAGS: token['name'] = 'p' if token['type'] ==", "= 'Characters' current_length = total_length yield token short_description_cleaner = Cleaner( tags = PARAGRAPH_TAGS", "re from html import unescape from bleach.sanitizer import Cleaner from html5lib.filters.base import Filter", "import re from html import unescape from bleach.sanitizer import Cleaner from html5lib.filters.base import", "PARAGRAPH_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'li'] STYLE_TAGS = ['strong', 'em'] class", "= ['p', 'h1', 'h2', 'h3', 'h4', 'li'] STYLE_TAGS = ['strong', 'em'] class ProcessDescription(Filter):", "ProcessShortDescription(Filter): max_length = 200 def __iter__(self): current_length = 0 reached_max_length = False nesting_level", "'Characters' current_length = total_length yield token short_description_cleaner = Cleaner( tags = PARAGRAPH_TAGS +", "nesting_level = 0 for token in Filter.__iter__(self): if reached_max_length and nesting_level == 0:", "'StartTag': continue if token['type'] in ['EndTag','EmptyTag']: token = {'type': 'Characters', 'data': '\\n'} yield", "html import unescape from bleach.sanitizer import Cleaner from html5lib.filters.base import Filter PARAGRAPH_TAGS =", "in ['EndTag','EmptyTag']: token = {'type': 'Characters', 'data': '\\n'} yield token description_cleaner = Cleaner(", "= 'p' if token['type'] == 'EndTag': nesting_level -= 1 if token['type'] == 'StartTag':", "if token['type'] in ['StartTag','EndTag'] and token['name'] in PARAGRAPH_TAGS: token['name'] = 'p' if token['type']", "continue total_length = current_length + len(token['data']) if total_length > self.max_length: reached_max_length = True", "token['data'][:self.max_length-current_length] + '...' token['type'] = 'Characters' current_length = total_length yield token short_description_cleaner =", "'data': '\\n'} yield token description_cleaner = Cleaner( tags = PARAGRAPH_TAGS + ['br'], filters", "= False nesting_level = 0 for token in Filter.__iter__(self): if reached_max_length and nesting_level", "1 if token['type'] in ['Characters', 'SpaceCharacters']: if reached_max_length: continue total_length = current_length +", "if token['type'] in ['Characters', 'SpaceCharacters']: if reached_max_length: continue total_length = current_length + len(token['data'])", "Cleaner from html5lib.filters.base import Filter PARAGRAPH_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'li']", "from html import unescape from bleach.sanitizer import Cleaner from html5lib.filters.base import Filter PARAGRAPH_TAGS", "= 0 reached_max_length = False nesting_level = 0 for token in Filter.__iter__(self): if", "if reached_max_length and nesting_level == 0: return if token['type'] in ['StartTag','EndTag'] and token['name']", "nesting_level == 0: return if token['type'] in ['StartTag','EndTag'] and token['name'] in PARAGRAPH_TAGS: token['name']", "if token['type'] in ['EndTag','EmptyTag']: token = {'type': 'Characters', 'data': '\\n'} yield token description_cleaner", "nesting_level += 1 if token['type'] in ['Characters', 'SpaceCharacters']: if reached_max_length: continue total_length =", "= [ProcessDescription], strip = True ) newline_re = re.compile('\\n{2,}') def process_description(txt): return unescape(", "'h3', 'h4', 'li'] STYLE_TAGS = ['strong', 'em'] class ProcessDescription(Filter): def __iter__(self): for token", "['StartTag','EndTag'] and token['name'] in PARAGRAPH_TAGS: token['name'] = 'p' if token['type'] == 'EndTag': nesting_level", "process_description(txt): return unescape( newline_re.sub( '\\n', description_cleaner.clean(txt) ).strip() ) class ProcessShortDescription(Filter): max_length = 200", "-*- import re from html import unescape from bleach.sanitizer import Cleaner from html5lib.filters.base", "re.compile('\\n{2,}') def process_description(txt): return unescape( newline_re.sub( '\\n', description_cleaner.clean(txt) ).strip() ) class ProcessShortDescription(Filter): max_length", "coding: utf-8 -*- import re from html import unescape from bleach.sanitizer import Cleaner", "Cleaner( tags = PARAGRAPH_TAGS + ['br'], filters = [ProcessDescription], strip = True )", "reached_max_length: continue total_length = current_length + len(token['data']) if total_length > self.max_length: reached_max_length =", "== 'StartTag': continue if token['type'] in ['EndTag','EmptyTag']: token = {'type': 'Characters', 'data': '\\n'}", "short_description_cleaner = Cleaner( tags = PARAGRAPH_TAGS + STYLE_TAGS, filters = [ProcessShortDescription], strip =", "html5lib.filters.base import Filter PARAGRAPH_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'li'] STYLE_TAGS =", "PARAGRAPH_TAGS + ['br'], filters = [ProcessDescription], strip = True ) newline_re = re.compile('\\n{2,}')", "and nesting_level == 0: return if token['type'] in ['StartTag','EndTag'] and token['name'] in PARAGRAPH_TAGS:", "token['data'] = token['data'][:self.max_length-current_length] + '...' token['type'] = 'Characters' current_length = total_length yield token", "from html5lib.filters.base import Filter PARAGRAPH_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'li'] STYLE_TAGS", "200 def __iter__(self): current_length = 0 reached_max_length = False nesting_level = 0 for", "__iter__(self): current_length = 0 reached_max_length = False nesting_level = 0 for token in", "= PARAGRAPH_TAGS + STYLE_TAGS, filters = [ProcessShortDescription], strip = True ) def process_short_description(txt):", "{'type': 'Characters', 'data': '\\n'} yield token description_cleaner = Cleaner( tags = PARAGRAPH_TAGS +", "filters = [ProcessDescription], strip = True ) newline_re = re.compile('\\n{2,}') def process_description(txt): return", "token['type'] = 'Characters' current_length = total_length yield token short_description_cleaner = Cleaner( tags =", "= current_length + len(token['data']) if total_length > self.max_length: reached_max_length = True token['data'] =" ]
[ "42 @classmethod def nome_e_atributo_de_clsse(cls): return f\"{cls} olhos {cls.olhos}\" if __name__ == \"__main__\": joao", "class Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=10): self.nome = nome", "joao = Pessoa(nome='João') pedro = Pessoa(joao,nome='Pedro') print(Pessoa.cumprimentar(pedro)) print(id(joao)) for filho in pedro.filhos: print(filho.nome)", "= nome self.idade = idade self.filhos = list(filhos) def cumprimentar(self): return f\"olá {self.nome}", "Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=10): self.nome = nome self.idade", "olhos {cls.olhos}\" if __name__ == \"__main__\": joao = Pessoa(nome='João') pedro = Pessoa(joao,nome='Pedro') print(Pessoa.cumprimentar(pedro))", "print(Pessoa.cumprimentar(pedro)) print(id(joao)) for filho in pedro.filhos: print(filho.nome) joao.sobrenome = \"Silva\" del pedro.filhos joao.olhos", "self.nome = nome self.idade = idade self.filhos = list(filhos) def cumprimentar(self): return f\"olá", "id({id(self)})\" @staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributo_de_clsse(cls): return f\"{cls} olhos {cls.olhos}\"", "= 2 def __init__(self, *filhos, nome=None, idade=10): self.nome = nome self.idade = idade", "nome_e_atributo_de_clsse(cls): return f\"{cls} olhos {cls.olhos}\" if __name__ == \"__main__\": joao = Pessoa(nome='João') pedro", "if __name__ == \"__main__\": joao = Pessoa(nome='João') pedro = Pessoa(joao,nome='Pedro') print(Pessoa.cumprimentar(pedro)) print(id(joao)) for", "= 1 Pessoa.olhos = 3 print(joao.__dict__) print(pedro.__dict__) print(Pessoa.olhos) print(joao.olhos) print(pedro.olhos) print(id(Pessoa.olhos),id(joao.olhos),id(pedro.olhos)) print(Pessoa.metodo_estatico(),joao.metodo_estatico()) print(Pessoa.nome_e_atributo_de_clsse(),joao.nome_e_atributo_de_clsse())", "__init__(self, *filhos, nome=None, idade=10): self.nome = nome self.idade = idade self.filhos = list(filhos)", "return 42 @classmethod def nome_e_atributo_de_clsse(cls): return f\"{cls} olhos {cls.olhos}\" if __name__ == \"__main__\":", "pedro = Pessoa(joao,nome='Pedro') print(Pessoa.cumprimentar(pedro)) print(id(joao)) for filho in pedro.filhos: print(filho.nome) joao.sobrenome = \"Silva\"", "cumprimentar(self): return f\"olá {self.nome} id({id(self)})\" @staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributo_de_clsse(cls):", "{self.nome} id({id(self)})\" @staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributo_de_clsse(cls): return f\"{cls} olhos", "f\"olá {self.nome} id({id(self)})\" @staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributo_de_clsse(cls): return f\"{cls}", "Pessoa(joao,nome='Pedro') print(Pessoa.cumprimentar(pedro)) print(id(joao)) for filho in pedro.filhos: print(filho.nome) joao.sobrenome = \"Silva\" del pedro.filhos", "for filho in pedro.filhos: print(filho.nome) joao.sobrenome = \"Silva\" del pedro.filhos joao.olhos = 1", "joao.sobrenome = \"Silva\" del pedro.filhos joao.olhos = 1 Pessoa.olhos = 3 print(joao.__dict__) print(pedro.__dict__)", "\"Silva\" del pedro.filhos joao.olhos = 1 Pessoa.olhos = 3 print(joao.__dict__) print(pedro.__dict__) print(Pessoa.olhos) print(joao.olhos)", "@staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributo_de_clsse(cls): return f\"{cls} olhos {cls.olhos}\" if", "def __init__(self, *filhos, nome=None, idade=10): self.nome = nome self.idade = idade self.filhos =", "def metodo_estatico(): return 42 @classmethod def nome_e_atributo_de_clsse(cls): return f\"{cls} olhos {cls.olhos}\" if __name__", "2 def __init__(self, *filhos, nome=None, idade=10): self.nome = nome self.idade = idade self.filhos", "== \"__main__\": joao = Pessoa(nome='João') pedro = Pessoa(joao,nome='Pedro') print(Pessoa.cumprimentar(pedro)) print(id(joao)) for filho in", "idade=10): self.nome = nome self.idade = idade self.filhos = list(filhos) def cumprimentar(self): return", "idade self.filhos = list(filhos) def cumprimentar(self): return f\"olá {self.nome} id({id(self)})\" @staticmethod def metodo_estatico():", "nome self.idade = idade self.filhos = list(filhos) def cumprimentar(self): return f\"olá {self.nome} id({id(self)})\"", "{cls.olhos}\" if __name__ == \"__main__\": joao = Pessoa(nome='João') pedro = Pessoa(joao,nome='Pedro') print(Pessoa.cumprimentar(pedro)) print(id(joao))", "joao.olhos = 1 Pessoa.olhos = 3 print(joao.__dict__) print(pedro.__dict__) print(Pessoa.olhos) print(joao.olhos) print(pedro.olhos) print(id(Pessoa.olhos),id(joao.olhos),id(pedro.olhos)) print(Pessoa.metodo_estatico(),joao.metodo_estatico())", "= idade self.filhos = list(filhos) def cumprimentar(self): return f\"olá {self.nome} id({id(self)})\" @staticmethod def", "return f\"olá {self.nome} id({id(self)})\" @staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributo_de_clsse(cls): return", "pedro.filhos: print(filho.nome) joao.sobrenome = \"Silva\" del pedro.filhos joao.olhos = 1 Pessoa.olhos = 3", "@classmethod def nome_e_atributo_de_clsse(cls): return f\"{cls} olhos {cls.olhos}\" if __name__ == \"__main__\": joao =", "f\"{cls} olhos {cls.olhos}\" if __name__ == \"__main__\": joao = Pessoa(nome='João') pedro = Pessoa(joao,nome='Pedro')", "self.idade = idade self.filhos = list(filhos) def cumprimentar(self): return f\"olá {self.nome} id({id(self)})\" @staticmethod", "\"__main__\": joao = Pessoa(nome='João') pedro = Pessoa(joao,nome='Pedro') print(Pessoa.cumprimentar(pedro)) print(id(joao)) for filho in pedro.filhos:", "del pedro.filhos joao.olhos = 1 Pessoa.olhos = 3 print(joao.__dict__) print(pedro.__dict__) print(Pessoa.olhos) print(joao.olhos) print(pedro.olhos)", "self.filhos = list(filhos) def cumprimentar(self): return f\"olá {self.nome} id({id(self)})\" @staticmethod def metodo_estatico(): return", "list(filhos) def cumprimentar(self): return f\"olá {self.nome} id({id(self)})\" @staticmethod def metodo_estatico(): return 42 @classmethod", "filho in pedro.filhos: print(filho.nome) joao.sobrenome = \"Silva\" del pedro.filhos joao.olhos = 1 Pessoa.olhos", "*filhos, nome=None, idade=10): self.nome = nome self.idade = idade self.filhos = list(filhos) def", "__name__ == \"__main__\": joao = Pessoa(nome='João') pedro = Pessoa(joao,nome='Pedro') print(Pessoa.cumprimentar(pedro)) print(id(joao)) for filho", "= \"Silva\" del pedro.filhos joao.olhos = 1 Pessoa.olhos = 3 print(joao.__dict__) print(pedro.__dict__) print(Pessoa.olhos)", "in pedro.filhos: print(filho.nome) joao.sobrenome = \"Silva\" del pedro.filhos joao.olhos = 1 Pessoa.olhos =", "= Pessoa(joao,nome='Pedro') print(Pessoa.cumprimentar(pedro)) print(id(joao)) for filho in pedro.filhos: print(filho.nome) joao.sobrenome = \"Silva\" del", "metodo_estatico(): return 42 @classmethod def nome_e_atributo_de_clsse(cls): return f\"{cls} olhos {cls.olhos}\" if __name__ ==", "return f\"{cls} olhos {cls.olhos}\" if __name__ == \"__main__\": joao = Pessoa(nome='João') pedro =", "= Pessoa(nome='João') pedro = Pessoa(joao,nome='Pedro') print(Pessoa.cumprimentar(pedro)) print(id(joao)) for filho in pedro.filhos: print(filho.nome) joao.sobrenome", "Pessoa(nome='João') pedro = Pessoa(joao,nome='Pedro') print(Pessoa.cumprimentar(pedro)) print(id(joao)) for filho in pedro.filhos: print(filho.nome) joao.sobrenome =", "pedro.filhos joao.olhos = 1 Pessoa.olhos = 3 print(joao.__dict__) print(pedro.__dict__) print(Pessoa.olhos) print(joao.olhos) print(pedro.olhos) print(id(Pessoa.olhos),id(joao.olhos),id(pedro.olhos))", "def cumprimentar(self): return f\"olá {self.nome} id({id(self)})\" @staticmethod def metodo_estatico(): return 42 @classmethod def", "= list(filhos) def cumprimentar(self): return f\"olá {self.nome} id({id(self)})\" @staticmethod def metodo_estatico(): return 42", "<reponame>arisobel/pythonbirds class Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=10): self.nome =", "olhos = 2 def __init__(self, *filhos, nome=None, idade=10): self.nome = nome self.idade =", "print(id(joao)) for filho in pedro.filhos: print(filho.nome) joao.sobrenome = \"Silva\" del pedro.filhos joao.olhos =", "nome=None, idade=10): self.nome = nome self.idade = idade self.filhos = list(filhos) def cumprimentar(self):", "print(filho.nome) joao.sobrenome = \"Silva\" del pedro.filhos joao.olhos = 1 Pessoa.olhos = 3 print(joao.__dict__)", "def nome_e_atributo_de_clsse(cls): return f\"{cls} olhos {cls.olhos}\" if __name__ == \"__main__\": joao = Pessoa(nome='João')" ]
[ "df to save as target feature(s) targ_type: type of target feature, e.g. int,'float32'", "if the matrix is in sparse COO format and should be densified later", "def fold2foldfile(df:pd.DataFrame, out_file:h5py.File, fold_idx:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], targ_type:Any, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, matrix_lookup:Optional[List[str]]=None, matrix_missing:Optional[np.ndarray]=None, matrix_shape:Optional[Tuple[int,int]]=None,", "variables cat_feats: list of columns in df to save as discreet variables targ_feats:", "dtype=np.array(feats).dtype),np.zeros(shape, dtype=np.bool) if row_wise: for i, v in enumerate(vecs): for j, c in", "def _build_matrix_lookups(feats:List[str], vecs:List[str], feats_per_vec:List[str], row_wise:bool) -> Tuple[List[str],np.ndarray,Tuple[int,int]]: shape = (len(vecs),len(feats_per_vec)) if row_wise else", "use, 'vecs': matrix_vecs, 'missing': [int(m) for m in missing], 'feats_per_vec': matrix_feats_per_vec, 'row_wise': matrix_row_wise,", "return list(lookup.flatten()),missing.flatten(),shape def fold2foldfile(df:pd.DataFrame, out_file:h5py.File, fold_idx:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], targ_type:Any, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, matrix_lookup:Optional[List[str]]=None,", "targ_type=targ_type, misc_feats=misc_feats, wgt_feat=wgt_feat, matrix_lookup=lookup, matrix_missing=missing, matrix_shape=shape, tensor_data=tensor_data[fold] if tensor_data is not None else", "passed to `tensor_data`. compression: optional compression argument for h5py, e.g. 'lzf' ''' savename", "= h5py.File(f'{savename}.hdf5', \"w\") lookup,missing,shape = None,None,None if matrix_vecs is not None: if tensor_data", "arr: array to be saved grp: group in which to save arr name:", "setting `matrix_lookup`, `matrix_missing`, and `matrix_shape`. The first dimension of the array must be", "column(s) in df to save as target feature(s) targ_type: type of target feature,", "suffixes. Features listed but not present in df will be replaced with NaN.", "objects will access this and automatically extract it to save the user from", "tensor_name: Name used to refer to the tensor when displaying model information tensor_shp:", "tensor_name=tensor_name, tensor_shp=tensor_data[0].shape if tensor_data is not None else None, tensor_is_sparse=tensor_is_sparse) def add_meta_data(out_file:h5py.File, feats:List[str],", "to use ''' grp = out_file.create_group('meta_data') grp.create_dataset('cont_feats', data=json.dumps(cont_feats)) grp.create_dataset('cat_feats', data=json.dumps(cat_feats)) grp.create_dataset('targ_feats', data=json.dumps(targ_feats)) if", "(i.e. all the features associated with an object are in their own row),", "out_file: h5py file to save data in feats: list of all features in", "of continuous features cat_feats: list of categorical features cat_maps: Dictionary mapping categorical features", "in their own column) tensor_data: data of higher order than a matrix can", "matrix_lookup is not None: if tensor_data is not None: raise ValueError(\"The saving of", "the other.\") mat = df[matrix_lookup].values.astype('float32') mat[:,matrix_missing] = np.NaN mat = mat.reshape((len(df),*matrix_shape)) save_to_grp(mat, grp,", "this and automatically extract it to save the user from having to manually", "length grp.create_dataset(name, shape=arr.shape, dtype=arr.dtype.name if arr.dtype.name not in ['object', 'str864'] else 'S64', data=arr", "will be saved under matrix data, and this is incompatible with also setting", "data=json.dumps(targ_feats)) if wgt_feat is not None: grp.create_dataset('wgt_feat', data=json.dumps(wgt_feat)) if cat_maps is not None:", "will to the foldfile's metadata. tensor_is_sparse: Set to True if the matrix is", "Only features present in data dup = [f for f in cont_feats if", "grp, 'inputs', compression=compression) save_to_grp(df[targ_feats].values.astype(targ_type), grp, 'targets', compression=compression) if wgt_feat is not None: if", "def add_meta_data(out_file:h5py.File, feats:List[str], cont_feats:List[str], cat_feats:List[str], cat_maps:Optional[Dict[str,Dict[int,Any]]], targ_feats:Union[str,List[str]], wgt_feat:Optional[str]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_name:Optional[str]=None, tensor_shp:Optional[Tuple[int]]=None,", "optional compression argument for h5py, e.g. 'lzf' ''' # TODO Option for string", "not None: grp.create_dataset('wgt_feat', data=json.dumps(wgt_feat)) if cat_maps is not None: grp.create_dataset('cat_maps', data=json.dumps(cat_maps)) if matrix_vecs", "than a matrix can be passed directly as a numpy array, rather than", "misc_feats=misc_feats, wgt_feat=wgt_feat, matrix_lookup=lookup, matrix_missing=missing, matrix_shape=shape, tensor_data=tensor_data[fold] if tensor_data is not None else None,", "of) target feature(s) wgt_feat: name of weight feature matrix_vecs: list of objects for", "to save data out_file: h5py file to save data in fold_idx: ID for", "matrix_feats_per_vec=matrix_feats_per_vec, matrix_row_wise=matrix_row_wise, tensor_name=tensor_name, tensor_shp=tensor_data[0].shape if tensor_data is not None else None, tensor_is_sparse=tensor_is_sparse) def", "None, tensor_is_sparse=tensor_is_sparse) def add_meta_data(out_file:h5py.File, feats:List[str], cont_feats:List[str], cat_feats:List[str], cat_maps:Optional[Dict[str,Dict[int,Any]]], targ_feats:Union[str,List[str]], wgt_feat:Optional[str]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None,", "targ_feats:Union[str,List[str]], wgt_feat:Optional[str]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_name:Optional[str]=None, tensor_shp:Optional[Tuple[int]]=None, tensor_is_sparse:bool=False) -> None: r''' Adds meta", "'fold2foldfile', 'df2foldfile', 'add_meta_data'] def save_to_grp(arr:np.ndarray, grp:h5py.Group, name:str, compression:Optional[str]=None) -> None: r''' Save Numpy", "the name that will to the foldfile's metadata. tensor_is_sparse: Set to True if", "''' savename = str(savename) os.system(f'rm {savename}.hdf5') os.makedirs(savename[:savename.rfind('/')], exist_ok=True) out_file = h5py.File(f'{savename}.hdf5', \"w\") lookup,missing,shape", "cont_feats=cont_feats, cat_feats=cat_feats, targ_feats=targ_feats, targ_type=targ_type, misc_feats=misc_feats, wgt_feat=wgt_feat, matrix_lookup=lookup, matrix_missing=missing, matrix_shape=shape, tensor_data=tensor_data[fold] if tensor_data is", "shape})) elif tensor_name is not None: grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': [tensor_name], 'vecs': [tensor_name], 'missing': [],", "f in df.columns: save_to_grp(df[f].values, grp, f, compression=compression) else: print(f'{f} not found in file')", "os from pathlib import Path import json from sklearn.model_selection import StratifiedKFold, KFold __all__", "in df to save as discreet variables targ_feats: (list of) column(s) in df", "that will to the foldfile's metadata. tensor_is_sparse: Set to True if the matrix", "etc. :class:`~lumin.nn.data.fold_yielder.FoldYielder` objects will access this and automatically extract it to save the", "feature matrix_vecs: list of objects for matrix encoding, i.e. feature prefixes matrix_feats_per_vec: list", "the matrix is in sparse COO format and should be densified later on", "meta data to foldfile containing information about the data: feature names, matrix information,", "elif tensor_name is not None: grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': [tensor_name], 'vecs': [tensor_name], 'missing': [], 'feats_per_vec':", "h5py, e.g. 'lzf' ''' # TODO infer target type automatically grp = out_file.create_group(f'fold_{fold_idx}')", "data n_folds: number of folds to split df into cont_feats: list of columns", "1: print(f'{dup} present in both matrix features and continuous features; removing from continuous", "under matrix data, and this is incompatible with also setting `matrix_lookup`, `matrix_missing`, and", "f in cont_feats if f not in dup] if strat_key is not None", "of target feature, e.g. int,'float32' misc_feats: any extra columns to save wgt_feat: column", "not present in df will be replaced with NaN. matrix_row_wise: whether objects encoded", "matrix encoding, i.e. feature prefixes matrix_feats_per_vec: list of features per vector for matrix", "DataFrame') strat_key = None if strat_key is None: kf = KFold(n_splits=n_folds, shuffle=True) folds", "kf = KFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df) else: kf = StratifiedKFold(n_splits=n_folds, shuffle=True) folds", "`matrix_shape`. The first dimension of the array must be compatible with the length", "save the user from having to manually pass lists of features. Arguments: out_file:", "targ_feats:Union[str,List[str]], targ_type:Any, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, matrix_lookup:Optional[List[str]]=None, matrix_missing:Optional[np.ndarray]=None, matrix_shape:Optional[Tuple[int,int]]=None, tensor_data:Optional[np.ndarray]=None, compression:Optional[str]=None) -> None: r''' Save", "h5py Group Arguments: df: Dataframe from which to save data out_file: h5py file", "else None, compression=compression) add_meta_data(out_file=out_file, feats=df.columns, cont_feats=cont_feats, cat_feats=cat_feats, cat_maps=cat_maps, targ_feats=targ_feats, wgt_feat=wgt_feat, matrix_vecs=matrix_vecs, matrix_feats_per_vec=matrix_feats_per_vec, matrix_row_wise=matrix_row_wise,", "shape = (len(vecs),len(feats_per_vec)) if row_wise else (len(feats_per_vec),len(vecs)) lookup,missing = np.zeros(shape, dtype=np.array(feats).dtype),np.zeros(shape, dtype=np.bool) if", "array as a dataset in an h5py Group Arguments: arr: array to be", "None and strat_key not in df.columns: print(f'{strat_key} not found in DataFrame') strat_key =", "save data n_folds: number of folds to split df into cont_feats: list of", "object are in their own column) tensor_data: data of higher order than a", "misc_feats: if f in df.columns: save_to_grp(df[f].values, grp, f, compression=compression) else: print(f'{f} not found", "compression=compression) save_to_grp(df[targ_feats].values.astype(targ_type), grp, 'targets', compression=compression) if wgt_feat is not None: if wgt_feat in", "'vecs': matrix_vecs, 'missing': [int(m) for m in missing], 'feats_per_vec': matrix_feats_per_vec, 'row_wise': matrix_row_wise, 'shape':", "columns in df to save as continuous variables cat_feats: list of columns in", "be passed directly as a numpy array, rather than beign extracted and reshaped", "information, etc. :class:`~lumin.nn.data.fold_yielder.FoldYielder` objects will access this and automatically extract it to save", "feature suffixes. Features listed but not present in df will be replaced with", "folds = kf.split(X=df) else: kf = StratifiedKFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df, y=df[strat_key]) for", "save as data weights matrix_vecs: list of objects for matrix encoding, i.e. feature", "is None: kf = KFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df) else: kf = StratifiedKFold(n_splits=n_folds,", "None else None, compression=compression) add_meta_data(out_file=out_file, feats=df.columns, cont_feats=cont_feats, cat_feats=cat_feats, cat_maps=cat_maps, targ_feats=targ_feats, wgt_feat=wgt_feat, matrix_vecs=matrix_vecs, matrix_feats_per_vec=matrix_feats_per_vec,", "df2foldfile(df:pd.DataFrame, n_folds:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], savename:Union[Path,str], targ_type:str, strat_key:Optional[str]=None, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, cat_maps:Optional[Dict[str,Dict[int,Any]]]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None,", "must be compatible with the length of the data frame. tensor_name: if `tensor_data`", "of the data frame. tensor_name: if `tensor_data` is set, then this is the", "row_wise: for i, v in enumerate(vecs): for j, c in enumerate(feats_per_vec): f =", "None: lookup,missing,shape = _build_matrix_lookups(feats, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) use = list(np.array(lookup)[np.logical_not(missing)]) # Only features", "grp = out_file.create_group(f'fold_{fold_idx}') save_to_grp(np.hstack((df[cont_feats].values.astype('float32'), df[cat_feats].values.astype('float32'))), grp, 'inputs', compression=compression) save_to_grp(df[targ_feats].values.astype(targ_type), grp, 'targets', compression=compression) if", "tensor_data is not None: save_to_grp(tensor_data.astype('float32'), grp, 'matrix_inputs', compression=compression) def df2foldfile(df:pd.DataFrame, n_folds:int, cont_feats:List[str], cat_feats:List[str],", "name of dataset to create compression: optional compression argument for h5py, e.g. 'lzf'", "str(savename) os.system(f'rm {savename}.hdf5') os.makedirs(savename[:savename.rfind('/')], exist_ok=True) out_file = h5py.File(f'{savename}.hdf5', \"w\") lookup,missing,shape = None,None,None if", "data=arr if arr.dtype.name not in ['object', 'str864'] else arr.astype('S64'), compression=compression) def _build_matrix_lookups(feats:List[str], vecs:List[str],", "None,None,None if matrix_vecs is not None: if tensor_data is not None: raise ValueError(\"The", "present in both matrix features and continuous features; removing from continuous features') cont_feats", "tensor_shp=tensor_data[0].shape if tensor_data is not None else None, tensor_is_sparse=tensor_is_sparse) def add_meta_data(out_file:h5py.File, feats:List[str], cont_feats:List[str],", "features to dictionary mapping codes to categories targ_feats: (list of) target feature(s) wgt_feat:", "f in mat_feats] if len(dup) > 1: print(f'{dup} present in both matrix features", "use = list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': use, 'vecs':", "if f in feats: lookup[i,j] = f else: lookup[i,j] = feats[0] # Temp", "extra columns to save wgt_feat: column to save as data weights cat_maps: Dictionary", "else arr.astype('S64'), compression=compression) def _build_matrix_lookups(feats:List[str], vecs:List[str], feats_per_vec:List[str], row_wise:bool) -> Tuple[List[str],np.ndarray,Tuple[int,int]]: shape = (len(vecs),len(feats_per_vec))", "= mat.reshape((len(df),*matrix_shape)) save_to_grp(mat, grp, 'matrix_inputs', compression=compression) elif tensor_data is not None: save_to_grp(tensor_data.astype('float32'), grp,", "`tensor_data` is set, then this is the name that will to the foldfile's", "matrix_row_wise=matrix_row_wise, tensor_name=tensor_name, tensor_shp=tensor_data[0].shape if tensor_data is not None else None, tensor_is_sparse=tensor_is_sparse) def add_meta_data(out_file:h5py.File,", "densified prior to use ''' grp = out_file.create_group('meta_data') grp.create_dataset('cont_feats', data=json.dumps(cont_feats)) grp.create_dataset('cat_feats', data=json.dumps(cat_feats)) grp.create_dataset('targ_feats',", "in an h5py Group Arguments: arr: array to be saved grp: group in", "cont_feats: list of continuous features cat_feats: list of categorical features cat_maps: Dictionary mapping", "not in dup] if strat_key is not None and strat_key not in df.columns:", "Name used to refer to the tensor when displaying model information tensor_shp: The", "# Temp value, to be set to null later using missing missing[i,j] =", "import numpy as np import pandas as pd from typing import List, Union,", "features and continuous features; removing from continuous features') cont_feats = [f for f", "{fold_idx} with {len(fold)} events\") fold2foldfile(df.iloc[fold].copy(), out_file, fold_idx, cont_feats=cont_feats, cat_feats=cat_feats, targ_feats=targ_feats, targ_type=targ_type, misc_feats=misc_feats, wgt_feat=wgt_feat,", "file to save data in fold_idx: ID for the fold; used name h5py", "of the tensor data (exclusing batch dimension) tensor_is_sparse: Whether the tensor is sparse", "in their own column) tensor_name: Name used to refer to the tensor when", "grp.create_dataset('wgt_feat', data=json.dumps(wgt_feat)) if cat_maps is not None: grp.create_dataset('cat_maps', data=json.dumps(cat_maps)) if matrix_vecs is not", "column-wise (i.e. all the features associated with an object are in their own", "= ['save_to_grp', 'fold2foldfile', 'df2foldfile', 'add_meta_data'] def save_to_grp(arr:np.ndarray, grp:h5py.Group, name:str, compression:Optional[str]=None) -> None: r'''", "fold; used name h5py group according to 'fold_{fold_idx}' cont_feats: list of columns in", "matrix is in sparse COO format and should be densified later on The", "targ_feats=targ_feats, targ_type=targ_type, misc_feats=misc_feats, wgt_feat=wgt_feat, matrix_lookup=lookup, matrix_missing=missing, matrix_shape=shape, tensor_data=tensor_data[fold] if tensor_data is not None", "columns to save wgt_feat: column to save as data weights matrix_vecs: list of", "all the features associated with an object are in their own column) tensor_name:", ":class:`~lumin.nn.data.fold_yielder.FoldYielder` Arguments: df: Dataframe from which to save data n_folds: number of folds", "for h5py, e.g. 'lzf' ''' # TODO Option for string length grp.create_dataset(name, shape=arr.shape,", "grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': use, 'vecs': matrix_vecs, 'missing': [int(m) for m in missing], 'feats_per_vec': matrix_feats_per_vec,", "np.zeros(shape, dtype=np.array(feats).dtype),np.zeros(shape, dtype=np.bool) if row_wise: for i, v in enumerate(vecs): for j, c", "create compression: optional compression argument for h5py, e.g. 'lzf' ''' # TODO Option", "DataFrame. The array will be saved under matrix data, and this is incompatible", "is not None: grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': [tensor_name], 'vecs': [tensor_name], 'missing': [], 'feats_per_vec': [''], 'row_wise':", "set to null later using missing missing[i,j] = True else: for j, v", "y=df[strat_key]) for fold_idx, (_, fold) in enumerate(folds): print(f\"Saving fold {fold_idx} with {len(fold)} events\")", "None: grp.create_dataset('wgt_feat', data=json.dumps(wgt_feat)) if cat_maps is not None: grp.create_dataset('cat_maps', data=json.dumps(cat_maps)) if matrix_vecs is", "continuous variables cat_feats: list of columns in df to save as discreet variables", "file by splitting data into sub-folds to be accessed by a :class:`~lumin.nn.data.fold_yielder.FoldYielder` Arguments:", "data, and this is incompatible with also setting `matrix_vecs`, `matrix_feats_per_vec`, and `matrix_row_wise`. The", "and should be densified later on The format expected is `coo_x = sparse.as_coo(x);", "e.g. 'lzf' ''' # TODO infer target type automatically grp = out_file.create_group(f'fold_{fold_idx}') save_to_grp(np.hstack((df[cont_feats].values.astype('float32'),", "is in sparse COO format and should be densified later on The format", "optional compression argument for h5py, e.g. 'lzf' ''' # TODO infer target type", "matrix_row_wise) use = list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': use,", "int,'float32' misc_feats: any extra columns to save wgt_feat: column to save as data", "splitting data into sub-folds to be accessed by a :class:`~lumin.nn.data.fold_yielder.FoldYielder` Arguments: df: Dataframe", "to null later using missing missing[i,j] = True else: for j, v in", "not None: if tensor_data is not None: raise ValueError(\"The saving of both matrix", "= True return list(lookup.flatten()),missing.flatten(),shape def fold2foldfile(df:pd.DataFrame, out_file:h5py.File, fold_idx:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], targ_type:Any, misc_feats:Optional[List[str]]=None,", "else: print(f'{f} not found in file') if matrix_lookup is not None: if tensor_data", "if `tensor_data` is set, then this is the name that will to the", "tensor_name is not None: grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': [tensor_name], 'vecs': [tensor_name], 'missing': [], 'feats_per_vec': [''],", "data=json.dumps(wgt_feat)) if cat_maps is not None: grp.create_dataset('cat_maps', data=json.dumps(cat_maps)) if matrix_vecs is not None:", "r''' Save fold of data into an h5py Group Arguments: df: Dataframe from", "strat_key is None: kf = KFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df) else: kf =", "in their own row), or column-wise (i.e. all the features associated with an", "this is the name that will to the foldfile's metadata. tensor_is_sparse: Set to", "tensor_name:Optional[str]=None, tensor_shp:Optional[Tuple[int]]=None, tensor_is_sparse:bool=False) -> None: r''' Adds meta data to foldfile containing information", "tensor_shp:Optional[Tuple[int]]=None, tensor_is_sparse:bool=False) -> None: r''' Adds meta data to foldfile containing information about", "r''' Convert dataframe into h5py file by splitting data into sub-folds to be", "it to save the user from having to manually pass lists of features.", "objects for matrix encoding, i.e. feature prefixes matrix_feats_per_vec: list of features per vector", "discreet variables targ_feats: (list of) column(s) in df to save as target feature(s)", "matrix information, etc. :class:`~lumin.nn.data.fold_yielder.FoldYielder` objects will access this and automatically extract it to", "grp.create_dataset('cat_maps', data=json.dumps(cat_maps)) if matrix_vecs is not None: lookup,missing,shape = _build_matrix_lookups(feats, matrix_vecs, matrix_feats_per_vec, matrix_row_wise)", "import os from pathlib import Path import json from sklearn.model_selection import StratifiedKFold, KFold", "list of columns in df to save as continuous variables cat_feats: list of", "matrix_lookup=lookup, matrix_missing=missing, matrix_shape=shape, tensor_data=tensor_data[fold] if tensor_data is not None else None, compression=compression) add_meta_data(out_file=out_file,", "per vector for matrix encoding, i.e. feature suffixes. Features listed but not present", "True if the matrix is in sparse COO format and should be densified", "by a :class:`~lumin.nn.data.fold_yielder.FoldYielder` Arguments: df: Dataframe from which to save data n_folds: number", "missing missing[i,j] = True return list(lookup.flatten()),missing.flatten(),shape def fold2foldfile(df:pd.DataFrame, out_file:h5py.File, fold_idx:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]],", "extra columns to save wgt_feat: column to save as data weights matrix_vecs: list", "matrix and tensor data is requested. This is ambiguous. Please only set one", "as target feature(s) savename: name of h5py file to create (.h5py extension not", "numpy as np import pandas as pd from typing import List, Union, Optional,", "splitting misc_feats: any extra columns to save wgt_feat: column to save as data", "data=json.dumps(cont_feats)) grp.create_dataset('cat_feats', data=json.dumps(cat_feats)) grp.create_dataset('targ_feats', data=json.dumps(targ_feats)) if wgt_feat is not None: grp.create_dataset('wgt_feat', data=json.dumps(wgt_feat)) if", "matrix_vecs is not None: lookup,missing,shape = _build_matrix_lookups(feats, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) use = list(np.array(lookup)[np.logical_not(missing)])", "a matrix should be encoded row-wise (i.e. all the features associated with an", "missing[i,j] = True else: for j, v in enumerate(vecs): for i, c in", "lookup[i,j] = feats[0] # Temp value, to be set to null later using", "v in enumerate(vecs): for i, c in enumerate(feats_per_vec): f = f'{v}_{c}' if f", "if tensor_data is not None else None, tensor_is_sparse=tensor_is_sparse) def add_meta_data(out_file:h5py.File, feats:List[str], cont_feats:List[str], cat_feats:List[str],", "compatible with the length of the data frame. tensor_name: if `tensor_data` is set,", "[f for f in cont_feats if f not in dup] if strat_key is", "to categories targ_feats: (list of) target feature(s) wgt_feat: name of weight feature matrix_vecs:", "mapping codes to categories targ_feats: (list of) target feature(s) wgt_feat: name of weight", "e.g. 'lzf' ''' savename = str(savename) os.system(f'rm {savename}.hdf5') os.makedirs(savename[:savename.rfind('/')], exist_ok=True) out_file = h5py.File(f'{savename}.hdf5',", "tensor_is_sparse=tensor_is_sparse) def add_meta_data(out_file:h5py.File, feats:List[str], cont_feats:List[str], cat_feats:List[str], cat_maps:Optional[Dict[str,Dict[int,Any]]], targ_feats:Union[str,List[str]], wgt_feat:Optional[str]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_name:Optional[str]=None,", "directly as a numpy array, rather than beign extracted and reshaped from the", "target type automatically grp = out_file.create_group(f'fold_{fold_idx}') save_to_grp(np.hstack((df[cont_feats].values.astype('float32'), df[cat_feats].values.astype('float32'))), grp, 'inputs', compression=compression) save_to_grp(df[targ_feats].values.astype(targ_type), grp,", "names, matrix information, etc. :class:`~lumin.nn.data.fold_yielder.FoldYielder` objects will access this and automatically extract it", "in feats: lookup[i,j] = f else: lookup[i,j] = feats[0] # Temp value, to", "j, c in enumerate(feats_per_vec): f = f'{v}_{c}' if f in feats: lookup[i,j] =", "not None: if wgt_feat in df.columns: save_to_grp(df[wgt_feat].values.astype('float32'), grp, 'weights', compression=compression) else: print(f'{wgt_feat} not", "incompatible with also setting `matrix_vecs`, `matrix_feats_per_vec`, and `matrix_row_wise`. The first dimension of the", "fold_idx, cont_feats=cont_feats, cat_feats=cat_feats, targ_feats=targ_feats, targ_type=targ_type, misc_feats=misc_feats, wgt_feat=wgt_feat, matrix_lookup=lookup, matrix_missing=missing, matrix_shape=shape, tensor_data=tensor_data[fold] if tensor_data", "feature prefixes matrix_feats_per_vec: list of features per vector for matrix encoding, i.e. feature", "wgt_feat=wgt_feat, matrix_vecs=matrix_vecs, matrix_feats_per_vec=matrix_feats_per_vec, matrix_row_wise=matrix_row_wise, tensor_name=tensor_name, tensor_shp=tensor_data[0].shape if tensor_data is not None else None,", "ambiguous. Please only set one of the other.\") mat = df[matrix_lookup].values.astype('float32') mat[:,matrix_missing] =", "None else None, tensor_is_sparse=tensor_is_sparse) def add_meta_data(out_file:h5py.File, feats:List[str], cont_feats:List[str], cat_feats:List[str], cat_maps:Optional[Dict[str,Dict[int,Any]]], targ_feats:Union[str,List[str]], wgt_feat:Optional[str]=None, matrix_vecs:Optional[List[str]]=None,", "target feature(s) wgt_feat: name of weight feature matrix_vecs: list of objects for matrix", "with also setting `matrix_lookup`, `matrix_missing`, and `matrix_shape`. The first dimension of the array", "object are in their own row), or column-wise (i.e. all the features associated", "encoded as a matrix should be encoded row-wise (i.e. all the features associated", "= (len(vecs),len(feats_per_vec)) if row_wise else (len(feats_per_vec),len(vecs)) lookup,missing = np.zeros(shape, dtype=np.array(feats).dtype),np.zeros(shape, dtype=np.bool) if row_wise:", "np.NaN mat = mat.reshape((len(df),*matrix_shape)) save_to_grp(mat, grp, 'matrix_inputs', compression=compression) elif tensor_data is not None:", "data dup = [f for f in cont_feats if f in mat_feats] if", "Optional, Any, Tuple, Dict import os from pathlib import Path import json from", "import StratifiedKFold, KFold __all__ = ['save_to_grp', 'fold2foldfile', 'df2foldfile', 'add_meta_data'] def save_to_grp(arr:np.ndarray, grp:h5py.Group, name:str,", "rather than beign extracted and reshaped from the DataFrame. The array will be", "= list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data dup = [f for f", "dataframe into h5py file by splitting data into sub-folds to be accessed by", "tensor_shp: The shape of the tensor data (exclusing batch dimension) tensor_is_sparse: Whether the", "dtype=arr.dtype.name if arr.dtype.name not in ['object', 'str864'] else 'S64', data=arr if arr.dtype.name not", "= kf.split(X=df) else: kf = StratifiedKFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df, y=df[strat_key]) for fold_idx,", "wgt_feat:Optional[str]=None, matrix_lookup:Optional[List[str]]=None, matrix_missing:Optional[np.ndarray]=None, matrix_shape:Optional[Tuple[int,int]]=None, tensor_data:Optional[np.ndarray]=None, compression:Optional[str]=None) -> None: r''' Save fold of data", "'matrix_inputs', compression=compression) elif tensor_data is not None: save_to_grp(tensor_data.astype('float32'), grp, 'matrix_inputs', compression=compression) def df2foldfile(df:pd.DataFrame,", "h5py, e.g. 'lzf' ''' # TODO Option for string length grp.create_dataset(name, shape=arr.shape, dtype=arr.dtype.name", "`matrix_row_wise`. The first dimension of the array must be compatible with the length", "under matrix data, and this is incompatible with also setting `matrix_vecs`, `matrix_feats_per_vec`, and", "r''' Adds meta data to foldfile containing information about the data: feature names,", "from the DataFrame. The array will be saved under matrix data, and this", "= feats[0] # Temp value, to be set to null later using missing", "feats=df.columns, cont_feats=cont_feats, cat_feats=cat_feats, cat_maps=cat_maps, targ_feats=targ_feats, wgt_feat=wgt_feat, matrix_vecs=matrix_vecs, matrix_feats_per_vec=matrix_feats_per_vec, matrix_row_wise=matrix_row_wise, tensor_name=tensor_name, tensor_shp=tensor_data[0].shape if tensor_data", "matrix_vecs, 'missing': [int(m) for m in missing], 'feats_per_vec': matrix_feats_per_vec, 'row_wise': matrix_row_wise, 'shape': shape}))", "with an object are in their own column) tensor_name: Name used to refer", "in feats: list of all features in data cont_feats: list of continuous features", "= out_file.create_group('meta_data') grp.create_dataset('cont_feats', data=json.dumps(cont_feats)) grp.create_dataset('cat_feats', data=json.dumps(cat_feats)) grp.create_dataset('targ_feats', data=json.dumps(targ_feats)) if wgt_feat is not None:", "_build_matrix_lookups(feats, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) use = list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data", "which to save data out_file: h5py file to save data in fold_idx: ID", "to save as discreet variables targ_feats: (list of) column(s) in df to save", "True return list(lookup.flatten()),missing.flatten(),shape def fold2foldfile(df:pd.DataFrame, out_file:h5py.File, fold_idx:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], targ_type:Any, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None,", "matrix_row_wise:Optional[bool]=None, tensor_data:Optional[np.ndarray]=None, tensor_name:Optional[str]=None, tensor_is_sparse:bool=False, compression:Optional[str]=None) -> None: r''' Convert dataframe into h5py file", "to split df into cont_feats: list of columns in df to save as", "column(s) in df to save as target feature(s) savename: name of h5py file", "argument for h5py, e.g. 'lzf' ''' # TODO Option for string length grp.create_dataset(name,", "not found in DataFrame') strat_key = None if strat_key is None: kf =", "targ_feats=targ_feats, wgt_feat=wgt_feat, matrix_vecs=matrix_vecs, matrix_feats_per_vec=matrix_feats_per_vec, matrix_row_wise=matrix_row_wise, tensor_name=tensor_name, tensor_shp=tensor_data[0].shape if tensor_data is not None else", "a numpy array, rather than beign extracted and reshaped from the DataFrame. The", "refer to the tensor when displaying model information tensor_shp: The shape of the", "group according to 'fold_{fold_idx}' cont_feats: list of columns in df to save as", "Option for string length grp.create_dataset(name, shape=arr.shape, dtype=arr.dtype.name if arr.dtype.name not in ['object', 'str864']", "the data: feature names, matrix information, etc. :class:`~lumin.nn.data.fold_yielder.FoldYielder` objects will access this and", "in enumerate(feats_per_vec): f = f'{v}_{c}' if f in feats: lookup[i,j] = f else:", "'row_wise': matrix_row_wise, 'shape': shape})) elif tensor_name is not None: grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': [tensor_name], 'vecs':", "grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': [tensor_name], 'vecs': [tensor_name], 'missing': [], 'feats_per_vec': [''], 'row_wise': None, 'shape': tensor_shp,", "mat = df[matrix_lookup].values.astype('float32') mat[:,matrix_missing] = np.NaN mat = mat.reshape((len(df),*matrix_shape)) save_to_grp(mat, grp, 'matrix_inputs', compression=compression)", "-> None: r''' Adds meta data to foldfile containing information about the data:", "Arguments: df: Dataframe from which to save data out_file: h5py file to save", "strat_key not in df.columns: print(f'{strat_key} not found in DataFrame') strat_key = None if", "to save as data weights cat_maps: Dictionary mapping categorical features to dictionary mapping", "df: Dataframe from which to save data out_file: h5py file to save data", "tensor_data is not None else None, tensor_is_sparse=tensor_is_sparse) def add_meta_data(out_file:h5py.File, feats:List[str], cont_feats:List[str], cat_feats:List[str], cat_maps:Optional[Dict[str,Dict[int,Any]]],", "compatible with the length of the data frame. compression: optional compression argument for", "of) column(s) in df to save as target feature(s) savename: name of h5py", "are in their own column) tensor_data: data of higher order than a matrix", "of features. Arguments: out_file: h5py file to save data in feats: list of", "optional compression argument for h5py, e.g. 'lzf' ''' savename = str(savename) os.system(f'rm {savename}.hdf5')", "prior to use ''' grp = out_file.create_group('meta_data') grp.create_dataset('cont_feats', data=json.dumps(cont_feats)) grp.create_dataset('cat_feats', data=json.dumps(cat_feats)) grp.create_dataset('targ_feats', data=json.dumps(targ_feats))", "dup = [f for f in cont_feats if f in mat_feats] if len(dup)", "matrix can be passed directly as a numpy array, rather than beign extracted", "requested. This is ambiguous. Please only set one of the other.\") lookup,missing,shape =", "n_folds:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], savename:Union[Path,str], targ_type:str, strat_key:Optional[str]=None, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, cat_maps:Optional[Dict[str,Dict[int,Any]]]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None,", "grp, f, compression=compression) else: print(f'{f} not found in file') if matrix_lookup is not", "wgt_feat: name of weight feature matrix_vecs: list of objects for matrix encoding, i.e.", "associated with an object are in their own column) tensor_name: Name used to", "later using missing missing[i,j] = True return list(lookup.flatten()),missing.flatten(),shape def fold2foldfile(df:pd.DataFrame, out_file:h5py.File, fold_idx:int, cont_feats:List[str],", "should be densified later on The format expected is `coo_x = sparse.as_coo(x); m", "file') if matrix_lookup is not None: if tensor_data is not None: raise ValueError(\"The", "column to use for stratified splitting misc_feats: any extra columns to save wgt_feat:", "will access this and automatically extract it to save the user from having", "is not None: for f in misc_feats: if f in df.columns: save_to_grp(df[f].values, grp,", "not None: grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': [tensor_name], 'vecs': [tensor_name], 'missing': [], 'feats_per_vec': [''], 'row_wise': None,", "expected is `coo_x = sparse.as_coo(x); m = np.vstack((coo_x.data, coo_x.coords))`, where `m` is the", "an h5py Group Arguments: arr: array to be saved grp: group in which", "codes to categories matrix_vecs: list of objects for matrix encoding, i.e. feature prefixes", "lookup,missing,shape = None,None,None if matrix_vecs is not None: if tensor_data is not None:", "-> Tuple[List[str],np.ndarray,Tuple[int,int]]: shape = (len(vecs),len(feats_per_vec)) if row_wise else (len(feats_per_vec),len(vecs)) lookup,missing = np.zeros(shape, dtype=np.array(feats).dtype),np.zeros(shape,", "shuffle=True) folds = kf.split(X=df, y=df[strat_key]) for fold_idx, (_, fold) in enumerate(folds): print(f\"Saving fold", "will be replaced with NaN. matrix_row_wise: whether objects encoded as a matrix should", "to the foldfile's metadata. tensor_is_sparse: Set to True if the matrix is in", "is requested. This is ambiguous. Please only set one of the other.\") lookup,missing,shape", "tensor_data:Optional[np.ndarray]=None, tensor_name:Optional[str]=None, tensor_is_sparse:bool=False, compression:Optional[str]=None) -> None: r''' Convert dataframe into h5py file by", "f'{v}_{c}' if f in feats: lookup[i,j] = f else: lookup[i,j] = feats[0] #", "set one of the other.\") mat = df[matrix_lookup].values.astype('float32') mat[:,matrix_missing] = np.NaN mat =", "accessed by a :class:`~lumin.nn.data.fold_yielder.FoldYielder` Arguments: df: Dataframe from which to save data n_folds:", "h5py file to create (.h5py extension not required) targ_type: type of target feature,", "_build_matrix_lookups(df.columns, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) mat_feats = list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data", "data=json.dumps({'present_feats': use, 'vecs': matrix_vecs, 'missing': [int(m) for m in missing], 'feats_per_vec': matrix_feats_per_vec, 'row_wise':", "print(f\"Saving fold {fold_idx} with {len(fold)} events\") fold2foldfile(df.iloc[fold].copy(), out_file, fold_idx, cont_feats=cont_feats, cat_feats=cat_feats, targ_feats=targ_feats, targ_type=targ_type,", "of h5py file to create (.h5py extension not required) targ_type: type of target", "'inputs', compression=compression) save_to_grp(df[targ_feats].values.astype(targ_type), grp, 'targets', compression=compression) if wgt_feat is not None: if wgt_feat", "weights matrix_vecs: list of objects for matrix encoding, i.e. feature prefixes matrix_feats_per_vec: list", "replaced with NaN. matrix_row_wise: whether objects encoded as a matrix should be encoded", "in missing], 'feats_per_vec': matrix_feats_per_vec, 'row_wise': matrix_row_wise, 'shape': shape})) elif tensor_name is not None:", "the user from having to manually pass lists of features. Arguments: out_file: h5py", "length of the data frame. tensor_name: if `tensor_data` is set, then this is", "typing import List, Union, Optional, Any, Tuple, Dict import os from pathlib import", "add_meta_data(out_file:h5py.File, feats:List[str], cont_feats:List[str], cat_feats:List[str], cat_maps:Optional[Dict[str,Dict[int,Any]]], targ_feats:Union[str,List[str]], wgt_feat:Optional[str]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_name:Optional[str]=None, tensor_shp:Optional[Tuple[int]]=None, tensor_is_sparse:bool=False)", "list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': use, 'vecs': matrix_vecs, 'missing':", "save wgt_feat: column to save as data weights matrix_vecs: list of objects for", "the tensor passed to `tensor_data`. compression: optional compression argument for h5py, e.g. 'lzf'", "f = f'{v}_{c}' if f in feats: lookup[i,j] = f else: lookup[i,j] =", "not in ['object', 'str864'] else arr.astype('S64'), compression=compression) def _build_matrix_lookups(feats:List[str], vecs:List[str], feats_per_vec:List[str], row_wise:bool) ->", "= [f for f in cont_feats if f in mat_feats] if len(dup) >", "requested. This is ambiguous. Please only set one of the other.\") mat =", "compression: optional compression argument for h5py, e.g. 'lzf' ''' savename = str(savename) os.system(f'rm", "in df to save as continuous variables cat_feats: list of columns in df", "print(f'{strat_key} not found in DataFrame') strat_key = None if strat_key is None: kf", "in df will be replaced with NaN. matrix_row_wise: whether objects encoded as a", "fold2foldfile(df:pd.DataFrame, out_file:h5py.File, fold_idx:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], targ_type:Any, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, matrix_lookup:Optional[List[str]]=None, matrix_missing:Optional[np.ndarray]=None, matrix_shape:Optional[Tuple[int,int]]=None, tensor_data:Optional[np.ndarray]=None,", "compression=compression) elif tensor_data is not None: save_to_grp(tensor_data.astype('float32'), grp, 'matrix_inputs', compression=compression) def df2foldfile(df:pd.DataFrame, n_folds:int,", "found in DataFrame') strat_key = None if strat_key is None: kf = KFold(n_splits=n_folds,", "e.g. 'lzf' ''' # TODO Option for string length grp.create_dataset(name, shape=arr.shape, dtype=arr.dtype.name if", "the length of the data frame. compression: optional compression argument for h5py, e.g.", "savename:Union[Path,str], targ_type:str, strat_key:Optional[str]=None, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, cat_maps:Optional[Dict[str,Dict[int,Any]]]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_data:Optional[np.ndarray]=None, tensor_name:Optional[str]=None, tensor_is_sparse:bool=False, compression:Optional[str]=None)", "into sub-folds to be accessed by a :class:`~lumin.nn.data.fold_yielder.FoldYielder` Arguments: df: Dataframe from which", "not required) targ_type: type of target feature, e.g. int,'float32' strat_key: column to use", "TODO Option for string length grp.create_dataset(name, shape=arr.shape, dtype=arr.dtype.name if arr.dtype.name not in ['object',", "to save as target feature(s) savename: name of h5py file to create (.h5py", "'lzf' ''' savename = str(savename) os.system(f'rm {savename}.hdf5') os.makedirs(savename[:savename.rfind('/')], exist_ok=True) out_file = h5py.File(f'{savename}.hdf5', \"w\")", "r''' Save Numpy array as a dataset in an h5py Group Arguments: arr:", "grp.create_dataset('cont_feats', data=json.dumps(cont_feats)) grp.create_dataset('cat_feats', data=json.dumps(cat_feats)) grp.create_dataset('targ_feats', data=json.dumps(targ_feats)) if wgt_feat is not None: grp.create_dataset('wgt_feat', data=json.dumps(wgt_feat))", "None, compression=compression) add_meta_data(out_file=out_file, feats=df.columns, cont_feats=cont_feats, cat_feats=cat_feats, cat_maps=cat_maps, targ_feats=targ_feats, wgt_feat=wgt_feat, matrix_vecs=matrix_vecs, matrix_feats_per_vec=matrix_feats_per_vec, matrix_row_wise=matrix_row_wise, tensor_name=tensor_name,", "not found in file') if misc_feats is not None: for f in misc_feats:", "feature(s) savename: name of h5py file to create (.h5py extension not required) targ_type:", "the array must be compatible with the length of the data frame. compression:", "cat_feats: list of columns in df to save as discreet variables targ_feats: (list", "found in file') if misc_feats is not None: for f in misc_feats: if", "information tensor_shp: The shape of the tensor data (exclusing batch dimension) tensor_is_sparse: Whether", "for i, c in enumerate(feats_per_vec): f = f'{v}_{c}' if f in feats: lookup[i,j]", "order than a matrix can be passed directly as a numpy array, rather", "fold_idx: ID for the fold; used name h5py group according to 'fold_{fold_idx}' cont_feats:", "is ambiguous. Please only set one of the other.\") mat = df[matrix_lookup].values.astype('float32') mat[:,matrix_missing]", "on The format expected is `coo_x = sparse.as_coo(x); m = np.vstack((coo_x.data, coo_x.coords))`, where", "in df.columns: save_to_grp(df[f].values, grp, f, compression=compression) else: print(f'{f} not found in file') if", "out_file:h5py.File, fold_idx:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], targ_type:Any, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, matrix_lookup:Optional[List[str]]=None, matrix_missing:Optional[np.ndarray]=None, matrix_shape:Optional[Tuple[int,int]]=None, tensor_data:Optional[np.ndarray]=None, compression:Optional[str]=None)", "cat_feats:List[str], targ_feats:Union[str,List[str]], targ_type:Any, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, matrix_lookup:Optional[List[str]]=None, matrix_missing:Optional[np.ndarray]=None, matrix_shape:Optional[Tuple[int,int]]=None, tensor_data:Optional[np.ndarray]=None, compression:Optional[str]=None) -> None: r'''", "dictionary mapping codes to categories targ_feats: (list of) target feature(s) wgt_feat: name of", "is not None: raise ValueError(\"The saving of both matrix and tensor data is", "f else: lookup[i,j] = feats[0] # Temp value, to be set to null", "of both matrix and tensor data is requested. This is ambiguous. Please only", "from having to manually pass lists of features. Arguments: out_file: h5py file to", "name: name of dataset to create compression: optional compression argument for h5py, e.g.", "grp: group in which to save arr name: name of dataset to create", "dimension) tensor_is_sparse: Whether the tensor is sparse (COO format) and should be densified", "features. Arguments: out_file: h5py file to save data in feats: list of all", "matrix_row_wise: whether objects encoded as a matrix should be encoded row-wise (i.e. all", "if f in df.columns: save_to_grp(df[f].values, grp, f, compression=compression) else: print(f'{f} not found in", "in data grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': use, 'vecs': matrix_vecs, 'missing': [int(m) for m in missing],", "set one of the other.\") lookup,missing,shape = _build_matrix_lookups(df.columns, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) mat_feats =", "`matrix_lookup`, `matrix_missing`, and `matrix_shape`. The first dimension of the array must be compatible", "null later using missing missing[i,j] = True else: for j, v in enumerate(vecs):", "save as target feature(s) savename: name of h5py file to create (.h5py extension", "save_to_grp(arr:np.ndarray, grp:h5py.Group, name:str, compression:Optional[str]=None) -> None: r''' Save Numpy array as a dataset", "else 'S64', data=arr if arr.dtype.name not in ['object', 'str864'] else arr.astype('S64'), compression=compression) def", "m in missing], 'feats_per_vec': matrix_feats_per_vec, 'row_wise': matrix_row_wise, 'shape': shape})) elif tensor_name is not", "Save Numpy array as a dataset in an h5py Group Arguments: arr: array", "int,'float32' strat_key: column to use for stratified splitting misc_feats: any extra columns to", "= f'{v}_{c}' if f in feats: lookup[i,j] = f else: lookup[i,j] = feats[0]", "batch dimension) tensor_is_sparse: Whether the tensor is sparse (COO format) and should be", "compression=compression) if wgt_feat is not None: if wgt_feat in df.columns: save_to_grp(df[wgt_feat].values.astype('float32'), grp, 'weights',", "to save wgt_feat: column to save as data weights matrix_vecs: list of objects", "for the fold; used name h5py group according to 'fold_{fold_idx}' cont_feats: list of", "an object are in their own column) tensor_name: Name used to refer to", "h5py import numpy as np import pandas as pd from typing import List,", "from pathlib import Path import json from sklearn.model_selection import StratifiedKFold, KFold __all__ =", "tensor_is_sparse:bool=False, compression:Optional[str]=None) -> None: r''' Convert dataframe into h5py file by splitting data", "h5py file to save data in feats: list of all features in data", "own row), or column-wise (i.e. all the features associated with an object are", "matrix_feats_per_vec, 'row_wise': matrix_row_wise, 'shape': shape})) elif tensor_name is not None: grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': [tensor_name],", "row), or column-wise (i.e. all the features associated with an object are in", "(len(vecs),len(feats_per_vec)) if row_wise else (len(feats_per_vec),len(vecs)) lookup,missing = np.zeros(shape, dtype=np.array(feats).dtype),np.zeros(shape, dtype=np.bool) if row_wise: for", "cont_feats if f not in dup] if strat_key is not None and strat_key", "tensor data (exclusing batch dimension) tensor_is_sparse: Whether the tensor is sparse (COO format)", "else: lookup[i,j] = feats[0] # Temp value, to be set to null later", "format and should be densified later on The format expected is `coo_x =", "mat_feats = list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data dup = [f for", "def df2foldfile(df:pd.DataFrame, n_folds:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], savename:Union[Path,str], targ_type:str, strat_key:Optional[str]=None, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, cat_maps:Optional[Dict[str,Dict[int,Any]]]=None, matrix_vecs:Optional[List[str]]=None,", "misc_feats: any extra columns to save wgt_feat: column to save as data weights", "for matrix encoding, i.e. feature prefixes matrix_feats_per_vec: list of features per vector for", "features') cont_feats = [f for f in cont_feats if f not in dup]", "not None and strat_key not in df.columns: print(f'{strat_key} not found in DataFrame') strat_key", "f not in dup] if strat_key is not None and strat_key not in", "to 'fold_{fold_idx}' cont_feats: list of columns in df to save as continuous variables", "the fold; used name h5py group according to 'fold_{fold_idx}' cont_feats: list of columns", "as a matrix should be encoded row-wise (i.e. all the features associated with", "The array will be saved under matrix data, and this is incompatible with", "and this is incompatible with also setting `matrix_lookup`, `matrix_missing`, and `matrix_shape`. The first", "= np.NaN mat = mat.reshape((len(df),*matrix_shape)) save_to_grp(mat, grp, 'matrix_inputs', compression=compression) elif tensor_data is not", "to save wgt_feat: column to save as data weights cat_maps: Dictionary mapping categorical", "a :class:`~lumin.nn.data.fold_yielder.FoldYielder` Arguments: df: Dataframe from which to save data n_folds: number of", "mapping codes to categories matrix_vecs: list of objects for matrix encoding, i.e. feature", "be set to null later using missing missing[i,j] = True return list(lookup.flatten()),missing.flatten(),shape def", "in DataFrame') strat_key = None if strat_key is None: kf = KFold(n_splits=n_folds, shuffle=True)", "whether objects encoded as a matrix should be encoded row-wise (i.e. all the", "name:str, compression:Optional[str]=None) -> None: r''' Save Numpy array as a dataset in an", "features per vector for matrix encoding, i.e. feature suffixes. Features listed but not", "None: if wgt_feat in df.columns: save_to_grp(df[wgt_feat].values.astype('float32'), grp, 'weights', compression=compression) else: print(f'{wgt_feat} not found", "name h5py group according to 'fold_{fold_idx}' cont_feats: list of columns in df to", "not None: raise ValueError(\"The saving of both matrix and tensor data is requested.", "if len(dup) > 1: print(f'{dup} present in both matrix features and continuous features;", "df: Dataframe from which to save data n_folds: number of folds to split", "fold_idx:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], targ_type:Any, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, matrix_lookup:Optional[List[str]]=None, matrix_missing:Optional[np.ndarray]=None, matrix_shape:Optional[Tuple[int,int]]=None, tensor_data:Optional[np.ndarray]=None, compression:Optional[str]=None) ->", "tensor_data is not None: raise ValueError(\"The saving of both matrix and tensor data", "i, v in enumerate(vecs): for j, c in enumerate(feats_per_vec): f = f'{v}_{c}' if", "out_file, fold_idx, cont_feats=cont_feats, cat_feats=cat_feats, targ_feats=targ_feats, targ_type=targ_type, misc_feats=misc_feats, wgt_feat=wgt_feat, matrix_lookup=lookup, matrix_missing=missing, matrix_shape=shape, tensor_data=tensor_data[fold] if", "name that will to the foldfile's metadata. tensor_is_sparse: Set to True if the", "to the tensor when displaying model information tensor_shp: The shape of the tensor", "is ambiguous. Please only set one of the other.\") lookup,missing,shape = _build_matrix_lookups(df.columns, matrix_vecs,", "import Path import json from sklearn.model_selection import StratifiedKFold, KFold __all__ = ['save_to_grp', 'fold2foldfile',", "dataset to create compression: optional compression argument for h5py, e.g. 'lzf' ''' #", "to create compression: optional compression argument for h5py, e.g. 'lzf' ''' # TODO", "is incompatible with also setting `matrix_lookup`, `matrix_missing`, and `matrix_shape`. The first dimension of", "compression:Optional[str]=None) -> None: r''' Save Numpy array as a dataset in an h5py", "not None: grp.create_dataset('cat_maps', data=json.dumps(cat_maps)) if matrix_vecs is not None: lookup,missing,shape = _build_matrix_lookups(feats, matrix_vecs,", "fold2foldfile(df.iloc[fold].copy(), out_file, fold_idx, cont_feats=cont_feats, cat_feats=cat_feats, targ_feats=targ_feats, targ_type=targ_type, misc_feats=misc_feats, wgt_feat=wgt_feat, matrix_lookup=lookup, matrix_missing=missing, matrix_shape=shape, tensor_data=tensor_data[fold]", "objects encoded as a matrix should be encoded row-wise (i.e. all the features", "in mat_feats] if len(dup) > 1: print(f'{dup} present in both matrix features and", "lookup[i,j] = f else: lookup[i,j] = feats[0] # Temp value, to be set", "cat_maps:Optional[Dict[str,Dict[int,Any]]], targ_feats:Union[str,List[str]], wgt_feat:Optional[str]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_name:Optional[str]=None, tensor_shp:Optional[Tuple[int]]=None, tensor_is_sparse:bool=False) -> None: r''' Adds", "is not None: grp.create_dataset('wgt_feat', data=json.dumps(wgt_feat)) if cat_maps is not None: grp.create_dataset('cat_maps', data=json.dumps(cat_maps)) if", "cat_maps=cat_maps, targ_feats=targ_feats, wgt_feat=wgt_feat, matrix_vecs=matrix_vecs, matrix_feats_per_vec=matrix_feats_per_vec, matrix_row_wise=matrix_row_wise, tensor_name=tensor_name, tensor_shp=tensor_data[0].shape if tensor_data is not None", "row_wise else (len(feats_per_vec),len(vecs)) lookup,missing = np.zeros(shape, dtype=np.array(feats).dtype),np.zeros(shape, dtype=np.bool) if row_wise: for i, v", "sklearn.model_selection import StratifiedKFold, KFold __all__ = ['save_to_grp', 'fold2foldfile', 'df2foldfile', 'add_meta_data'] def save_to_grp(arr:np.ndarray, grp:h5py.Group,", "else: for j, v in enumerate(vecs): for i, c in enumerate(feats_per_vec): f =", "saving of both matrix and tensor data is requested. This is ambiguous. Please", "string length grp.create_dataset(name, shape=arr.shape, dtype=arr.dtype.name if arr.dtype.name not in ['object', 'str864'] else 'S64',", "matrix_feats_per_vec, matrix_row_wise) use = list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data grp.create_dataset('matrix_feats', data=json.dumps({'present_feats':", "The shape of the tensor data (exclusing batch dimension) tensor_is_sparse: Whether the tensor", "encoded row-wise (i.e. all the features associated with an object are in their", "df.columns: save_to_grp(df[f].values, grp, f, compression=compression) else: print(f'{f} not found in file') if matrix_lookup", "object are in their own column) tensor_name: Name used to refer to the", "print(f'{wgt_feat} not found in file') if misc_feats is not None: for f in", "be saved under matrix data, and this is incompatible with also setting `matrix_vecs`,", "'str864'] else arr.astype('S64'), compression=compression) def _build_matrix_lookups(feats:List[str], vecs:List[str], feats_per_vec:List[str], row_wise:bool) -> Tuple[List[str],np.ndarray,Tuple[int,int]]: shape =", "if cat_maps is not None: grp.create_dataset('cat_maps', data=json.dumps(cat_maps)) if matrix_vecs is not None: lookup,missing,shape", "the features associated with an object are in their own row), or column-wise", "matrix_vecs is not None: if tensor_data is not None: raise ValueError(\"The saving of", "if strat_key is None: kf = KFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df) else: kf", "tensor_is_sparse: Set to True if the matrix is in sparse COO format and", "from continuous features') cont_feats = [f for f in cont_feats if f not", "data into an h5py Group Arguments: df: Dataframe from which to save data", "['object', 'str864'] else arr.astype('S64'), compression=compression) def _build_matrix_lookups(feats:List[str], vecs:List[str], feats_per_vec:List[str], row_wise:bool) -> Tuple[List[str],np.ndarray,Tuple[int,int]]: shape", "def save_to_grp(arr:np.ndarray, grp:h5py.Group, name:str, compression:Optional[str]=None) -> None: r''' Save Numpy array as a", "variables targ_feats: (list of) column(s) in df to save as target feature(s) targ_type:", "_build_matrix_lookups(feats:List[str], vecs:List[str], feats_per_vec:List[str], row_wise:bool) -> Tuple[List[str],np.ndarray,Tuple[int,int]]: shape = (len(vecs),len(feats_per_vec)) if row_wise else (len(feats_per_vec),len(vecs))", "wgt_feat: column to save as data weights matrix_vecs: list of objects for matrix", "# TODO Option for string length grp.create_dataset(name, shape=arr.shape, dtype=arr.dtype.name if arr.dtype.name not in", "Convert dataframe into h5py file by splitting data into sub-folds to be accessed", "type of target feature, e.g. int,'float32' misc_feats: any extra columns to save wgt_feat:", "n_folds: number of folds to split df into cont_feats: list of columns in", "list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data dup = [f for f in", "cont_feats=cont_feats, cat_feats=cat_feats, cat_maps=cat_maps, targ_feats=targ_feats, wgt_feat=wgt_feat, matrix_vecs=matrix_vecs, matrix_feats_per_vec=matrix_feats_per_vec, matrix_row_wise=matrix_row_wise, tensor_name=tensor_name, tensor_shp=tensor_data[0].shape if tensor_data is", "pandas as pd from typing import List, Union, Optional, Any, Tuple, Dict import", "-> None: r''' Convert dataframe into h5py file by splitting data into sub-folds", "StratifiedKFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df, y=df[strat_key]) for fold_idx, (_, fold) in enumerate(folds): print(f\"Saving", "data to foldfile containing information about the data: feature names, matrix information, etc.", "of weight feature matrix_vecs: list of objects for matrix encoding, i.e. feature prefixes", "j, v in enumerate(vecs): for i, c in enumerate(feats_per_vec): f = f'{v}_{c}' if", "in enumerate(vecs): for i, c in enumerate(feats_per_vec): f = f'{v}_{c}' if f in", "kf.split(X=df, y=df[strat_key]) for fold_idx, (_, fold) in enumerate(folds): print(f\"Saving fold {fold_idx} with {len(fold)}", "in enumerate(folds): print(f\"Saving fold {fold_idx} with {len(fold)} events\") fold2foldfile(df.iloc[fold].copy(), out_file, fold_idx, cont_feats=cont_feats, cat_feats=cat_feats,", "'shape': shape})) elif tensor_name is not None: grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': [tensor_name], 'vecs': [tensor_name], 'missing':", "their own column) tensor_name: Name used to refer to the tensor when displaying", "= None if strat_key is None: kf = KFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df)", "kf = StratifiedKFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df, y=df[strat_key]) for fold_idx, (_, fold) in", "grp.create_dataset(name, shape=arr.shape, dtype=arr.dtype.name if arr.dtype.name not in ['object', 'str864'] else 'S64', data=arr if", "be compatible with the length of the data frame. tensor_name: if `tensor_data` is", "folds = kf.split(X=df, y=df[strat_key]) for fold_idx, (_, fold) in enumerate(folds): print(f\"Saving fold {fold_idx}", "is not None: grp.create_dataset('cat_maps', data=json.dumps(cat_maps)) if matrix_vecs is not None: lookup,missing,shape = _build_matrix_lookups(feats,", "data of higher order than a matrix can be passed directly as a", "Tuple[List[str],np.ndarray,Tuple[int,int]]: shape = (len(vecs),len(feats_per_vec)) if row_wise else (len(feats_per_vec),len(vecs)) lookup,missing = np.zeros(shape, dtype=np.array(feats).dtype),np.zeros(shape, dtype=np.bool)", "df to save as target feature(s) savename: name of h5py file to create", "user from having to manually pass lists of features. Arguments: out_file: h5py file", "target feature, e.g. int,'float32' strat_key: column to use for stratified splitting misc_feats: any", "'weights', compression=compression) else: print(f'{wgt_feat} not found in file') if misc_feats is not None:", "os.makedirs(savename[:savename.rfind('/')], exist_ok=True) out_file = h5py.File(f'{savename}.hdf5', \"w\") lookup,missing,shape = None,None,None if matrix_vecs is not", "-> None: r''' Save Numpy array as a dataset in an h5py Group", "list(lookup.flatten()),missing.flatten(),shape def fold2foldfile(df:pd.DataFrame, out_file:h5py.File, fold_idx:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], targ_type:Any, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, matrix_lookup:Optional[List[str]]=None, matrix_missing:Optional[np.ndarray]=None,", "an h5py Group Arguments: df: Dataframe from which to save data out_file: h5py", "for j, v in enumerate(vecs): for i, c in enumerate(feats_per_vec): f = f'{v}_{c}'", "their own row), or column-wise (i.e. all the features associated with an object", "save data in feats: list of all features in data cont_feats: list of", "matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_name:Optional[str]=None, tensor_shp:Optional[Tuple[int]]=None, tensor_is_sparse:bool=False) -> None: r''' Adds meta data to", "fold of data into an h5py Group Arguments: df: Dataframe from which to", "None: kf = KFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df) else: kf = StratifiedKFold(n_splits=n_folds, shuffle=True)", "the DataFrame. The array will be saved under matrix data, and this is", "targ_type: type of target feature, e.g. int,'float32' strat_key: column to use for stratified", "sparse (COO format) and should be densified prior to use ''' grp =", "categorical features to dictionary mapping codes to categories matrix_vecs: list of objects for", "missing[i,j] = True return list(lookup.flatten()),missing.flatten(),shape def fold2foldfile(df:pd.DataFrame, out_file:h5py.File, fold_idx:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], targ_type:Any,", "targ_type:Any, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, matrix_lookup:Optional[List[str]]=None, matrix_missing:Optional[np.ndarray]=None, matrix_shape:Optional[Tuple[int,int]]=None, tensor_data:Optional[np.ndarray]=None, compression:Optional[str]=None) -> None: r''' Save fold", "if wgt_feat in df.columns: save_to_grp(df[wgt_feat].values.astype('float32'), grp, 'weights', compression=compression) else: print(f'{wgt_feat} not found in", "number of folds to split df into cont_feats: list of columns in df", "to null later using missing missing[i,j] = True return list(lookup.flatten()),missing.flatten(),shape def fold2foldfile(df:pd.DataFrame, out_file:h5py.File,", "infer target type automatically grp = out_file.create_group(f'fold_{fold_idx}') save_to_grp(np.hstack((df[cont_feats].values.astype('float32'), df[cat_feats].values.astype('float32'))), grp, 'inputs', compression=compression) save_to_grp(df[targ_feats].values.astype(targ_type),", "folds to split df into cont_feats: list of columns in df to save", "manually pass lists of features. Arguments: out_file: h5py file to save data in", "np import pandas as pd from typing import List, Union, Optional, Any, Tuple,", "compression:Optional[str]=None) -> None: r''' Convert dataframe into h5py file by splitting data into", "= df[matrix_lookup].values.astype('float32') mat[:,matrix_missing] = np.NaN mat = mat.reshape((len(df),*matrix_shape)) save_to_grp(mat, grp, 'matrix_inputs', compression=compression) elif", "saved under matrix data, and this is incompatible with also setting `matrix_lookup`, `matrix_missing`,", "ID for the fold; used name h5py group according to 'fold_{fold_idx}' cont_feats: list", "`tensor_data`. compression: optional compression argument for h5py, e.g. 'lzf' ''' savename = str(savename)", "'fold_{fold_idx}' cont_feats: list of columns in df to save as continuous variables cat_feats:", "feature(s) targ_type: type of target feature, e.g. int,'float32' misc_feats: any extra columns to", "using missing missing[i,j] = True return list(lookup.flatten()),missing.flatten(),shape def fold2foldfile(df:pd.DataFrame, out_file:h5py.File, fold_idx:int, cont_feats:List[str], cat_feats:List[str],", "(i.e. all the features associated with an object are in their own column)", "cat_feats:List[str], cat_maps:Optional[Dict[str,Dict[int,Any]]], targ_feats:Union[str,List[str]], wgt_feat:Optional[str]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_name:Optional[str]=None, tensor_shp:Optional[Tuple[int]]=None, tensor_is_sparse:bool=False) -> None: r'''", "encoding, i.e. feature prefixes matrix_feats_per_vec: list of features per vector for matrix encoding,", "mat_feats] if len(dup) > 1: print(f'{dup} present in both matrix features and continuous", "about the data: feature names, matrix information, etc. :class:`~lumin.nn.data.fold_yielder.FoldYielder` objects will access this", "Whether the tensor is sparse (COO format) and should be densified prior to", "dictionary mapping codes to categories matrix_vecs: list of objects for matrix encoding, i.e.", "# Only features present in data grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': use, 'vecs': matrix_vecs, 'missing': [int(m)", "not None: for f in misc_feats: if f in df.columns: save_to_grp(df[f].values, grp, f,", "the data frame. tensor_name: if `tensor_data` is set, then this is the name", "of categorical features cat_maps: Dictionary mapping categorical features to dictionary mapping codes to", "mat[:,matrix_missing] = np.NaN mat = mat.reshape((len(df),*matrix_shape)) save_to_grp(mat, grp, 'matrix_inputs', compression=compression) elif tensor_data is", "Dict import os from pathlib import Path import json from sklearn.model_selection import StratifiedKFold,", "for j, c in enumerate(feats_per_vec): f = f'{v}_{c}' if f in feats: lookup[i,j]", "shuffle=True) folds = kf.split(X=df) else: kf = StratifiedKFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df, y=df[strat_key])", "save_to_grp(tensor_data.astype('float32'), grp, 'matrix_inputs', compression=compression) def df2foldfile(df:pd.DataFrame, n_folds:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], savename:Union[Path,str], targ_type:str, strat_key:Optional[str]=None,", "is the tensor passed to `tensor_data`. compression: optional compression argument for h5py, e.g.", "array must be compatible with the length of the data frame. compression: optional", "savename: name of h5py file to create (.h5py extension not required) targ_type: type", "matrix data, and this is incompatible with also setting `matrix_vecs`, `matrix_feats_per_vec`, and `matrix_row_wise`.", "column) tensor_name: Name used to refer to the tensor when displaying model information", "to save data in fold_idx: ID for the fold; used name h5py group", "from sklearn.model_selection import StratifiedKFold, KFold __all__ = ['save_to_grp', 'fold2foldfile', 'df2foldfile', 'add_meta_data'] def save_to_grp(arr:np.ndarray,", "-> None: r''' Save fold of data into an h5py Group Arguments: df:", "in fold_idx: ID for the fold; used name h5py group according to 'fold_{fold_idx}'", "shape of the tensor data (exclusing batch dimension) tensor_is_sparse: Whether the tensor is", "any extra columns to save wgt_feat: column to save as data weights matrix_vecs:", "Union, Optional, Any, Tuple, Dict import os from pathlib import Path import json", "KFold __all__ = ['save_to_grp', 'fold2foldfile', 'df2foldfile', 'add_meta_data'] def save_to_grp(arr:np.ndarray, grp:h5py.Group, name:str, compression:Optional[str]=None) ->", "the data frame. compression: optional compression argument for h5py, e.g. 'lzf' ''' #", "Dataframe from which to save data n_folds: number of folds to split df", "which to save data n_folds: number of folds to split df into cont_feats:", "tensor_name:Optional[str]=None, tensor_is_sparse:bool=False, compression:Optional[str]=None) -> None: r''' Convert dataframe into h5py file by splitting", "data frame. tensor_name: if `tensor_data` is set, then this is the name that", "in cont_feats if f not in dup] if strat_key is not None and", "is not None: lookup,missing,shape = _build_matrix_lookups(feats, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) use = list(np.array(lookup)[np.logical_not(missing)]) #", "strat_key: column to use for stratified splitting misc_feats: any extra columns to save", "for f in misc_feats: if f in df.columns: save_to_grp(df[f].values, grp, f, compression=compression) else:", "matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_data:Optional[np.ndarray]=None, tensor_name:Optional[str]=None, tensor_is_sparse:bool=False, compression:Optional[str]=None) -> None: r''' Convert dataframe into", "continuous features cat_feats: list of categorical features cat_maps: Dictionary mapping categorical features to", "wgt_feat is not None: if wgt_feat in df.columns: save_to_grp(df[wgt_feat].values.astype('float32'), grp, 'weights', compression=compression) else:", "'str864'] else 'S64', data=arr if arr.dtype.name not in ['object', 'str864'] else arr.astype('S64'), compression=compression)", "data weights matrix_vecs: list of objects for matrix encoding, i.e. feature prefixes matrix_feats_per_vec:", "then this is the name that will to the foldfile's metadata. tensor_is_sparse: Set", "strat_key is not None and strat_key not in df.columns: print(f'{strat_key} not found in", "found in file') if matrix_lookup is not None: if tensor_data is not None:", "extension not required) targ_type: type of target feature, e.g. int,'float32' strat_key: column to", "is not None else None, tensor_is_sparse=tensor_is_sparse) def add_meta_data(out_file:h5py.File, feats:List[str], cont_feats:List[str], cat_feats:List[str], cat_maps:Optional[Dict[str,Dict[int,Any]]], targ_feats:Union[str,List[str]],", "enumerate(folds): print(f\"Saving fold {fold_idx} with {len(fold)} events\") fold2foldfile(df.iloc[fold].copy(), out_file, fold_idx, cont_feats=cont_feats, cat_feats=cat_feats, targ_feats=targ_feats,", "List, Union, Optional, Any, Tuple, Dict import os from pathlib import Path import", "''' grp = out_file.create_group('meta_data') grp.create_dataset('cont_feats', data=json.dumps(cont_feats)) grp.create_dataset('cat_feats', data=json.dumps(cat_feats)) grp.create_dataset('targ_feats', data=json.dumps(targ_feats)) if wgt_feat is", "of columns in df to save as continuous variables cat_feats: list of columns", "to save as data weights matrix_vecs: list of objects for matrix encoding, i.e.", "compression argument for h5py, e.g. 'lzf' ''' savename = str(savename) os.system(f'rm {savename}.hdf5') os.makedirs(savename[:savename.rfind('/')],", "pass lists of features. Arguments: out_file: h5py file to save data in feats:", "model information tensor_shp: The shape of the tensor data (exclusing batch dimension) tensor_is_sparse:", "Path import json from sklearn.model_selection import StratifiedKFold, KFold __all__ = ['save_to_grp', 'fold2foldfile', 'df2foldfile',", "to foldfile containing information about the data: feature names, matrix information, etc. :class:`~lumin.nn.data.fold_yielder.FoldYielder`", "to dictionary mapping codes to categories targ_feats: (list of) target feature(s) wgt_feat: name", "list of features per vector for matrix encoding, i.e. feature suffixes. Features listed", "of higher order than a matrix can be passed directly as a numpy", "add_meta_data(out_file=out_file, feats=df.columns, cont_feats=cont_feats, cat_feats=cat_feats, cat_maps=cat_maps, targ_feats=targ_feats, wgt_feat=wgt_feat, matrix_vecs=matrix_vecs, matrix_feats_per_vec=matrix_feats_per_vec, matrix_row_wise=matrix_row_wise, tensor_name=tensor_name, tensor_shp=tensor_data[0].shape if", "'S64', data=arr if arr.dtype.name not in ['object', 'str864'] else arr.astype('S64'), compression=compression) def _build_matrix_lookups(feats:List[str],", "(list of) target feature(s) wgt_feat: name of weight feature matrix_vecs: list of objects", "matrix_row_wise, 'shape': shape})) elif tensor_name is not None: grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': [tensor_name], 'vecs': [tensor_name],", "= KFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df) else: kf = StratifiedKFold(n_splits=n_folds, shuffle=True) folds =", "None: save_to_grp(tensor_data.astype('float32'), grp, 'matrix_inputs', compression=compression) def df2foldfile(df:pd.DataFrame, n_folds:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], savename:Union[Path,str], targ_type:str,", "wgt_feat: column to save as data weights cat_maps: Dictionary mapping categorical features to", "categorical features cat_maps: Dictionary mapping categorical features to dictionary mapping codes to categories", "matrix_feats_per_vec: list of features per vector for matrix encoding, i.e. feature suffixes. Features", "if wgt_feat is not None: grp.create_dataset('wgt_feat', data=json.dumps(wgt_feat)) if cat_maps is not None: grp.create_dataset('cat_maps',", "are in their own row), or column-wise (i.e. all the features associated with", "`matrix_vecs`, `matrix_feats_per_vec`, and `matrix_row_wise`. The first dimension of the array must be compatible", "is not None: save_to_grp(tensor_data.astype('float32'), grp, 'matrix_inputs', compression=compression) def df2foldfile(df:pd.DataFrame, n_folds:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]],", "events\") fold2foldfile(df.iloc[fold].copy(), out_file, fold_idx, cont_feats=cont_feats, cat_feats=cat_feats, targ_feats=targ_feats, targ_type=targ_type, misc_feats=misc_feats, wgt_feat=wgt_feat, matrix_lookup=lookup, matrix_missing=missing, matrix_shape=shape,", "as target feature(s) targ_type: type of target feature, e.g. int,'float32' misc_feats: any extra", "= np.vstack((coo_x.data, coo_x.coords))`, where `m` is the tensor passed to `tensor_data`. compression: optional", "cat_maps: Dictionary mapping categorical features to dictionary mapping codes to categories targ_feats: (list", "compression: optional compression argument for h5py, e.g. 'lzf' ''' # TODO Option for", "array, rather than beign extracted and reshaped from the DataFrame. The array will", "json from sklearn.model_selection import StratifiedKFold, KFold __all__ = ['save_to_grp', 'fold2foldfile', 'df2foldfile', 'add_meta_data'] def", "matrix_lookup:Optional[List[str]]=None, matrix_missing:Optional[np.ndarray]=None, matrix_shape:Optional[Tuple[int,int]]=None, tensor_data:Optional[np.ndarray]=None, compression:Optional[str]=None) -> None: r''' Save fold of data into", "encoding, i.e. feature suffixes. Features listed but not present in df will be", "print(f'{dup} present in both matrix features and continuous features; removing from continuous features')", "tensor when displaying model information tensor_shp: The shape of the tensor data (exclusing", "their own column) tensor_data: data of higher order than a matrix can be", "raise ValueError(\"The saving of both matrix and tensor data is requested. This is", "if row_wise else (len(feats_per_vec),len(vecs)) lookup,missing = np.zeros(shape, dtype=np.array(feats).dtype),np.zeros(shape, dtype=np.bool) if row_wise: for i,", "Features listed but not present in df will be replaced with NaN. matrix_row_wise:", "lookup,missing,shape = _build_matrix_lookups(df.columns, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) mat_feats = list(np.array(lookup)[np.logical_not(missing)]) # Only features present", "dataset in an h5py Group Arguments: arr: array to be saved grp: group", "cont_feats: list of columns in df to save as continuous variables cat_feats: list", "f in misc_feats: if f in df.columns: save_to_grp(df[f].values, grp, f, compression=compression) else: print(f'{f}", "savename = str(savename) os.system(f'rm {savename}.hdf5') os.makedirs(savename[:savename.rfind('/')], exist_ok=True) out_file = h5py.File(f'{savename}.hdf5', \"w\") lookup,missing,shape =", "array will be saved under matrix data, and this is incompatible with also", "grp, 'matrix_inputs', compression=compression) def df2foldfile(df:pd.DataFrame, n_folds:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], savename:Union[Path,str], targ_type:str, strat_key:Optional[str]=None, misc_feats:Optional[List[str]]=None,", "df.columns: print(f'{strat_key} not found in DataFrame') strat_key = None if strat_key is None:", "targ_type:str, strat_key:Optional[str]=None, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, cat_maps:Optional[Dict[str,Dict[int,Any]]]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_data:Optional[np.ndarray]=None, tensor_name:Optional[str]=None, tensor_is_sparse:bool=False, compression:Optional[str]=None) ->", "in df to save as target feature(s) targ_type: type of target feature, e.g.", "matrix should be encoded row-wise (i.e. all the features associated with an object", "are in their own column) tensor_name: Name used to refer to the tensor", "<gh_stars>10-100 import h5py import numpy as np import pandas as pd from typing", "None if strat_key is None: kf = KFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df) else:", "Set to True if the matrix is in sparse COO format and should", "not in df.columns: print(f'{strat_key} not found in DataFrame') strat_key = None if strat_key", "Please only set one of the other.\") lookup,missing,shape = _build_matrix_lookups(df.columns, matrix_vecs, matrix_feats_per_vec, matrix_row_wise)", "weights cat_maps: Dictionary mapping categorical features to dictionary mapping codes to categories matrix_vecs:", "as a dataset in an h5py Group Arguments: arr: array to be saved", "to save as target feature(s) targ_type: type of target feature, e.g. int,'float32' misc_feats:", "data is requested. This is ambiguous. Please only set one of the other.\")", "compression=compression) def df2foldfile(df:pd.DataFrame, n_folds:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], savename:Union[Path,str], targ_type:str, strat_key:Optional[str]=None, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, cat_maps:Optional[Dict[str,Dict[int,Any]]]=None,", "else: print(f'{wgt_feat} not found in file') if misc_feats is not None: for f", "= [f for f in cont_feats if f not in dup] if strat_key", "categorical features to dictionary mapping codes to categories targ_feats: (list of) target feature(s)", "strat_key = None if strat_key is None: kf = KFold(n_splits=n_folds, shuffle=True) folds =", "in data dup = [f for f in cont_feats if f in mat_feats]", "enumerate(vecs): for j, c in enumerate(feats_per_vec): f = f'{v}_{c}' if f in feats:", "Group Arguments: df: Dataframe from which to save data out_file: h5py file to", "cat_feats:List[str], targ_feats:Union[str,List[str]], savename:Union[Path,str], targ_type:str, strat_key:Optional[str]=None, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, cat_maps:Optional[Dict[str,Dict[int,Any]]]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_data:Optional[np.ndarray]=None, tensor_name:Optional[str]=None,", "[f for f in cont_feats if f in mat_feats] if len(dup) > 1:", "compression argument for h5py, e.g. 'lzf' ''' # TODO Option for string length", "compression=compression) else: print(f'{f} not found in file') if matrix_lookup is not None: if", "of the other.\") mat = df[matrix_lookup].values.astype('float32') mat[:,matrix_missing] = np.NaN mat = mat.reshape((len(df),*matrix_shape)) save_to_grp(mat,", "wgt_feat is not None: grp.create_dataset('wgt_feat', data=json.dumps(wgt_feat)) if cat_maps is not None: grp.create_dataset('cat_maps', data=json.dumps(cat_maps))", "present in df will be replaced with NaN. matrix_row_wise: whether objects encoded as", "__all__ = ['save_to_grp', 'fold2foldfile', 'df2foldfile', 'add_meta_data'] def save_to_grp(arr:np.ndarray, grp:h5py.Group, name:str, compression:Optional[str]=None) -> None:", "variables targ_feats: (list of) column(s) in df to save as target feature(s) savename:", "for m in missing], 'feats_per_vec': matrix_feats_per_vec, 'row_wise': matrix_row_wise, 'shape': shape})) elif tensor_name is", "data: feature names, matrix information, etc. :class:`~lumin.nn.data.fold_yielder.FoldYielder` objects will access this and automatically", "list of continuous features cat_feats: list of categorical features cat_maps: Dictionary mapping categorical", "to save data in feats: list of all features in data cont_feats: list", "(.h5py extension not required) targ_type: type of target feature, e.g. int,'float32' strat_key: column", "vecs:List[str], feats_per_vec:List[str], row_wise:bool) -> Tuple[List[str],np.ndarray,Tuple[int,int]]: shape = (len(vecs),len(feats_per_vec)) if row_wise else (len(feats_per_vec),len(vecs)) lookup,missing", "to save arr name: name of dataset to create compression: optional compression argument", "target feature(s) targ_type: type of target feature, e.g. int,'float32' misc_feats: any extra columns", "of data into an h5py Group Arguments: df: Dataframe from which to save", "prefixes matrix_feats_per_vec: list of features per vector for matrix encoding, i.e. feature suffixes.", "an object are in their own column) tensor_data: data of higher order than", "not None: save_to_grp(tensor_data.astype('float32'), grp, 'matrix_inputs', compression=compression) def df2foldfile(df:pd.DataFrame, n_folds:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], savename:Union[Path,str],", "with the length of the data frame. tensor_name: if `tensor_data` is set, then", "'targets', compression=compression) if wgt_feat is not None: if wgt_feat in df.columns: save_to_grp(df[wgt_feat].values.astype('float32'), grp,", "features; removing from continuous features') cont_feats = [f for f in cont_feats if", "target feature(s) savename: name of h5py file to create (.h5py extension not required)", "associated with an object are in their own row), or column-wise (i.e. all", "'lzf' ''' # TODO Option for string length grp.create_dataset(name, shape=arr.shape, dtype=arr.dtype.name if arr.dtype.name", "automatically extract it to save the user from having to manually pass lists", "be densified prior to use ''' grp = out_file.create_group('meta_data') grp.create_dataset('cont_feats', data=json.dumps(cont_feats)) grp.create_dataset('cat_feats', data=json.dumps(cat_feats))", "is incompatible with also setting `matrix_vecs`, `matrix_feats_per_vec`, and `matrix_row_wise`. The first dimension of", "in file') if misc_feats is not None: for f in misc_feats: if f", "in ['object', 'str864'] else 'S64', data=arr if arr.dtype.name not in ['object', 'str864'] else", "stratified splitting misc_feats: any extra columns to save wgt_feat: column to save as", "matrix_feats_per_vec, matrix_row_wise) mat_feats = list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data dup =", "matrix features and continuous features; removing from continuous features') cont_feats = [f for", "from which to save data out_file: h5py file to save data in fold_idx:", "of columns in df to save as discreet variables targ_feats: (list of) column(s)", "for h5py, e.g. 'lzf' ''' savename = str(savename) os.system(f'rm {savename}.hdf5') os.makedirs(savename[:savename.rfind('/')], exist_ok=True) out_file", "used to refer to the tensor when displaying model information tensor_shp: The shape", "True else: for j, v in enumerate(vecs): for i, c in enumerate(feats_per_vec): f", "own column) tensor_data: data of higher order than a matrix can be passed", "should be densified prior to use ''' grp = out_file.create_group('meta_data') grp.create_dataset('cont_feats', data=json.dumps(cont_feats)) grp.create_dataset('cat_feats',", "grp, 'matrix_inputs', compression=compression) elif tensor_data is not None: save_to_grp(tensor_data.astype('float32'), grp, 'matrix_inputs', compression=compression) def", "cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], savename:Union[Path,str], targ_type:str, strat_key:Optional[str]=None, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, cat_maps:Optional[Dict[str,Dict[int,Any]]]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_data:Optional[np.ndarray]=None,", "compression=compression) add_meta_data(out_file=out_file, feats=df.columns, cont_feats=cont_feats, cat_feats=cat_feats, cat_maps=cat_maps, targ_feats=targ_feats, wgt_feat=wgt_feat, matrix_vecs=matrix_vecs, matrix_feats_per_vec=matrix_feats_per_vec, matrix_row_wise=matrix_row_wise, tensor_name=tensor_name, tensor_shp=tensor_data[0].shape", "save as discreet variables targ_feats: (list of) column(s) in df to save as", "lists of features. Arguments: out_file: h5py file to save data in feats: list", "tensor_is_sparse: Whether the tensor is sparse (COO format) and should be densified prior", "from typing import List, Union, Optional, Any, Tuple, Dict import os from pathlib", "e.g. int,'float32' strat_key: column to use for stratified splitting misc_feats: any extra columns", "of all features in data cont_feats: list of continuous features cat_feats: list of", "Arguments: arr: array to be saved grp: group in which to save arr", "with {len(fold)} events\") fold2foldfile(df.iloc[fold].copy(), out_file, fold_idx, cont_feats=cont_feats, cat_feats=cat_feats, targ_feats=targ_feats, targ_type=targ_type, misc_feats=misc_feats, wgt_feat=wgt_feat, matrix_lookup=lookup,", "= str(savename) os.system(f'rm {savename}.hdf5') os.makedirs(savename[:savename.rfind('/')], exist_ok=True) out_file = h5py.File(f'{savename}.hdf5', \"w\") lookup,missing,shape = None,None,None", "vector for matrix encoding, i.e. feature suffixes. Features listed but not present in", "matrix_vecs: list of objects for matrix encoding, i.e. feature prefixes matrix_feats_per_vec: list of", "`m` is the tensor passed to `tensor_data`. compression: optional compression argument for h5py,", "for h5py, e.g. 'lzf' ''' # TODO infer target type automatically grp =", "foldfile's metadata. tensor_is_sparse: Set to True if the matrix is in sparse COO", "features associated with an object are in their own row), or column-wise (i.e.", "both matrix and tensor data is requested. This is ambiguous. Please only set", "to save data n_folds: number of folds to split df into cont_feats: list", "the other.\") lookup,missing,shape = _build_matrix_lookups(df.columns, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) mat_feats = list(np.array(lookup)[np.logical_not(missing)]) # Only", "The first dimension of the array must be compatible with the length of", "data grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': use, 'vecs': matrix_vecs, 'missing': [int(m) for m in missing], 'feats_per_vec':", "lookup,missing = np.zeros(shape, dtype=np.array(feats).dtype),np.zeros(shape, dtype=np.bool) if row_wise: for i, v in enumerate(vecs): for", "in enumerate(vecs): for j, c in enumerate(feats_per_vec): f = f'{v}_{c}' if f in", "fold_idx, (_, fold) in enumerate(folds): print(f\"Saving fold {fold_idx} with {len(fold)} events\") fold2foldfile(df.iloc[fold].copy(), out_file,", "if tensor_data is not None else None, compression=compression) add_meta_data(out_file=out_file, feats=df.columns, cont_feats=cont_feats, cat_feats=cat_feats, cat_maps=cat_maps,", "feats: lookup[i,j] = f else: lookup[i,j] = feats[0] # Temp value, to be", "this is incompatible with also setting `matrix_vecs`, `matrix_feats_per_vec`, and `matrix_row_wise`. The first dimension", "else: kf = StratifiedKFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df, y=df[strat_key]) for fold_idx, (_, fold)", "and `matrix_row_wise`. The first dimension of the array must be compatible with the", "fold {fold_idx} with {len(fold)} events\") fold2foldfile(df.iloc[fold].copy(), out_file, fold_idx, cont_feats=cont_feats, cat_feats=cat_feats, targ_feats=targ_feats, targ_type=targ_type, misc_feats=misc_feats,", "to refer to the tensor when displaying model information tensor_shp: The shape of", "information about the data: feature names, matrix information, etc. :class:`~lumin.nn.data.fold_yielder.FoldYielder` objects will access", "the foldfile's metadata. tensor_is_sparse: Set to True if the matrix is in sparse", "file') if misc_feats is not None: for f in misc_feats: if f in", "tensor_data: data of higher order than a matrix can be passed directly as", "not None: lookup,missing,shape = _build_matrix_lookups(feats, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) use = list(np.array(lookup)[np.logical_not(missing)]) # Only", "= list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': use, 'vecs': matrix_vecs,", "should be encoded row-wise (i.e. all the features associated with an object are", "[int(m) for m in missing], 'feats_per_vec': matrix_feats_per_vec, 'row_wise': matrix_row_wise, 'shape': shape})) elif tensor_name", "Dictionary mapping categorical features to dictionary mapping codes to categories targ_feats: (list of)", "Save fold of data into an h5py Group Arguments: df: Dataframe from which", "densified later on The format expected is `coo_x = sparse.as_coo(x); m = np.vstack((coo_x.data,", "save wgt_feat: column to save as data weights cat_maps: Dictionary mapping categorical features", "and automatically extract it to save the user from having to manually pass", "= out_file.create_group(f'fold_{fold_idx}') save_to_grp(np.hstack((df[cont_feats].values.astype('float32'), df[cat_feats].values.astype('float32'))), grp, 'inputs', compression=compression) save_to_grp(df[targ_feats].values.astype(targ_type), grp, 'targets', compression=compression) if wgt_feat", "['save_to_grp', 'fold2foldfile', 'df2foldfile', 'add_meta_data'] def save_to_grp(arr:np.ndarray, grp:h5py.Group, name:str, compression:Optional[str]=None) -> None: r''' Save", "dimension of the array must be compatible with the length of the data", "removing from continuous features') cont_feats = [f for f in cont_feats if f", "type of target feature, e.g. int,'float32' strat_key: column to use for stratified splitting", "The format expected is `coo_x = sparse.as_coo(x); m = np.vstack((coo_x.data, coo_x.coords))`, where `m`", "import json from sklearn.model_selection import StratifiedKFold, KFold __all__ = ['save_to_grp', 'fold2foldfile', 'df2foldfile', 'add_meta_data']", "tensor_data is not None else None, compression=compression) add_meta_data(out_file=out_file, feats=df.columns, cont_feats=cont_feats, cat_feats=cat_feats, cat_maps=cat_maps, targ_feats=targ_feats,", "this is incompatible with also setting `matrix_lookup`, `matrix_missing`, and `matrix_shape`. The first dimension", "KFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df) else: kf = StratifiedKFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df,", "arr.dtype.name not in ['object', 'str864'] else 'S64', data=arr if arr.dtype.name not in ['object',", "for f in cont_feats if f in mat_feats] if len(dup) > 1: print(f'{dup}", "h5py file to save data in fold_idx: ID for the fold; used name", "Temp value, to be set to null later using missing missing[i,j] = True", "`matrix_missing`, and `matrix_shape`. The first dimension of the array must be compatible with", "mat = mat.reshape((len(df),*matrix_shape)) save_to_grp(mat, grp, 'matrix_inputs', compression=compression) elif tensor_data is not None: save_to_grp(tensor_data.astype('float32'),", "codes to categories targ_feats: (list of) target feature(s) wgt_feat: name of weight feature", "(COO format) and should be densified prior to use ''' grp = out_file.create_group('meta_data')", "as pd from typing import List, Union, Optional, Any, Tuple, Dict import os", "if wgt_feat is not None: if wgt_feat in df.columns: save_to_grp(df[wgt_feat].values.astype('float32'), grp, 'weights', compression=compression)", "in dup] if strat_key is not None and strat_key not in df.columns: print(f'{strat_key}", "data (exclusing batch dimension) tensor_is_sparse: Whether the tensor is sparse (COO format) and", "with the length of the data frame. compression: optional compression argument for h5py,", "Arguments: df: Dataframe from which to save data n_folds: number of folds to", "grp = out_file.create_group('meta_data') grp.create_dataset('cont_feats', data=json.dumps(cont_feats)) grp.create_dataset('cat_feats', data=json.dumps(cat_feats)) grp.create_dataset('targ_feats', data=json.dumps(targ_feats)) if wgt_feat is not", "dtype=np.bool) if row_wise: for i, v in enumerate(vecs): for j, c in enumerate(feats_per_vec):", "= f else: lookup[i,j] = feats[0] # Temp value, to be set to", "tensor_name: if `tensor_data` is set, then this is the name that will to", "categories targ_feats: (list of) target feature(s) wgt_feat: name of weight feature matrix_vecs: list", "by splitting data into sub-folds to be accessed by a :class:`~lumin.nn.data.fold_yielder.FoldYielder` Arguments: df:", "enumerate(vecs): for i, c in enumerate(feats_per_vec): f = f'{v}_{c}' if f in feats:", "if strat_key is not None and strat_key not in df.columns: print(f'{strat_key} not found", "data=json.dumps({'present_feats': [tensor_name], 'vecs': [tensor_name], 'missing': [], 'feats_per_vec': [''], 'row_wise': None, 'shape': tensor_shp, 'is_sparse':tensor_is_sparse}))", "for i, v in enumerate(vecs): for j, c in enumerate(feats_per_vec): f = f'{v}_{c}'", "lookup,missing,shape = _build_matrix_lookups(feats, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) use = list(np.array(lookup)[np.logical_not(missing)]) # Only features present", "of target feature, e.g. int,'float32' strat_key: column to use for stratified splitting misc_feats:", "wgt_feat in df.columns: save_to_grp(df[wgt_feat].values.astype('float32'), grp, 'weights', compression=compression) else: print(f'{wgt_feat} not found in file')", "arr.dtype.name not in ['object', 'str864'] else arr.astype('S64'), compression=compression) def _build_matrix_lookups(feats:List[str], vecs:List[str], feats_per_vec:List[str], row_wise:bool)", "create (.h5py extension not required) targ_type: type of target feature, e.g. int,'float32' strat_key:", "later using missing missing[i,j] = True else: for j, v in enumerate(vecs): for", "all the features associated with an object are in their own row), or", "value, to be set to null later using missing missing[i,j] = True return", "save as continuous variables cat_feats: list of columns in df to save as", "print(f'{f} not found in file') if matrix_lookup is not None: if tensor_data is", "compression: optional compression argument for h5py, e.g. 'lzf' ''' # TODO infer target", "one of the other.\") mat = df[matrix_lookup].values.astype('float32') mat[:,matrix_missing] = np.NaN mat = mat.reshape((len(df),*matrix_shape))", "Group Arguments: arr: array to be saved grp: group in which to save", "beign extracted and reshaped from the DataFrame. The array will be saved under", "split df into cont_feats: list of columns in df to save as continuous", "of the array must be compatible with the length of the data frame.", "f, compression=compression) else: print(f'{f} not found in file') if matrix_lookup is not None:", "This is ambiguous. Please only set one of the other.\") lookup,missing,shape = _build_matrix_lookups(df.columns,", "list of all features in data cont_feats: list of continuous features cat_feats: list", "if misc_feats is not None: for f in misc_feats: if f in df.columns:", "features present in data dup = [f for f in cont_feats if f", "of the other.\") lookup,missing,shape = _build_matrix_lookups(df.columns, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) mat_feats = list(np.array(lookup)[np.logical_not(missing)]) #", "in cont_feats if f in mat_feats] if len(dup) > 1: print(f'{dup} present in", "both matrix features and continuous features; removing from continuous features') cont_feats = [f", "feature names, matrix information, etc. :class:`~lumin.nn.data.fold_yielder.FoldYielder` objects will access this and automatically extract", "i.e. feature suffixes. Features listed but not present in df will be replaced", "data in feats: list of all features in data cont_feats: list of continuous", "for matrix encoding, i.e. feature suffixes. Features listed but not present in df", "is not None: if tensor_data is not None: raise ValueError(\"The saving of both", "= StratifiedKFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df, y=df[strat_key]) for fold_idx, (_, fold) in enumerate(folds):", "in file') if matrix_lookup is not None: if tensor_data is not None: raise", "data weights cat_maps: Dictionary mapping categorical features to dictionary mapping codes to categories", "other.\") mat = df[matrix_lookup].values.astype('float32') mat[:,matrix_missing] = np.NaN mat = mat.reshape((len(df),*matrix_shape)) save_to_grp(mat, grp, 'matrix_inputs',", "targ_type: type of target feature, e.g. int,'float32' misc_feats: any extra columns to save", "and reshaped from the DataFrame. The array will be saved under matrix data,", "cont_feats = [f for f in cont_feats if f not in dup] if", "in data cont_feats: list of continuous features cat_feats: list of categorical features cat_maps:", "Tuple, Dict import os from pathlib import Path import json from sklearn.model_selection import", "= np.zeros(shape, dtype=np.array(feats).dtype),np.zeros(shape, dtype=np.bool) if row_wise: for i, v in enumerate(vecs): for j,", "= kf.split(X=df, y=df[strat_key]) for fold_idx, (_, fold) in enumerate(folds): print(f\"Saving fold {fold_idx} with", "features present in data grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': use, 'vecs': matrix_vecs, 'missing': [int(m) for m", "as data weights cat_maps: Dictionary mapping categorical features to dictionary mapping codes to", "save_to_grp(df[targ_feats].values.astype(targ_type), grp, 'targets', compression=compression) if wgt_feat is not None: if wgt_feat in df.columns:", "out_file.create_group('meta_data') grp.create_dataset('cont_feats', data=json.dumps(cont_feats)) grp.create_dataset('cat_feats', data=json.dumps(cat_feats)) grp.create_dataset('targ_feats', data=json.dumps(targ_feats)) if wgt_feat is not None: grp.create_dataset('wgt_feat',", "if f in mat_feats] if len(dup) > 1: print(f'{dup} present in both matrix", "all the features associated with an object are in their own column) tensor_data:", "matrix data, and this is incompatible with also setting `matrix_lookup`, `matrix_missing`, and `matrix_shape`.", "Dataframe from which to save data out_file: h5py file to save data in", "be compatible with the length of the data frame. compression: optional compression argument", "name of h5py file to create (.h5py extension not required) targ_type: type of", "h5py, e.g. 'lzf' ''' savename = str(savename) os.system(f'rm {savename}.hdf5') os.makedirs(savename[:savename.rfind('/')], exist_ok=True) out_file =", "other.\") lookup,missing,shape = _build_matrix_lookups(df.columns, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) mat_feats = list(np.array(lookup)[np.logical_not(missing)]) # Only features", "f in cont_feats if f in mat_feats] if len(dup) > 1: print(f'{dup} present", "None: r''' Save fold of data into an h5py Group Arguments: df: Dataframe", "as continuous variables cat_feats: list of columns in df to save as discreet", "in misc_feats: if f in df.columns: save_to_grp(df[f].values, grp, f, compression=compression) else: print(f'{f} not", "mapping categorical features to dictionary mapping codes to categories targ_feats: (list of) target", "in df to save as target feature(s) savename: name of h5py file to", "matrix encoding, i.e. feature suffixes. Features listed but not present in df will", "is not None: if wgt_feat in df.columns: save_to_grp(df[wgt_feat].values.astype('float32'), grp, 'weights', compression=compression) else: print(f'{wgt_feat}", "if row_wise: for i, v in enumerate(vecs): for j, c in enumerate(feats_per_vec): f", "having to manually pass lists of features. Arguments: out_file: h5py file to save", "all features in data cont_feats: list of continuous features cat_feats: list of categorical", "Adds meta data to foldfile containing information about the data: feature names, matrix", "name of weight feature matrix_vecs: list of objects for matrix encoding, i.e. feature", "not None else None, compression=compression) add_meta_data(out_file=out_file, feats=df.columns, cont_feats=cont_feats, cat_feats=cat_feats, cat_maps=cat_maps, targ_feats=targ_feats, wgt_feat=wgt_feat, matrix_vecs=matrix_vecs,", "feats_per_vec:List[str], row_wise:bool) -> Tuple[List[str],np.ndarray,Tuple[int,int]]: shape = (len(vecs),len(feats_per_vec)) if row_wise else (len(feats_per_vec),len(vecs)) lookup,missing =", "pathlib import Path import json from sklearn.model_selection import StratifiedKFold, KFold __all__ = ['save_to_grp',", "mapping categorical features to dictionary mapping codes to categories matrix_vecs: list of objects", "grp.create_dataset('cat_feats', data=json.dumps(cat_feats)) grp.create_dataset('targ_feats', data=json.dumps(targ_feats)) if wgt_feat is not None: grp.create_dataset('wgt_feat', data=json.dumps(wgt_feat)) if cat_maps", "out_file: h5py file to save data in fold_idx: ID for the fold; used", "tensor_data=tensor_data[fold] if tensor_data is not None else None, compression=compression) add_meta_data(out_file=out_file, feats=df.columns, cont_feats=cont_feats, cat_feats=cat_feats,", "columns to save wgt_feat: column to save as data weights cat_maps: Dictionary mapping", "as a numpy array, rather than beign extracted and reshaped from the DataFrame.", "than beign extracted and reshaped from the DataFrame. The array will be saved", "only set one of the other.\") lookup,missing,shape = _build_matrix_lookups(df.columns, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) mat_feats", "for string length grp.create_dataset(name, shape=arr.shape, dtype=arr.dtype.name if arr.dtype.name not in ['object', 'str864'] else", "with an object are in their own column) tensor_data: data of higher order", "is the name that will to the foldfile's metadata. tensor_is_sparse: Set to True", "to `tensor_data`. compression: optional compression argument for h5py, e.g. 'lzf' ''' savename =", "data out_file: h5py file to save data in fold_idx: ID for the fold;", "to save as continuous variables cat_feats: list of columns in df to save", "if matrix_lookup is not None: if tensor_data is not None: raise ValueError(\"The saving", "df to save as continuous variables cat_feats: list of columns in df to", "with also setting `matrix_vecs`, `matrix_feats_per_vec`, and `matrix_row_wise`. The first dimension of the array", "compression argument for h5py, e.g. 'lzf' ''' # TODO infer target type automatically", "save arr name: name of dataset to create compression: optional compression argument for", "None: grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': [tensor_name], 'vecs': [tensor_name], 'missing': [], 'feats_per_vec': [''], 'row_wise': None, 'shape':", "present in data dup = [f for f in cont_feats if f in", "tensor data is requested. This is ambiguous. Please only set one of the", "i, c in enumerate(feats_per_vec): f = f'{v}_{c}' if f in feats: lookup[i,j] =", "categories matrix_vecs: list of objects for matrix encoding, i.e. feature prefixes matrix_feats_per_vec: list", "metadata. tensor_is_sparse: Set to True if the matrix is in sparse COO format", "df[matrix_lookup].values.astype('float32') mat[:,matrix_missing] = np.NaN mat = mat.reshape((len(df),*matrix_shape)) save_to_grp(mat, grp, 'matrix_inputs', compression=compression) elif tensor_data", "listed but not present in df will be replaced with NaN. matrix_row_wise: whether", "\"w\") lookup,missing,shape = None,None,None if matrix_vecs is not None: if tensor_data is not", "fold) in enumerate(folds): print(f\"Saving fold {fold_idx} with {len(fold)} events\") fold2foldfile(df.iloc[fold].copy(), out_file, fold_idx, cont_feats=cont_feats,", "sparse COO format and should be densified later on The format expected is", "to save the user from having to manually pass lists of features. Arguments:", "TODO infer target type automatically grp = out_file.create_group(f'fold_{fold_idx}') save_to_grp(np.hstack((df[cont_feats].values.astype('float32'), df[cat_feats].values.astype('float32'))), grp, 'inputs', compression=compression)", "to be set to null later using missing missing[i,j] = True return list(lookup.flatten()),missing.flatten(),shape", "incompatible with also setting `matrix_lookup`, `matrix_missing`, and `matrix_shape`. The first dimension of the", "using missing missing[i,j] = True else: for j, v in enumerate(vecs): for i,", "targ_feats: (list of) column(s) in df to save as target feature(s) targ_type: type", "used name h5py group according to 'fold_{fold_idx}' cont_feats: list of columns in df", "cat_feats=cat_feats, targ_feats=targ_feats, targ_type=targ_type, misc_feats=misc_feats, wgt_feat=wgt_feat, matrix_lookup=lookup, matrix_missing=missing, matrix_shape=shape, tensor_data=tensor_data[fold] if tensor_data is not", "feature(s) wgt_feat: name of weight feature matrix_vecs: list of objects for matrix encoding,", "for f in cont_feats if f not in dup] if strat_key is not", "{savename}.hdf5') os.makedirs(savename[:savename.rfind('/')], exist_ok=True) out_file = h5py.File(f'{savename}.hdf5', \"w\") lookup,missing,shape = None,None,None if matrix_vecs is", "Arguments: out_file: h5py file to save data in feats: list of all features", "value, to be set to null later using missing missing[i,j] = True else:", "cont_feats:List[str], cat_feats:List[str], cat_maps:Optional[Dict[str,Dict[int,Any]]], targ_feats:Union[str,List[str]], wgt_feat:Optional[str]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_name:Optional[str]=None, tensor_shp:Optional[Tuple[int]]=None, tensor_is_sparse:bool=False) -> None:", "the tensor data (exclusing batch dimension) tensor_is_sparse: Whether the tensor is sparse (COO", "can be passed directly as a numpy array, rather than beign extracted and", "to dictionary mapping codes to categories matrix_vecs: list of objects for matrix encoding,", "wgt_feat:Optional[str]=None, cat_maps:Optional[Dict[str,Dict[int,Any]]]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_data:Optional[np.ndarray]=None, tensor_name:Optional[str]=None, tensor_is_sparse:bool=False, compression:Optional[str]=None) -> None: r''' Convert", "is set, then this is the name that will to the foldfile's metadata.", "grp.create_dataset('targ_feats', data=json.dumps(targ_feats)) if wgt_feat is not None: grp.create_dataset('wgt_feat', data=json.dumps(wgt_feat)) if cat_maps is not", "an object are in their own row), or column-wise (i.e. all the features", "length of the data frame. compression: optional compression argument for h5py, e.g. 'lzf'", "= sparse.as_coo(x); m = np.vstack((coo_x.data, coo_x.coords))`, where `m` is the tensor passed to", "data cont_feats: list of continuous features cat_feats: list of categorical features cat_maps: Dictionary", "to manually pass lists of features. Arguments: out_file: h5py file to save data", "feature, e.g. int,'float32' misc_feats: any extra columns to save wgt_feat: column to save", "data frame. compression: optional compression argument for h5py, e.g. 'lzf' ''' # TODO", "save data in fold_idx: ID for the fold; used name h5py group according", "save as data weights cat_maps: Dictionary mapping categorical features to dictionary mapping codes", "feats:List[str], cont_feats:List[str], cat_feats:List[str], cat_maps:Optional[Dict[str,Dict[int,Any]]], targ_feats:Union[str,List[str]], wgt_feat:Optional[str]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_name:Optional[str]=None, tensor_shp:Optional[Tuple[int]]=None, tensor_is_sparse:bool=False) ->", "use for stratified splitting misc_feats: any extra columns to save wgt_feat: column to", "later on The format expected is `coo_x = sparse.as_coo(x); m = np.vstack((coo_x.data, coo_x.coords))`,", ":class:`~lumin.nn.data.fold_yielder.FoldYielder` objects will access this and automatically extract it to save the user", "features in data cont_feats: list of continuous features cat_feats: list of categorical features", "'missing': [int(m) for m in missing], 'feats_per_vec': matrix_feats_per_vec, 'row_wise': matrix_row_wise, 'shape': shape})) elif", "if arr.dtype.name not in ['object', 'str864'] else arr.astype('S64'), compression=compression) def _build_matrix_lookups(feats:List[str], vecs:List[str], feats_per_vec:List[str],", "out_file.create_group(f'fold_{fold_idx}') save_to_grp(np.hstack((df[cont_feats].values.astype('float32'), df[cat_feats].values.astype('float32'))), grp, 'inputs', compression=compression) save_to_grp(df[targ_feats].values.astype(targ_type), grp, 'targets', compression=compression) if wgt_feat is", "matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_data:Optional[np.ndarray]=None, tensor_name:Optional[str]=None, tensor_is_sparse:bool=False, compression:Optional[str]=None) -> None: r''' Convert dataframe into h5py", "matrix_missing:Optional[np.ndarray]=None, matrix_shape:Optional[Tuple[int,int]]=None, tensor_data:Optional[np.ndarray]=None, compression:Optional[str]=None) -> None: r''' Save fold of data into an", "format expected is `coo_x = sparse.as_coo(x); m = np.vstack((coo_x.data, coo_x.coords))`, where `m` is", "> 1: print(f'{dup} present in both matrix features and continuous features; removing from", "(len(feats_per_vec),len(vecs)) lookup,missing = np.zeros(shape, dtype=np.array(feats).dtype),np.zeros(shape, dtype=np.bool) if row_wise: for i, v in enumerate(vecs):", "the tensor when displaying model information tensor_shp: The shape of the tensor data", "features to dictionary mapping codes to categories matrix_vecs: list of objects for matrix", "extracted and reshaped from the DataFrame. The array will be saved under matrix", "import h5py import numpy as np import pandas as pd from typing import", "if f not in dup] if strat_key is not None and strat_key not", "v in enumerate(vecs): for j, c in enumerate(feats_per_vec): f = f'{v}_{c}' if f", "arr.astype('S64'), compression=compression) def _build_matrix_lookups(feats:List[str], vecs:List[str], feats_per_vec:List[str], row_wise:bool) -> Tuple[List[str],np.ndarray,Tuple[int,int]]: shape = (len(vecs),len(feats_per_vec)) if", "matrix_row_wise:Optional[bool]=None, tensor_name:Optional[str]=None, tensor_shp:Optional[Tuple[int]]=None, tensor_is_sparse:bool=False) -> None: r''' Adds meta data to foldfile containing", "is sparse (COO format) and should be densified prior to use ''' grp", "e.g. int,'float32' misc_feats: any extra columns to save wgt_feat: column to save as", "cat_maps is not None: grp.create_dataset('cat_maps', data=json.dumps(cat_maps)) if matrix_vecs is not None: lookup,missing,shape =", "file to save data in feats: list of all features in data cont_feats:", "save as target feature(s) targ_type: type of target feature, e.g. int,'float32' misc_feats: any", "if matrix_vecs is not None: lookup,missing,shape = _build_matrix_lookups(feats, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) use =", "type automatically grp = out_file.create_group(f'fold_{fold_idx}') save_to_grp(np.hstack((df[cont_feats].values.astype('float32'), df[cat_feats].values.astype('float32'))), grp, 'inputs', compression=compression) save_to_grp(df[targ_feats].values.astype(targ_type), grp, 'targets',", "save_to_grp(df[wgt_feat].values.astype('float32'), grp, 'weights', compression=compression) else: print(f'{wgt_feat} not found in file') if misc_feats is", "cat_feats=cat_feats, cat_maps=cat_maps, targ_feats=targ_feats, wgt_feat=wgt_feat, matrix_vecs=matrix_vecs, matrix_feats_per_vec=matrix_feats_per_vec, matrix_row_wise=matrix_row_wise, tensor_name=tensor_name, tensor_shp=tensor_data[0].shape if tensor_data is not", "foldfile containing information about the data: feature names, matrix information, etc. :class:`~lumin.nn.data.fold_yielder.FoldYielder` objects", "h5py group according to 'fold_{fold_idx}' cont_feats: list of columns in df to save", "the array must be compatible with the length of the data frame. tensor_name:", "arr name: name of dataset to create compression: optional compression argument for h5py,", "weight feature matrix_vecs: list of objects for matrix encoding, i.e. feature prefixes matrix_feats_per_vec:", "but not present in df will be replaced with NaN. matrix_row_wise: whether objects", "elif tensor_data is not None: save_to_grp(tensor_data.astype('float32'), grp, 'matrix_inputs', compression=compression) def df2foldfile(df:pd.DataFrame, n_folds:int, cont_feats:List[str],", "row_wise:bool) -> Tuple[List[str],np.ndarray,Tuple[int,int]]: shape = (len(vecs),len(feats_per_vec)) if row_wise else (len(feats_per_vec),len(vecs)) lookup,missing = np.zeros(shape,", "['object', 'str864'] else 'S64', data=arr if arr.dtype.name not in ['object', 'str864'] else arr.astype('S64'),", "(list of) column(s) in df to save as target feature(s) targ_type: type of", "list of objects for matrix encoding, i.e. feature prefixes matrix_feats_per_vec: list of features", "None: grp.create_dataset('cat_maps', data=json.dumps(cat_maps)) if matrix_vecs is not None: lookup,missing,shape = _build_matrix_lookups(feats, matrix_vecs, matrix_feats_per_vec,", "column to save as data weights matrix_vecs: list of objects for matrix encoding,", "Dictionary mapping categorical features to dictionary mapping codes to categories matrix_vecs: list of", "only set one of the other.\") mat = df[matrix_lookup].values.astype('float32') mat[:,matrix_missing] = np.NaN mat", "for fold_idx, (_, fold) in enumerate(folds): print(f\"Saving fold {fold_idx} with {len(fold)} events\") fold2foldfile(df.iloc[fold].copy(),", "to categories matrix_vecs: list of objects for matrix encoding, i.e. feature prefixes matrix_feats_per_vec:", "cat_maps:Optional[Dict[str,Dict[int,Any]]]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_data:Optional[np.ndarray]=None, tensor_name:Optional[str]=None, tensor_is_sparse:bool=False, compression:Optional[str]=None) -> None: r''' Convert dataframe", "matrix_row_wise) mat_feats = list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data dup = [f", "or column-wise (i.e. all the features associated with an object are in their", "of) column(s) in df to save as target feature(s) targ_type: type of target", "StratifiedKFold, KFold __all__ = ['save_to_grp', 'fold2foldfile', 'df2foldfile', 'add_meta_data'] def save_to_grp(arr:np.ndarray, grp:h5py.Group, name:str, compression:Optional[str]=None)", "matrix_shape:Optional[Tuple[int,int]]=None, tensor_data:Optional[np.ndarray]=None, compression:Optional[str]=None) -> None: r''' Save fold of data into an h5py", "cat_maps: Dictionary mapping categorical features to dictionary mapping codes to categories matrix_vecs: list", "if matrix_vecs is not None: if tensor_data is not None: raise ValueError(\"The saving", "of the data frame. compression: optional compression argument for h5py, e.g. 'lzf' '''", "and this is incompatible with also setting `matrix_vecs`, `matrix_feats_per_vec`, and `matrix_row_wise`. The first", "(_, fold) in enumerate(folds): print(f\"Saving fold {fold_idx} with {len(fold)} events\") fold2foldfile(df.iloc[fold].copy(), out_file, fold_idx,", "h5py Group Arguments: arr: array to be saved grp: group in which to", "row-wise (i.e. all the features associated with an object are in their own", "= None,None,None if matrix_vecs is not None: if tensor_data is not None: raise", "as data weights matrix_vecs: list of objects for matrix encoding, i.e. feature prefixes", "is not None else None, compression=compression) add_meta_data(out_file=out_file, feats=df.columns, cont_feats=cont_feats, cat_feats=cat_feats, cat_maps=cat_maps, targ_feats=targ_feats, wgt_feat=wgt_feat,", "None: for f in misc_feats: if f in df.columns: save_to_grp(df[f].values, grp, f, compression=compression)", "where `m` is the tensor passed to `tensor_data`. compression: optional compression argument for", "passed directly as a numpy array, rather than beign extracted and reshaped from", "matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_name:Optional[str]=None, tensor_shp:Optional[Tuple[int]]=None, tensor_is_sparse:bool=False) -> None: r''' Adds meta data to foldfile", "f in feats: lookup[i,j] = f else: lookup[i,j] = feats[0] # Temp value,", "feature, e.g. int,'float32' strat_key: column to use for stratified splitting misc_feats: any extra", "matrix_shape=shape, tensor_data=tensor_data[fold] if tensor_data is not None else None, compression=compression) add_meta_data(out_file=out_file, feats=df.columns, cont_feats=cont_feats,", "extract it to save the user from having to manually pass lists of", "containing information about the data: feature names, matrix information, etc. :class:`~lumin.nn.data.fold_yielder.FoldYielder` objects will", "import List, Union, Optional, Any, Tuple, Dict import os from pathlib import Path", "and should be densified prior to use ''' grp = out_file.create_group('meta_data') grp.create_dataset('cont_feats', data=json.dumps(cont_feats))", "exist_ok=True) out_file = h5py.File(f'{savename}.hdf5', \"w\") lookup,missing,shape = None,None,None if matrix_vecs is not None:", "save_to_grp(np.hstack((df[cont_feats].values.astype('float32'), df[cat_feats].values.astype('float32'))), grp, 'inputs', compression=compression) save_to_grp(df[targ_feats].values.astype(targ_type), grp, 'targets', compression=compression) if wgt_feat is not", "df[cat_feats].values.astype('float32'))), grp, 'inputs', compression=compression) save_to_grp(df[targ_feats].values.astype(targ_type), grp, 'targets', compression=compression) if wgt_feat is not None:", "be encoded row-wise (i.e. all the features associated with an object are in", "df to save as discreet variables targ_feats: (list of) column(s) in df to", "None: if tensor_data is not None: raise ValueError(\"The saving of both matrix and", "Any, Tuple, Dict import os from pathlib import Path import json from sklearn.model_selection", "None: r''' Convert dataframe into h5py file by splitting data into sub-folds to", "null later using missing missing[i,j] = True return list(lookup.flatten()),missing.flatten(),shape def fold2foldfile(df:pd.DataFrame, out_file:h5py.File, fold_idx:int,", "cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], targ_type:Any, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, matrix_lookup:Optional[List[str]]=None, matrix_missing:Optional[np.ndarray]=None, matrix_shape:Optional[Tuple[int,int]]=None, tensor_data:Optional[np.ndarray]=None, compression:Optional[str]=None) -> None:", "grp, 'weights', compression=compression) else: print(f'{wgt_feat} not found in file') if misc_feats is not", "format) and should be densified prior to use ''' grp = out_file.create_group('meta_data') grp.create_dataset('cont_feats',", "matrix_missing=missing, matrix_shape=shape, tensor_data=tensor_data[fold] if tensor_data is not None else None, compression=compression) add_meta_data(out_file=out_file, feats=df.columns,", "data=json.dumps(cat_feats)) grp.create_dataset('targ_feats', data=json.dumps(targ_feats)) if wgt_feat is not None: grp.create_dataset('wgt_feat', data=json.dumps(wgt_feat)) if cat_maps is", "must be compatible with the length of the data frame. compression: optional compression", "list of categorical features cat_maps: Dictionary mapping categorical features to dictionary mapping codes", "`coo_x = sparse.as_coo(x); m = np.vstack((coo_x.data, coo_x.coords))`, where `m` is the tensor passed", "if tensor_data is not None: raise ValueError(\"The saving of both matrix and tensor", "{len(fold)} events\") fold2foldfile(df.iloc[fold].copy(), out_file, fold_idx, cont_feats=cont_feats, cat_feats=cat_feats, targ_feats=targ_feats, targ_type=targ_type, misc_feats=misc_feats, wgt_feat=wgt_feat, matrix_lookup=lookup, matrix_missing=missing,", "None: r''' Save Numpy array as a dataset in an h5py Group Arguments:", "sub-folds to be accessed by a :class:`~lumin.nn.data.fold_yielder.FoldYielder` Arguments: df: Dataframe from which to", "targ_feats:Union[str,List[str]], savename:Union[Path,str], targ_type:str, strat_key:Optional[str]=None, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, cat_maps:Optional[Dict[str,Dict[int,Any]]]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_data:Optional[np.ndarray]=None, tensor_name:Optional[str]=None, tensor_is_sparse:bool=False,", "associated with an object are in their own column) tensor_data: data of higher", "data into sub-folds to be accessed by a :class:`~lumin.nn.data.fold_yielder.FoldYielder` Arguments: df: Dataframe from", "(list of) column(s) in df to save as target feature(s) savename: name of", "list of columns in df to save as discreet variables targ_feats: (list of)", "reshaped from the DataFrame. The array will be saved under matrix data, and", "to be accessed by a :class:`~lumin.nn.data.fold_yielder.FoldYielder` Arguments: df: Dataframe from which to save", "for stratified splitting misc_feats: any extra columns to save wgt_feat: column to save", "matrix_vecs, matrix_feats_per_vec, matrix_row_wise) use = list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data grp.create_dataset('matrix_feats',", "COO format and should be densified later on The format expected is `coo_x", "targ_feats: (list of) column(s) in df to save as target feature(s) savename: name", "file to create (.h5py extension not required) targ_type: type of target feature, e.g.", "first dimension of the array must be compatible with the length of the", "h5py file by splitting data into sub-folds to be accessed by a :class:`~lumin.nn.data.fold_yielder.FoldYielder`", "ValueError(\"The saving of both matrix and tensor data is requested. This is ambiguous.", "(exclusing batch dimension) tensor_is_sparse: Whether the tensor is sparse (COO format) and should", "'matrix_inputs', compression=compression) def df2foldfile(df:pd.DataFrame, n_folds:int, cont_feats:List[str], cat_feats:List[str], targ_feats:Union[str,List[str]], savename:Union[Path,str], targ_type:str, strat_key:Optional[str]=None, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None,", "be replaced with NaN. matrix_row_wise: whether objects encoded as a matrix should be", "features associated with an object are in their own column) tensor_name: Name used", "data in fold_idx: ID for the fold; used name h5py group according to", "to be saved grp: group in which to save arr name: name of", "tensor is sparse (COO format) and should be densified prior to use '''", "be densified later on The format expected is `coo_x = sparse.as_coo(x); m =", "tensor_is_sparse:bool=False) -> None: r''' Adds meta data to foldfile containing information about the", "'df2foldfile', 'add_meta_data'] def save_to_grp(arr:np.ndarray, grp:h5py.Group, name:str, compression:Optional[str]=None) -> None: r''' Save Numpy array", "be saved under matrix data, and this is incompatible with also setting `matrix_lookup`,", "matrix_vecs, matrix_feats_per_vec, matrix_row_wise) mat_feats = list(np.array(lookup)[np.logical_not(missing)]) # Only features present in data dup", "wgt_feat:Optional[str]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_name:Optional[str]=None, tensor_shp:Optional[Tuple[int]]=None, tensor_is_sparse:bool=False) -> None: r''' Adds meta data", "not None else None, tensor_is_sparse=tensor_is_sparse) def add_meta_data(out_file:h5py.File, feats:List[str], cont_feats:List[str], cat_feats:List[str], cat_maps:Optional[Dict[str,Dict[int,Any]]], targ_feats:Union[str,List[str]], wgt_feat:Optional[str]=None,", "argument for h5py, e.g. 'lzf' ''' # TODO infer target type automatically grp", "also setting `matrix_vecs`, `matrix_feats_per_vec`, and `matrix_row_wise`. The first dimension of the array must", "cont_feats if f in mat_feats] if len(dup) > 1: print(f'{dup} present in both", "frame. compression: optional compression argument for h5py, e.g. 'lzf' ''' # TODO infer", "of folds to split df into cont_feats: list of columns in df to", "sparse.as_coo(x); m = np.vstack((coo_x.data, coo_x.coords))`, where `m` is the tensor passed to `tensor_data`.", "np.vstack((coo_x.data, coo_x.coords))`, where `m` is the tensor passed to `tensor_data`. compression: optional compression", "else (len(feats_per_vec),len(vecs)) lookup,missing = np.zeros(shape, dtype=np.array(feats).dtype),np.zeros(shape, dtype=np.bool) if row_wise: for i, v in", "df will be replaced with NaN. matrix_row_wise: whether objects encoded as a matrix", "column to save as data weights cat_maps: Dictionary mapping categorical features to dictionary", "of features per vector for matrix encoding, i.e. feature suffixes. Features listed but", "automatically grp = out_file.create_group(f'fold_{fold_idx}') save_to_grp(np.hstack((df[cont_feats].values.astype('float32'), df[cat_feats].values.astype('float32'))), grp, 'inputs', compression=compression) save_to_grp(df[targ_feats].values.astype(targ_type), grp, 'targets', compression=compression)", "data=json.dumps(cat_maps)) if matrix_vecs is not None: lookup,missing,shape = _build_matrix_lookups(feats, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) use", "features associated with an object are in their own column) tensor_data: data of", "and continuous features; removing from continuous features') cont_feats = [f for f in", "kf.split(X=df) else: kf = StratifiedKFold(n_splits=n_folds, shuffle=True) folds = kf.split(X=df, y=df[strat_key]) for fold_idx, (_,", "wgt_feat=wgt_feat, matrix_lookup=lookup, matrix_missing=missing, matrix_shape=shape, tensor_data=tensor_data[fold] if tensor_data is not None else None, compression=compression)", "features cat_feats: list of categorical features cat_maps: Dictionary mapping categorical features to dictionary", "the features associated with an object are in their own column) tensor_name: Name", "None: r''' Adds meta data to foldfile containing information about the data: feature", "targ_feats: (list of) target feature(s) wgt_feat: name of weight feature matrix_vecs: list of", "Only features present in data grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': use, 'vecs': matrix_vecs, 'missing': [int(m) for", "dup] if strat_key is not None and strat_key not in df.columns: print(f'{strat_key} not", "higher order than a matrix can be passed directly as a numpy array,", "''' # TODO infer target type automatically grp = out_file.create_group(f'fold_{fold_idx}') save_to_grp(np.hstack((df[cont_feats].values.astype('float32'), df[cat_feats].values.astype('float32'))), grp,", "features cat_maps: Dictionary mapping categorical features to dictionary mapping codes to categories targ_feats:", "in df.columns: save_to_grp(df[wgt_feat].values.astype('float32'), grp, 'weights', compression=compression) else: print(f'{wgt_feat} not found in file') if", "with NaN. matrix_row_wise: whether objects encoded as a matrix should be encoded row-wise", "column) tensor_data: data of higher order than a matrix can be passed directly", "according to 'fold_{fold_idx}' cont_feats: list of columns in df to save as continuous", "= _build_matrix_lookups(feats, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) use = list(np.array(lookup)[np.logical_not(missing)]) # Only features present in", "the features associated with an object are in their own column) tensor_data: data", "to True if the matrix is in sparse COO format and should be", "from which to save data n_folds: number of folds to split df into", "= True else: for j, v in enumerate(vecs): for i, c in enumerate(feats_per_vec):", "of objects for matrix encoding, i.e. feature prefixes matrix_feats_per_vec: list of features per", "= _build_matrix_lookups(df.columns, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) mat_feats = list(np.array(lookup)[np.logical_not(missing)]) # Only features present in", "grp, 'targets', compression=compression) if wgt_feat is not None: if wgt_feat in df.columns: save_to_grp(df[wgt_feat].values.astype('float32'),", "be saved grp: group in which to save arr name: name of dataset", "setting `matrix_vecs`, `matrix_feats_per_vec`, and `matrix_row_wise`. The first dimension of the array must be", "`matrix_feats_per_vec`, and `matrix_row_wise`. The first dimension of the array must be compatible with", "in df.columns: print(f'{strat_key} not found in DataFrame') strat_key = None if strat_key is", "c in enumerate(feats_per_vec): f = f'{v}_{c}' if f in feats: lookup[i,j] = f", "a matrix can be passed directly as a numpy array, rather than beign", "tensor_data:Optional[np.ndarray]=None, compression:Optional[str]=None) -> None: r''' Save fold of data into an h5py Group", "enumerate(feats_per_vec): f = f'{v}_{c}' if f in feats: lookup[i,j] = f else: lookup[i,j]", "data, and this is incompatible with also setting `matrix_lookup`, `matrix_missing`, and `matrix_shape`. The", "cat_feats: list of categorical features cat_maps: Dictionary mapping categorical features to dictionary mapping", "strat_key:Optional[str]=None, misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, cat_maps:Optional[Dict[str,Dict[int,Any]]]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_data:Optional[np.ndarray]=None, tensor_name:Optional[str]=None, tensor_is_sparse:bool=False, compression:Optional[str]=None) -> None:", "grp:h5py.Group, name:str, compression:Optional[str]=None) -> None: r''' Save Numpy array as a dataset in", "ambiguous. Please only set one of the other.\") lookup,missing,shape = _build_matrix_lookups(df.columns, matrix_vecs, matrix_feats_per_vec,", "the length of the data frame. tensor_name: if `tensor_data` is set, then this", "also setting `matrix_lookup`, `matrix_missing`, and `matrix_shape`. The first dimension of the array must", "into h5py file by splitting data into sub-folds to be accessed by a", "shape=arr.shape, dtype=arr.dtype.name if arr.dtype.name not in ['object', 'str864'] else 'S64', data=arr if arr.dtype.name", "in sparse COO format and should be densified later on The format expected", "set to null later using missing missing[i,j] = True return list(lookup.flatten()),missing.flatten(),shape def fold2foldfile(df:pd.DataFrame,", "None: raise ValueError(\"The saving of both matrix and tensor data is requested. This", "be accessed by a :class:`~lumin.nn.data.fold_yielder.FoldYielder` Arguments: df: Dataframe from which to save data", "os.system(f'rm {savename}.hdf5') os.makedirs(savename[:savename.rfind('/')], exist_ok=True) out_file = h5py.File(f'{savename}.hdf5', \"w\") lookup,missing,shape = None,None,None if matrix_vecs", "is not None and strat_key not in df.columns: print(f'{strat_key} not found in DataFrame')", "i.e. feature prefixes matrix_feats_per_vec: list of features per vector for matrix encoding, i.e.", "own column) tensor_name: Name used to refer to the tensor when displaying model", "continuous features') cont_feats = [f for f in cont_feats if f not in", "target feature, e.g. int,'float32' misc_feats: any extra columns to save wgt_feat: column to", "save data out_file: h5py file to save data in fold_idx: ID for the", "columns in df to save as discreet variables targ_feats: (list of) column(s) in", "compression=compression) else: print(f'{wgt_feat} not found in file') if misc_feats is not None: for", "coo_x.coords))`, where `m` is the tensor passed to `tensor_data`. compression: optional compression argument", "to create (.h5py extension not required) targ_type: type of target feature, e.g. int,'float32'", "of dataset to create compression: optional compression argument for h5py, e.g. 'lzf' '''", "array to be saved grp: group in which to save arr name: name", "tensor passed to `tensor_data`. compression: optional compression argument for h5py, e.g. 'lzf' '''", "any extra columns to save wgt_feat: column to save as data weights cat_maps:", "else None, tensor_is_sparse=tensor_is_sparse) def add_meta_data(out_file:h5py.File, feats:List[str], cont_feats:List[str], cat_feats:List[str], cat_maps:Optional[Dict[str,Dict[int,Any]]], targ_feats:Union[str,List[str]], wgt_feat:Optional[str]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None,", "and strat_key not in df.columns: print(f'{strat_key} not found in DataFrame') strat_key = None", "Numpy array as a dataset in an h5py Group Arguments: arr: array to", "not in ['object', 'str864'] else 'S64', data=arr if arr.dtype.name not in ['object', 'str864']", "'lzf' ''' # TODO infer target type automatically grp = out_file.create_group(f'fold_{fold_idx}') save_to_grp(np.hstack((df[cont_feats].values.astype('float32'), df[cat_feats].values.astype('float32'))),", "displaying model information tensor_shp: The shape of the tensor data (exclusing batch dimension)", "compression:Optional[str]=None) -> None: r''' Save fold of data into an h5py Group Arguments:", "the tensor is sparse (COO format) and should be densified prior to use", "''' # TODO Option for string length grp.create_dataset(name, shape=arr.shape, dtype=arr.dtype.name if arr.dtype.name not", "df into cont_feats: list of columns in df to save as continuous variables", "h5py.File(f'{savename}.hdf5', \"w\") lookup,missing,shape = None,None,None if matrix_vecs is not None: if tensor_data is", "which to save arr name: name of dataset to create compression: optional compression", "is `coo_x = sparse.as_coo(x); m = np.vstack((coo_x.data, coo_x.coords))`, where `m` is the tensor", "pd from typing import List, Union, Optional, Any, Tuple, Dict import os from", "not found in file') if matrix_lookup is not None: if tensor_data is not", "matrix_vecs=matrix_vecs, matrix_feats_per_vec=matrix_feats_per_vec, matrix_row_wise=matrix_row_wise, tensor_name=tensor_name, tensor_shp=tensor_data[0].shape if tensor_data is not None else None, tensor_is_sparse=tensor_is_sparse)", "Please only set one of the other.\") mat = df[matrix_lookup].values.astype('float32') mat[:,matrix_missing] = np.NaN", "and `matrix_shape`. The first dimension of the array must be compatible with the", "required) targ_type: type of target feature, e.g. int,'float32' strat_key: column to use for", "with an object are in their own row), or column-wise (i.e. all the", "# Only features present in data dup = [f for f in cont_feats", "as np import pandas as pd from typing import List, Union, Optional, Any,", "one of the other.\") lookup,missing,shape = _build_matrix_lookups(df.columns, matrix_vecs, matrix_feats_per_vec, matrix_row_wise) mat_feats = list(np.array(lookup)[np.logical_not(missing)])", "missing], 'feats_per_vec': matrix_feats_per_vec, 'row_wise': matrix_row_wise, 'shape': shape})) elif tensor_name is not None: grp.create_dataset('matrix_feats',", "numpy array, rather than beign extracted and reshaped from the DataFrame. The array", "compression=compression) def _build_matrix_lookups(feats:List[str], vecs:List[str], feats_per_vec:List[str], row_wise:bool) -> Tuple[List[str],np.ndarray,Tuple[int,int]]: shape = (len(vecs),len(feats_per_vec)) if row_wise", "misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, matrix_lookup:Optional[List[str]]=None, matrix_missing:Optional[np.ndarray]=None, matrix_shape:Optional[Tuple[int,int]]=None, tensor_data:Optional[np.ndarray]=None, compression:Optional[str]=None) -> None: r''' Save fold of", "misc_feats:Optional[List[str]]=None, wgt_feat:Optional[str]=None, cat_maps:Optional[Dict[str,Dict[int,Any]]]=None, matrix_vecs:Optional[List[str]]=None, matrix_feats_per_vec:Optional[List[str]]=None, matrix_row_wise:Optional[bool]=None, tensor_data:Optional[np.ndarray]=None, tensor_name:Optional[str]=None, tensor_is_sparse:bool=False, compression:Optional[str]=None) -> None: r'''", "to be set to null later using missing missing[i,j] = True else: for", "present in data grp.create_dataset('matrix_feats', data=json.dumps({'present_feats': use, 'vecs': matrix_vecs, 'missing': [int(m) for m in", "in ['object', 'str864'] else arr.astype('S64'), compression=compression) def _build_matrix_lookups(feats:List[str], vecs:List[str], feats_per_vec:List[str], row_wise:bool) -> Tuple[List[str],np.ndarray,Tuple[int,int]]:", "'add_meta_data'] def save_to_grp(arr:np.ndarray, grp:h5py.Group, name:str, compression:Optional[str]=None) -> None: r''' Save Numpy array as", "be set to null later using missing missing[i,j] = True else: for j,", "and tensor data is requested. This is ambiguous. Please only set one of", "as discreet variables targ_feats: (list of) column(s) in df to save as target", "argument for h5py, e.g. 'lzf' ''' savename = str(savename) os.system(f'rm {savename}.hdf5') os.makedirs(savename[:savename.rfind('/')], exist_ok=True)", "out_file = h5py.File(f'{savename}.hdf5', \"w\") lookup,missing,shape = None,None,None if matrix_vecs is not None: if", "save_to_grp(df[f].values, grp, f, compression=compression) else: print(f'{f} not found in file') if matrix_lookup is", "feats: list of all features in data cont_feats: list of continuous features cat_feats:", "use ''' grp = out_file.create_group('meta_data') grp.create_dataset('cont_feats', data=json.dumps(cont_feats)) grp.create_dataset('cat_feats', data=json.dumps(cat_feats)) grp.create_dataset('targ_feats', data=json.dumps(targ_feats)) if wgt_feat", "array must be compatible with the length of the data frame. tensor_name: if", "set, then this is the name that will to the foldfile's metadata. tensor_is_sparse:", "mat.reshape((len(df),*matrix_shape)) save_to_grp(mat, grp, 'matrix_inputs', compression=compression) elif tensor_data is not None: save_to_grp(tensor_data.astype('float32'), grp, 'matrix_inputs',", "continuous features; removing from continuous features') cont_feats = [f for f in cont_feats", "saved grp: group in which to save arr name: name of dataset to", "a dataset in an h5py Group Arguments: arr: array to be saved grp:", "import pandas as pd from typing import List, Union, Optional, Any, Tuple, Dict", "if arr.dtype.name not in ['object', 'str864'] else 'S64', data=arr if arr.dtype.name not in", "saved under matrix data, and this is incompatible with also setting `matrix_vecs`, `matrix_feats_per_vec`,", "missing missing[i,j] = True else: for j, v in enumerate(vecs): for i, c", "into an h5py Group Arguments: df: Dataframe from which to save data out_file:", "in which to save arr name: name of dataset to create compression: optional", "NaN. matrix_row_wise: whether objects encoded as a matrix should be encoded row-wise (i.e.", "frame. tensor_name: if `tensor_data` is set, then this is the name that will", "in both matrix features and continuous features; removing from continuous features') cont_feats =", "len(dup) > 1: print(f'{dup} present in both matrix features and continuous features; removing", "access this and automatically extract it to save the user from having to", "when displaying model information tensor_shp: The shape of the tensor data (exclusing batch", "# TODO infer target type automatically grp = out_file.create_group(f'fold_{fold_idx}') save_to_grp(np.hstack((df[cont_feats].values.astype('float32'), df[cat_feats].values.astype('float32'))), grp, 'inputs',", "save_to_grp(mat, grp, 'matrix_inputs', compression=compression) elif tensor_data is not None: save_to_grp(tensor_data.astype('float32'), grp, 'matrix_inputs', compression=compression)", "into cont_feats: list of columns in df to save as continuous variables cat_feats:", "'feats_per_vec': matrix_feats_per_vec, 'row_wise': matrix_row_wise, 'shape': shape})) elif tensor_name is not None: grp.create_dataset('matrix_feats', data=json.dumps({'present_feats':", "feats[0] # Temp value, to be set to null later using missing missing[i,j]", "to use for stratified splitting misc_feats: any extra columns to save wgt_feat: column", "m = np.vstack((coo_x.data, coo_x.coords))`, where `m` is the tensor passed to `tensor_data`. compression:", "This is ambiguous. Please only set one of the other.\") mat = df[matrix_lookup].values.astype('float32')", "is requested. This is ambiguous. Please only set one of the other.\") mat", "group in which to save arr name: name of dataset to create compression:", "misc_feats is not None: for f in misc_feats: if f in df.columns: save_to_grp(df[f].values,", "df.columns: save_to_grp(df[wgt_feat].values.astype('float32'), grp, 'weights', compression=compression) else: print(f'{wgt_feat} not found in file') if misc_feats" ]
[ "None, None except ValueError: dc = wx.ScreenDC() # compute for font size of", "= self.xpathEval(node, self.xpContent)[0] for sId in sIds.split(): l = self.xpathEval(ndPage, './/*[@id=\"%s\"]'%sId) ndItem =", "\"\"\"A rectangle \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now", "sIds = self.xpathEval(node, self.xpContent)[0] for sId in sIds.split(): l = self.xpathEval(ndPage, './/*[@id=\"%s\"]'%sId) ndItem", "= \"Removal of @%s\"%sAttrName else: node.set(sAttrName, sAttrValue) s = '@%s := \"%s\"'%(sAttrName,sAttrValue) return", "self._inc = self.xpathToInt(node, self.xpInc, 0) self._x,self._y = self._x-self._inc, self._y-self._inc self._w,self._h = self._w+2*self._inc, self._h+2*self._inc", "self.xpLineColorSlctd = cfg.get(sSurname, \"xpath_LineColor_Selected\") self.xpLineWidthSlctd = cfg.get(sSurname, \"xpath_LineWidth_Selected\") self.xpFillColorSlctd = cfg.get(sSurname, \"xpath_FillColor_Selected\") self.xpFillStyleSlctd", "return lo class DecoLink(Deco): \"\"\"A link from x1,y1 to x2,y2 \"\"\" def __init__(self,", "sArg = self.xpCtxt.xpathEval(xpExprArg)[0] sPythonExpr = \"(%s)(%s)\" % (sLambdaExpr, repr(sArg)) s = eval(sPythonExpr) else:", "fit the polygon and the extent of the 'x' character for this font", "cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return s def", "Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") try: iFontSizeX = 24 * abs(x2-x1)", "iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node)", "ln[0] #while nd and nd.name != \"PAGE\": nd = nd.parent while nd and", "class DecoREAD(Deco): \"\"\" READ PageXml has a special way to encode coordinates. like:", "font size return iFontSize, ExtentX, ExtentY \"\"\" (x1, y1), (x2, y2) = self._coordList_to_BB(ltXY)", "== iLARGENEG: self._x2 = self.xpathToInt(node, self.xpDfltX2, iLARGENEG) xpY2 = self.xpathToStr(node, self.xpEvalY2, '\"\"') self._y2", "import random from lxml import etree #import cStringIO import wx sEncoding = \"utf-8\"", "types.ListType: try: s = s[0].text except AttributeError: s = s[0] #should be an", "self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") self.xpFit = cfg.get(sSurname, \"xpath_fit_text_size\").lower() def", "if sToId: ln = self.xpathEval(node.doc.getroot(), '//*[@id=\"%s\"]'%sToId.strip()) if ln: #find the page number ndTo", "a one-node nodeset On error, return the default int value \"\"\" try: #", "bNoCase=True) try: x0, y0 = ltXY[0] _ldLabel = dCustom[self.xpathToStr(node, self.xpLabel, \"\").lower()] for _dLabel", "DecoImage(DecoBBXYWH): \"\"\"An image \"\"\" # in case the use wants to specify it", "\"\"\"A character encoded in Unicode We assume the unicode index is given in", "character for this font size return iFontSize, ExtentX, ExtentY \"\"\" (x1, y1), (x2,", "self.xpathToInt(node, self.xpLineWidth, 1) #draw a line obj = wxh.AddLine( [(self._x1, -self._y1), (self._x2, -self._y2)]", "\"xpath_radius\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.lsLineColor = cfg.get(sSurname, \"LineColors\").split()", "lo class DecoPolyLine(DecoREAD): \"\"\"A polyline along x1,y1,x2,y2, ...,xn,yn or x1,y1 x2,y2 .... xn,yn", "any sequnce of draw for a given page\"\"\" self.bInit = False def draw(self,", "# maybe the file is in a subfolder ? # e.g. \"S_Aicha_an_der_Donau_004-03_0005.jpg\" is", "Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class DecoText(DecoBBXYWH): \"\"\"A text \"\"\" def __init__(self,", "= False def draw(self, wxh, node): \"\"\"draw itself using the wx handle return", "Ex, Ey = dc.GetTextExtent(\"x\") del dc return iFontSize, Ex, Ey def draw(self, wxh,", "} \"\"\" dic = defaultdict(list) s = s.strip() lChunk = s.split('}') if lChunk:", "sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate else: # maybe the file is in", "= True iEllipseParam = min(w,h) / 2 wxh.AddEllipse((x, -y), (iEllipseParam, -iEllipseParam), LineColor=sLineColor, LineWidth=5,", "self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") self.xpX2, self.xpY2 = cfg.get(sSurname, \"xpath_x2\"), cfg.get(sSurname,", "self.xpathToStr(node, self.xpAttrValue, None) if sAttrName and sAttrValue != None: try: initialValue = self.dInitialValue[node]", "random.randrange(iMaxFC) Nl = random.randrange(iMaxFC) iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillStyle = self.xpathToStr(node, self.xpFillStyle,", "sCandidate = os.path.join(self.sImageFolder, sDir, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate except ValueError: pass", "self.xpathToInt(node, self.xpLineWidthSlctd, 1) sFillColor = self.xpathToStr(node, self.xpFillColorSlctd, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyleSlctd, \"Solid\")", "e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToStr return %s as default value\"%sDefault) return", "by offset found in the custom attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "try: x0, y0 = ltXY[0] _ldLabel = dCustom[self.xpathToStr(node, self.xpLabel, \"\").lower()] for _dLabel in", "wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) obj = wxh.AddScaledBitmap(img, (x,-y), h) lo.append(obj) except Exception, e: self.warning(\"DecoImageBox ERROR:", "sCoords = self.xpathToStr(node, self.xpCoords, \"\") if not sCoords: if node.get(\"id\") is None: self.warning(\"No", "@%s\"%sAttrName else: node.set(sAttrName, sAttrValue) s = '@%s := \"%s\"'%(sAttrName,sAttrValue) return s class DecoClickableRectangleJump(DecoBBXYWH):", "created WX objects \"\"\" lo = [] #add the text itself txt =", "to a node \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt)", "def endPage(self, node): \"\"\"called before any sequnce of draw for a given page\"\"\"", "#draw a line obj = wxh.AddLine( [(self._x1, -self._y1), (self._x2, -self._y2)] , LineWidth=iLineWidth ,", "# LineColor=sLineColor, # FillColor=sFillColor, # FillStyle=sFillStyle) lo.append(obj) \"\"\" lo = DecoBBXYWH.draw(self, wxh, node)", "self._y2 != iLARGENEG: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1)", "dict() lsKeyVal = sValues.split(';') #things like \"x:1\" for sKeyVal in lsKeyVal: if not", "a page \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now", "\"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) if xpExpr[0] == \"|\": #must be", "= self._w+2*self._inc, self._h+2*self._inc self._node = node return (self._x, self._y, self._w, self._h, self._inc) class", "draw(self, wxh, node): \"\"\" draw itself using the wx handle return a list", "and width/height. xpX, xpY, xpW, xpH are scalar XPath expressions to get the", "expressions that let us find the rectangle line and fill colors self.xpLineColor =", "itself txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor =", "We parse this syntax here and return a dictionary of list of dictionary", "objects\"\"\" DecoClusterCircle.count = DecoClusterCircle.count + 1 lo = DecoREAD.draw(self, wxh, node) if self._node", "h/2.0) if self.bInit: #draw a line iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) obj =", "= cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") self.xpX2, self.xpY2 = cfg.get(sSurname, \"xpath_x2\"), cfg.get(sSurname, \"xpath_y2\") #now", "toolbar \"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a configuration object", "ValueError: return int(round(float(s))) toInt = classmethod(toInt) def xpathToInt(self, node, xpExpr, iDefault=0, bShowError=True): \"\"\"The", "self._node != node: self._lxy = self._getCoordList(node) self._node = node if self._lxy: sLineColor =", "ltXY] lY = [_y for _x,_y in ltXY] return (min(lX), max(lY)), (max(lX), min(lY))", "except: pass return number,x,y,w,h class DecoClickableRectangleJumpToPage(DecoBBXYWH): \"\"\"A rectangle clicking on it jump to", "self._x-self._inc, self._y-self._inc self._w,self._h = self._w+2*self._inc, self._h+2*self._inc self._node = node return (self._x, self._y, self._w,", "\"\"\" A class that reflect a decoration to be made on certain XML", "sStartEmpty, sLambdaExpr, xpExprArg, sEndEmpty = xpExpr.split('|') assert sEndEmpty == \"\", \"Missing last '|'\"", "None\") return None def beginPage(self, node): \"\"\"called before any sequnce of draw for", "-self.prevY), (x, -y)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) else: self.bInit = True iEllipseParam", "file! xpCtxt is an XPath context \"\"\" self.sSurname = sSurname def __str__(self): return", "DecoBBXYWH.draw(self, wxh, node) #add the image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node,", "dic = defaultdict(list) s = s.strip() lChunk = s.split('}') if lChunk: for chunk", "try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType:", "[obj] + lo return lo def act(self, obj, node): \"\"\" Toggle the attribute", "True def setXPathContext(self, xpCtxt): pass class Deco: \"\"\"A general decoration class\"\"\" def __init__(self,", "\"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def draw(self,", "self.xpathToStr(node, self.xpFillColorSlctd, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyleSlctd, \"Solid\") else: sLineColor = self.xpathToStr(node, self.xpLineColor,", "else: self.warning(\"No coordinates: node id = %s\" % node.get(\"id\")) return [(0,0)] try: ltXY", "return (min(lX), max(lY)), (max(lX), min(lY)) class DecoREADTextLine(DecoREAD): \"\"\"A TextLine as defined by the", "cfg.get(sSurname, \"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return s def", "sDir, sFilePath)) if os.path.exists(sCandidate): sFilePath = sCandidate print(sFilePath) break if not os.path.exists(sFilePath): #", "( self.xpCoords, sCoords)) raise e return ltXY def _coordList_to_BB(self, ltXY): \"\"\" return (x1,", "wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") del dc return iFontSize, Ex, Ey def", "LineColor=sLineColor) lo.append(obj) return lo class DecoClickableRectangleSetAttr(DecoBBXYWH): \"\"\"A rectangle clicking on it add/remove an", "+= iTerm xSum += iTerm * (xprev+x) ySum += iTerm * (yprev+y) xprev,", "sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpCluster = cfg.get(sSurname, \"xpath\") self.xpContent = cfg.get(sSurname,", "= os.path.abspath(os.path.join(sLocalDir, sDir, sFilePath)) if os.path.exists(sCandidate): sFilePath = sCandidate print(sFilePath) break if not", "the selected nodes \"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a", "wxh, node) if self._node != node: self._x1 = self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 =", "wx.ScreenDC() # compute for font size of 24 and do proportional dc.SetFont(wx.Font(24, Family,", "cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") self.xpX2, self.xpY2 = cfg.get(sSurname, \"xpath_x2\"), cfg.get(sSurname, \"xpath_y2\") #now get", "1 lo = DecoREAD.draw(self, wxh, node) if self._node != node: self._laxyr = []", "iFontSize = min(iFontSizeX, iFontSizeY) dc.SetFont(wx.Font(iFontSize, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") del", "s += \"+(coords=%s)\" % (self.xpCoords) return s def getArea_and_CenterOfMass(self, lXY): \"\"\" https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone return", "go thru each item ndPage = node.xpath(\"ancestor::*[local-name()='Page']\")[0] sIds = self.xpathEval(node, self.xpContent)[0] for sId", "the default int value \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) s =", "sMsg=\"\"): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_xpath_error except AttributeError: Deco._s_prev_xpath_error = \"\" Deco._prev_xpath_error_count", "cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions that", "(sx, sy) = _sPair.split(',') ltXY.append((Deco.toInt(sx), Deco.toInt(sy))) except Exception as e: logging.error(\"ERROR: polyline coords", "w = self.xpathToInt(ndTo, self.xp_wTo, None) h = self.xpathToInt(ndTo, self.xp_hTo, None) if x==None or", "= DecoBBXYWH.draw(self, wxh, node) #add the image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath =", "xpY2 = self.xpathToStr(node, self.xpEvalY2, '\"\"') self._y2 = self.xpathToInt(node, xpY2, iLARGENEG, False) #do not", "syntax here and return a dictionary of list of dictionary Example: parseCustomAttr( \"readingOrder", "page number ndTo = nd = ln[0] #while nd and nd.name != \"PAGE\":", "self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillColor = self.xpathToStr(node, self.xpFillColor, \"#000000\")", "txt , Family=wx.FONTFAMILY_TELETYPE) dCustom = self.parseCustomAttr(node.get(\"custom\"), bNoCase=True) try: x0, y0 = ltXY[0] _ldLabel", "sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontColor = cfg.get(sSurname,", "{offset:0; length:11;} Item-price {offset:12; length:2;}\"> <Coords points=\"985,390 1505,390 1505,440 985,440\"/> <Baseline points=\"985,435 1505,435\"/>", "__str__(self): s = \"%s=\"%self.__class__ return s def _getFontSize(self, node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE): \"\"\"", "cfg.get(sSurname, \"xpath_ToPageNumber\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def", "the attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now", "+= \"\\n--- XML node = %s\" % sNode s += \"\\n\" + \"-\"*60", "find the rectangle line and fill colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor =", "in the custom attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREADTextLine.__init__(self, cfg, sSurname,", "= [] #need to go thru each item ndPage = node.xpath(\"ancestor::*[local-name()='Page']\")[0] sIds =", "s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return s def getArea_and_CenterOfMass(self, lXY):", "class %s\"%self.__class__ s += \"\\n--- xpath=%s\" % xpExpr s += \"\\n--- Python Exception=%s\"", "self.xp_wTo: x = self.xpathToInt(ndTo, self.xp_xTo, None) y = self.xpathToInt(ndTo, self.xp_yTo, None) w =", "node \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now get", "\"\"\" @classmethod def parseCustomAttr(cls, s, bNoCase=True): \"\"\" The custom attribute contains data in", "self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return", "self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt,", "= cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") #cached values self._node = None self._lxy", ", LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoREAD(Deco): \"\"\" READ PageXml has", "rectangle line and fill colors self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\")", "FillColor=sFillColor, FillStyle=sFillStyle) lo = [obj] + lo return lo def act(self, obj, node):", "raise ValueError(\"Expected a comma-separated string, got '%s'\"%sKeyVal) sKey = sKey.strip().lower() if bNoCase else", "s = \"%s=\"%self.__class__ s += \"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpEvalX2,", "name in lName: name = name.strip().lower() if bNoCase else name.strip() dic[name].append(dicValForName) return dic", "cfg.get(sSurname, \"xpath_AttrName\") self.xpAttrValue = cfg.get(sSurname, \"xpath_AttrValue\") self.dInitialValue = {} self.xpLineColorSlctd = cfg.get(sSurname, \"xpath_LineColor_Selected\")", "xpCtxt): \"\"\" cfg is a configuration object sSurname is the surname of the", "\"Solid\") for (_a, x, y, r) in self._laxyr: #draw a circle sFillColor =", "indicate the precise arrival point? if self.xp_xTo and self.xp_yTo and self.xp_hTo and self.xp_wTo:", "special case: when an attr was set, then saved, re-clicking on it wil", "int(_dLabel[\"length\"]) x = x0 + Ex * iOffset y = -y0+iFontSize/6 obj =", "= cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrName =", "namespace sEnabled = cfg.get(sSurname, \"enabled\").lower() self.bEnabled = sEnabled in ['1', 'yes', 'true'] def", "cfg, sSurname, xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") #the following expression", "sKey, sVal = sKeyVal.split(':') except Exception: raise ValueError(\"Expected a comma-separated string, got '%s'\"%sKeyVal)", "return s def draw(self, wxh, node): \"\"\"draw itself using the wx handle return", "file! xpCtxt is an XPath context \"\"\" self.sSurname = sSurname self.xpMain = cfg.get(sSurname,", "s, bNoCase=True): \"\"\" The custom attribute contains data in a CSS style syntax.", "node): lo = Deco.draw(self, wxh, node) if self._node != node: self._lxy = self._getCoordList(node)", "on the given node The XPath expression should return a scalar or a", "in cache\"\"\" if self._node != node: self._x = self.xpathToInt(node, self.xpX, 1) self._y =", "sAttrValue = self.xpathToStr(node, self.xpAttrValue, None) if sAttrName and sAttrValue != None: try: initialValue", "\"\"\" cfg is a config file sSurname is the decoration surname and the", "= self.xpathToInt(node, self.xpLineWidth, 1) sFillColor = self.xpathToStr(node, self.xpFillColor, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyle,", "self.xpDfltY2 = cfg.get(sSurname, \"xpath_x2_default\"), cfg.get(sSurname, \"xpath_y2_default\") #now get the xpath expressions that let", "self.xpLineWidth, 1) for (x1, y1), (x2, y2) in zip(self._lxy, self._lxy[1:]): #draw a line", "sAttrName and sAttrValue != None: if node.prop(sAttrName) == sAttrValue: sLineColor = self.xpathToStr(node, self.xpLineColorSlctd,", "\"%s=\"%self.__class__ s += \"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpX2, self.xpY2) return", "cfg.get(sSurname, \"xpath_LineColor_Selected\") self.xpLineWidthSlctd = cfg.get(sSurname, \"xpath_LineWidth_Selected\") self.xpFillColorSlctd = cfg.get(sSurname, \"xpath_FillColor_Selected\") self.xpFillStyleSlctd = cfg.get(sSurname,", "nd.name != \"PAGE\": nd = nd.parent while nd and nd.name != sPageTag: nd", "data in a CSS style syntax. We parse this syntax here and return", "\"\"\" Toggle the attribute value \"\"\" s = \"do nothing\" sAttrName = self.xpathToStr(node,", "for that name dicValForName = dict() lsKeyVal = sValues.split(';') #things like \"x:1\" for", "\"\"\"A rectangle clicking on it jump to a page \"\"\" def __init__(self, cfg,", "sAttrValue != None: try: initialValue = self.dInitialValue[node] except KeyError: initialValue = node.prop(sAttrName) #first", "None, None bbHighlight = None sToId = self.xpathToStr(node, self.xpAttrToId , None) if sToId:", "of created WX objects\"\"\" DecoClusterCircle.count = DecoClusterCircle.count + 1 lo = DecoREAD.draw(self, wxh,", "@classmethod def parseCustomAttr(cls, s, bNoCase=True): \"\"\" The custom attribute contains data in a", "== 0.0: raise ValueError(\"surface == 0.0\") fA = fA / 2 xg, yg", "< 1000: if sMsg != Deco._s_prev_warning: logging.warning(sMsg) Deco._warning_count += 1 Deco._s_prev_warning = sMsg", "xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") #the", "lo.append(obj) return lo def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class DecoUnicodeChar(DecoText):", "\"xpath_y2\") #now get the xpath expressions that let us find the rectangle line", "= self.xpathToStr(node, self.xpFillStyle, \"Solid\") obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor,", "iFontSize = iFontSizeX elif sFit == \"y\": iFontSize = iFontSizeY else: iFontSize =", "self.xpLabel = cfg.get(sSurname, \"xpath_label\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpBackgroundColor = cfg.get(sSurname, \"xpath_background_color\") def", "sClass): \"\"\"given a decoration type, return the associated class\"\"\" c = globals()[sClass] if", "def draw(self, wxh, node): \"\"\"draw itself using the wx handle return a list", "node) if self._node != node: self._x1 = self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node,", "Ex, Ey = self._getFontSize(node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE) # x, y = ltXY[0] (x,", "except KeyError: pass return lo class DecoPolyLine(DecoREAD): \"\"\"A polyline along x1,y1,x2,y2, ...,xn,yn or", "fA += iTerm xSum += iTerm * (xprev+x) ySum += iTerm * (yprev+y)", "self.xpEvalY2) return s def draw(self, wxh, node): \"\"\"draw itself using the wx handle", "xpExpr, eExcpt, sMsg=\"\"): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_xpath_error except AttributeError: Deco._s_prev_xpath_error =", "= initialValue if node.get(sAttrName) == sAttrValue: #back to previous value if initialValue ==", "bool(sFilePath): img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) try: if h > 0: obj = wxh.AddScaledBitmap(img,", "chunk.strip() if not chunk: continue try: sNames, sValues = chunk.split('{') #things like: (\"a,b\",", "self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) for (x1, y1), (x2, y2)", "= node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) if xpExpr[0] == \"|\": #must be a lambda assert xpExpr[:8]", "image \"\"\" # in case the use wants to specify it via the", "of created WX objects\"\"\" lo = [] #add the text itself txt =", "value return Deco.toInt(s) except Exception, e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToInt return", "sCandidate = os.path.join(self.sImageFolder, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate else: # maybe the", "xpath_content=@content xpath_radius=40 xpath_item_lxy=./pg:Coords/@points xpath_LineWidth=\"1\" xpath_FillStyle=\"Transparent\" LineColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" FillColors=\"BLUE SIENNA", "ERROR: File %s: %s\"%(sFilePath, str(e))) lo.append( DecoRectangle.draw(self, wxh, node) ) return lo class", "class DecoClickableRectangleJump(DecoBBXYWH): \"\"\"A rectangle clicking on it jump to a node \"\"\" def", "itself txt = self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') sLineColor = self.xpathToStr(node,", "defaultdict(list) s = s.strip() lChunk = s.split('}') if lChunk: for chunk in lChunk:", "sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) def _getCoordList(self, node): lCoord = DecoPolyLine._getCoordList(self, node)", "the PageXml format of the READ project <TextLine id=\"line_1551946877389_284\" custom=\"readingOrder {index:0;} Item-name {offset:0;", "y = self.xpathToInt(ndTo, self.xp_yTo, None) w = self.xpathToInt(ndTo, self.xp_wTo, None) h = self.xpathToInt(ndTo,", "y if fA == 0.0: raise ValueError(\"surface == 0.0\") fA = fA /", "Size=iFontSize, Family=wx.ROMAN, Position='cl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo def getText(self, wxh, node):", "= DecoRectangle.draw(self, wxh, node) #add the text itself txt = self.xpathToStr(node, self.xpContent, \"\")", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoText.__init__(self, cfg, sSurname, xpCtxt) self.base = int(cfg.get(sSurname,", "list of created WX objects\"\"\" lo = [] #add the image itself x,y,w,h,inc", "a list of created WX objects\"\"\" lo = DecoRectangle.draw(self, wxh, node) #add the", "xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self): s =", "LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo.append(obj) return lo class DecoTextBox(DecoRectangle): \"\"\"A text within a", "self.sImageFolder: sCandidate = os.path.join(self.sImageFolder, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate else: # maybe", "\"\" class DecoImageBox(DecoRectangle): \"\"\"An image with a box around it \"\"\" def __init__(self,", "return True def draw(self, wxh, node): \"\"\"draw itself using the wx handle return", "[(self._x1, -self._y1), (self._x2, -self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoREAD(Deco):", "'%s' -> '%s'\" % ( self.xpCoords, sCoords)) raise e return ltXY def _coordList_to_BB(self,", "a line obj = wxh.AddLine( [(x1, -y1), (x2, -y2)] , LineWidth=iLineWidth , LineColor=sLineColor)", "def draw(self, wxh, node): \"\"\"draw the associated decorations, return the list of wx", "image is in a folder with same name as XML file? (Transkribus style)", "iLARGENEG: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) #draw a", "[\"file://\", \"file:/\"]: if sUrl[0:len(sPrefix)] == sPrefix: sLocalDir = os.path.dirname(sUrl[len(sPrefix):]) sDir,_ = os.path.splitext(os.path.basename(sUrl)) sCandidate", "int(y + h/2.0) if self.bInit: #draw a line iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1)", "On error, return the default int value \"\"\" try: # s = node.xpathEval(xpExpr)", "custom=\"readingOrder {index:0;} Item-name {offset:0; length:11;} Item-price {offset:12; length:2;}\"> <Coords points=\"985,390 1505,390 1505,440 985,440\"/>", "by the PageXml format of the READ project <TextLine id=\"line_1551946877389_284\" custom=\"readingOrder {index:0;} Item-name", "sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue = self.xpathToStr(node, self.xpAttrValue, None) if sAttrName", "the xpath expressions that let uis find x,y,w,h from a selected node self.xpX,", "8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') obj = wxh.AddScaledTextBox(txt, (x+x_inc, -y-y_inc), Size=iFontSize, Family=wx.ROMAN,", "self._node = node #lo = DecoClosedPolyLine.draw(self, wxh, node) #add the text itself x,", "a CSS style syntax. We parse this syntax here and return a dictionary", "xpCtxt) self.xpCluster = cfg.get(sSurname, \"xpath\") self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpRadius = cfg.get(sSurname, \"xpath_radius\")", "import glob import logging import random from lxml import etree #import cStringIO import", "File %s: %s\"%(sFilePath, str(e))) return lo class DecoOrder(DecoBBXYWH): \"\"\"Show the order with lines", "2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) def _getCoordList(self,", "\"%s\"'%(sAttrName,initialValue) else: if not sAttrValue: del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else:", "size return iFontSize, ExtentX, ExtentY \"\"\" (x1, y1), (x2, y2) = self._coordList_to_BB(ltXY) sFit", ") --> { 'readingOrder': [{ 'index':'4' }], 'structure':[{'type':'catch-word'}] } \"\"\" dic = defaultdict(list)", "self.xp_xTo and self.xp_yTo and self.xp_hTo and self.xp_wTo: x = self.xpathToInt(ndTo, self.xp_xTo, None) y", "True for s in lCandidate: if os.path.exists(s): sFilePath = s bKO = False", "if self._node != node: self._lxy = self._getCoordList(node) self._node = node #lo = DecoClosedPolyLine.draw(self,", "the attribute value \"\"\" s = \"do nothing\" sAttrName = self.xpathToStr(node, self.xpAttrName ,", "self.xpathToStr(node, self.xpCoords, \"\") if not sCoords: if node.get(\"id\") is None: self.warning(\"No coordinates: node", "= self.xpathToInt(node, self.xpY, 1) self._w = self.xpathToInt(node, self.xpW, 1) self._h = self.xpathToInt(node, self.xpH,", "ltXY): \"\"\" return (x1, y1), (x2, y2) \"\"\" lX = [_x for _x,_y", "e return ltXY def _coordList_to_BB(self, ltXY): \"\"\" return (x1, y1), (x2, y2) \"\"\"", "img.GetHeight()) lo.append(obj) except Exception, e: self.warning(\"DecoImage ERROR: File %s: %s\"%(sFilePath, str(e))) return lo", "if sMsg != Deco._s_prev_warning: logging.warning(sMsg) Deco._warning_count += 1 Deco._s_prev_warning = sMsg def toInt(cls,", "Deco._s_prev_warning except AttributeError: Deco._s_prev_warning = \"\" Deco._warning_count = 0 # if sMsg !=", "= nd.parent while nd and nd.name != sPageTag: nd = nd.parent try: #number", "thru each item ndPage = node.xpath(\"ancestor::*[local-name()='Page']\")[0] sIds = self.xpathEval(node, self.xpContent)[0] for sId in", "that reflect a decoration to be made on certain XML node using WX", "lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"BLACK\")", "node.getroottree().docinfo.URL.decode('utf-8') # py2 ... for sPrefix in [\"file://\", \"file:/\"]: if sUrl[0:len(sPrefix)] == sPrefix:", "def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\")", "for _dLabel in _ldLabel: try: iOffset = int(_dLabel[\"offset\"]) iLength = int(_dLabel[\"length\"]) x =", "self.xpAttrValue, None) if sAttrName and sAttrValue != None: if node.prop(sAttrName) == sAttrValue: sLineColor", "s += \"\\n--- XML node = %s\" % sNode s += \"\\n\" +", "n in node.xpathEval(self.xpX): print n.serialize() iLARGENEG = -9999 lo = Deco.draw(self, wxh, node)", "self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return", "1505,440 985,440\"/> or <Baseline points=\"985,435 1505,435\"/> \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self,", "self.xpLabel, \"\").lower()] for _dLabel in _ldLabel: try: iOffset = int(_dLabel[\"offset\"]) iLength = int(_dLabel[\"length\"])", "try: img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) obj = wxh.AddScaledBitmap(img, (x,-y), h) lo.append(obj) except Exception,", "expressions that let us find the rectangle line and fill colors self.xpLineWidth =", "xpExpr): \"\"\" evaluate the xpath expression return None on error \"\"\" try: #", "x = self.xpathToInt(ndTo, self.xp_xTo, None) y = self.xpathToInt(ndTo, self.xp_yTo, None) w = self.xpathToInt(ndTo,", "line obj = wxh.AddLine( [(x1, -y1), (x2, -y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj)", "def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class READ_custom: \"\"\" Everything related", "_x,_y in ltXY] lY = [_y for _x,_y in ltXY] return (min(lX), max(lY)),", "the unicode index is given in a certain base, e.g. 10 or 16", "sLineColor = self.xpathToStr(node, self.xpLineColor, \"BLACK\") x, y = int(x + w/2.0), int(y +", "x2,y2 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpX1, self.xpY1", "should return a string on the given node The XPath expression should return", "any error if self._x2 == iLARGENEG: self._x2 = self.xpathToInt(node, self.xpDfltX2, iLARGENEG) xpY2 =", "= self.xpathToInt(node, self.xpDfltY2, iLARGENEG) self._node = node if self._x1 != iLARGENEG and self._y1", "s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def beginPage(self, node): \"\"\"called before", "handle return a list of created WX objects\"\"\" # print node.serialize() # print", "self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y-h/2.0), Size=iFontSize, Family=wx.ROMAN,", "s[0].text except AttributeError: s = s[0] return s except Exception, e: if bShowError:", "iLineWidth = self.xpathToInt(node, self.xpLineWidthSlctd, 1) sFillColor = self.xpathToStr(node, self.xpFillColorSlctd, \"#000000\") sFillStyle = self.xpathToStr(node,", "= cfg.get(sSurname, \"xpath_LineColor\") self._node = None def __str__(self): s = \"%s=\"%self.__class__ s +=", "given XPath expression should return an int on the given node. The XPath", "an attribute the rectangle color is indicative of the presence/absence of the attribute", "bounding box defined by X,Y for its top-left corner and width/height. xpX, xpY,", "lo.append(obj) except Exception, e: self.warning(\"DecoImageBox ERROR: File %s: %s\"%(sFilePath, str(e))) lo.append( DecoRectangle.draw(self, wxh,", "= node.prop(sAttrName) #first time self.dInitialValue[node] = initialValue if node.get(sAttrName) == sAttrValue: #back to", "XPath context \"\"\" self.sSurname = sSurname self.xpMain = cfg.get(sSurname, \"xpath\") # a main", "self.xpX2, self.xpY2) return s def draw(self, wxh, node): \"\"\"draw itself using the wx", "if sAttrName and sAttrValue != None: if node.prop(sAttrName) == sAttrValue: sLineColor = self.xpathToStr(node,", "cfg.get(sSurname, \"xpath_font_color\") self.xpFit = cfg.get(sSurname, \"xpath_fit_text_size\").lower() def __str__(self): s = \"%s=\"%self.__class__ return s", "cfg.get(sSurname, \"xpath_content\") self.xpFontSize = cfg.get(sSurname, \"xpath_font_size\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s", "list of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node)", "= [_x for _x,_y in ltXY] lY = [_y for _x,_y in ltXY]", "except Exception, e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToInt return %d as default", "= None, None except ValueError: dc = wx.ScreenDC() # compute for font size", "\"y\": iFontSize = iFontSizeY else: iFontSize = min(iFontSizeX, iFontSizeY) dc.SetFont(wx.Font(iFontSize, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))", "the annotation by offset found in the custom attribute \"\"\" def __init__(self, cfg,", "\"xpath_content\") self.xpRadius = cfg.get(sSurname, \"xpath_radius\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\")", "__str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return s def getArea_and_CenterOfMass(self,", "+= DecoBBXYWH.__str__(self) return s def isActionable(self): return True def draw(self, wxh, node): \"\"\"draw", "rectangle clicking on it jump to a node \"\"\" def __init__(self, cfg, sSurname,", "draw for a given page\"\"\" pass def draw(self, wxh, node): \"\"\"draw the associated", "e: logging.error(\"ERROR: polyline coords are bad: '%s' -> '%s'\" % ( self.xpCoords, sCoords))", "# Position and computation of font size ltXY = self._getCoordList(node) iFontSize, Ex, Ey", "the image is in a folder with same name as XML file? (Transkribus", "12</Unicode> </TextEquiv> </TextLine> \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt)", "XPath expressions to get the associated x,y,w,h values from the selected nodes \"\"\"", "iEllipseParam = min(w,h) / 2 wxh.AddEllipse((x, -y), (iEllipseParam, -iEllipseParam), LineColor=sLineColor, LineWidth=5, FillStyle=\"Transparent\") self.prevX,", "yg, r) ) self._node = node if self._laxyr: iMaxFC = len(self.lsFillColor) iMaxLC =", "[(self.prevX, -self.prevY), (x, -y)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) else: self.bInit = True", "sDefault, bShowError=True): \"\"\"The given XPath expression should return a string on the given", "using the wx handle return a list of created WX objects\"\"\" lo =", "points=\"985,435 1505,435\"/> \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpCoords", "= s.split('}') if lChunk: for chunk in lChunk: #things like \"a {x:1\" chunk", "if self._node != node: self._laxyr = [] #need to go thru each item", "1) #draw a line obj = wxh.AddLine( [(self._x1, -self._y1), (self._x2, -self._y2)] , LineWidth=iLineWidth", "self.xpH = cfg.get(sSurname, \"xpath_w\"), cfg.get(sSurname, \"xpath_h\") self.xpInc = cfg.get(sSurname, \"xpath_incr\") #to increase the", "try: sNode = etree.tostring(node) except: sNode = str(node) if len(sNode) > iMaxLen: sNode", "self._node = node if self._x1 != iLARGENEG and self._y1 != iLARGENEG and self._x2", ", Position='tl' , Color=sFontColor) lo.append(obj) return lo def getText(self, wxh, node): return self.xpathToStr(node,", "self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y-h/2.0), Size=iFontSize, Family=wx.ROMAN, Position='cl',", "\"xpath_AttrName\") self.xpAttrValue = cfg.get(sSurname, \"xpath_AttrValue\") self.dInitialValue = {} self.xpLineColorSlctd = cfg.get(sSurname, \"xpath_LineColor_Selected\") self.xpLineWidthSlctd", "node): \"\"\" Toggle the attribute value \"\"\" s = \"do nothing\" sAttrName =", "+= 1 Deco._s_prev_warning = sMsg def toInt(cls, s): try: return int(s) except ValueError:", "= %s\" % sNode s += \"\\n\" + \"-\"*60 + \"\\n\" logging.warning(s) def", "decoration class\"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a configuration object", "self.xpLineWidthSlctd, 1) sFillColor = self.xpathToStr(node, self.xpFillColorSlctd, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyleSlctd, \"Solid\") else:", "an xpath error\"\"\" try: Deco._s_prev_warning except AttributeError: Deco._s_prev_warning = \"\" Deco._warning_count = 0", "a config file sSurname is the decoration surname and the section name in", "cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xp_xTo = cfg.get(sSurname, \"xpath_xTo\") self.xp_yTo = cfg.get(sSurname,", "if fA == 0.0: raise ValueError(\"surface == 0.0\") fA = fA / 2", "yg) else: return fA, (xg, yg) assert fA >0 and xg >0 and", "= \"\" Deco._warning_count = 0 # if sMsg != Deco._s_prev_warning and Deco._warning_count <", "toInt = classmethod(toInt) def xpathToInt(self, node, xpExpr, iDefault=0, bShowError=True): \"\"\"The given XPath expression", "node.get(\"id\")) return [(0,0)] try: ltXY = [] for _sPair in sCoords.split(' '): (sx,", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREADTextLine.__init__(self, cfg, sSurname, xpCtxt) self.xpLabel = cfg.get(sSurname,", "except ValueError: dc = wx.ScreenDC() # compute for font size of 24 and", "and self.xp_hTo and self.xp_wTo: x = self.xpathToInt(ndTo, self.xp_xTo, None) y = self.xpathToInt(ndTo, self.xp_yTo,", "self._node = node if self._lxy: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node,", "Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") self.xpX2, self.xpY2", "undefined.\") fA = 0.0 xSum, ySum = 0, 0 xprev, yprev = lXY[-1]", "[_x for _x,_y in ltXY] lY = [_y for _x,_y in ltXY] return", "s += \"\\n--- Python Exception=%s\" % str(eExcpt) if sMsg: s += \"\\n--- Info:", "objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sAttrName = self.xpathToStr(node, self.xpAttrName", "= self.xpathToInt(node, self.xpH, 1) self._inc = self.xpathToInt(node, self.xpInc, 0) self._x,self._y = self._x-self._inc, self._y-self._inc", "height self._node = None def __str__(self): s = Deco.__str__(self) s += \"+(x=%s y=%s", "class DecoClickableRectangleJumpToPage(DecoBBXYWH): \"\"\"A rectangle clicking on it jump to a page \"\"\" def", "in folder \"S_Aicha_an_der_Donau_004-03\" try: sDir = sFilePath[:sFilePath.rindex(\"_\")] sCandidate = os.path.join(self.sImageFolder, sDir, sFilePath) if", "DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") def", "self.xp_hTo = cfg.get(sSurname, \"xpath_hTo\") self.xpAttrToId = cfg.get(sSurname, \"xpath_ToId\") self.config = cfg.jl_hack_cfg #HACK def", "decoration type, return the associated class\"\"\" c = globals()[sClass] if type(c) != types.ClassType:", "#draw a line iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) obj = wxh.AddLine( [(self.prevX, -self.prevY),", "= wx.ScreenDC() # compute for font size of 24 and do proportional dc.SetFont(wx.Font(24,", "= \", self.lsLineColor print \"DecoClusterCircle lsFillColor = \", self.lsFillColor def __str__(self): s =", "endPage(self, node): \"\"\"called before any sequnce of draw for a given page\"\"\" pass", "cfg.get(sSurname, \"eval_xpath_x2\"), cfg.get(sSurname, \"eval_xpath_y2\") self.xpDfltX2, self.xpDfltY2 = cfg.get(sSurname, \"xpath_x2_default\"), cfg.get(sSurname, \"xpath_y2_default\") #now get", "WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sAttrName = self.xpathToStr(node,", "READ project <TextLine id=\"line_1551946877389_284\" custom=\"readingOrder {index:0;} Item-name {offset:0; length:11;} Item-price {offset:12; length:2;}\"> <Coords", "wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) try: if h > 0: obj = wxh.AddScaledBitmap(img, (x,-y), h) else:", "yg >0, \"%s\\t%s\"%(lXY (fA, (xg, yg))) return fA, (xg, yg) def draw(self, wxh,", "Exception as e: logging.error(\"ERROR: polyline coords are bad: '%s' -> '%s'\" % (", "in lXY: iTerm = xprev*y - yprev*x fA += iTerm xSum += iTerm", "self.warning(\"absence of text: cannot compute font size along X axis\") iFontSizeX = 8", "self.xpathToInt(node, self.xpInc, 0) self._x,self._y = self._x-self._inc, self._y-self._inc self._w,self._h = self._w+2*self._inc, self._h+2*self._inc self._node =", "Family=wx.ROMAN, Position='cl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo def getText(self, wxh, node): return", "sUrl = node.getroottree().docinfo.URL.decode('utf-8') # py2 ... for sPrefix in [\"file://\", \"file:/\"]: if sUrl[0:len(sPrefix)]", "menu sImageFolder = None def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt)", "= self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y+inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None)", ", LineColor=sLineColor , BackgroundColor=sBackgroundColor) lo.append(obj) except KeyError: pass except KeyError: pass return lo", "lCoord = DecoPolyLine._getCoordList(self, node) if lCoord: lCoord.append(lCoord[0]) return lCoord class DecoTextPolyLine(DecoPolyLine, DecoText): \"\"\"A", "DecoClusterCircle.count + 1 lo = DecoREAD.draw(self, wxh, node) if self._node != node: self._laxyr", "in lName: name = name.strip().lower() if bNoCase else name.strip() dic[name].append(dicValForName) return dic class", "polyline that closes automatically the shape <NAME> - September 2016 \"\"\" def __init__(self,", "= len(self.lsLineColor) if False: Nf = DecoClusterCircle.count Nl = Nf else: Nf =", "GREEN\" enabled=1 \"\"\" count = 0 def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg,", "self._inc) class DecoRectangle(DecoBBXYWH): \"\"\"A rectangle \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg,", "Family=wx.FONTFAMILY_TELETYPE) # x, y = ltXY[0] (x, _y1), (_x2, y) = self._coordList_to_BB(ltXY) obj", "yprev = lXY[-1] for x, y in lXY: iTerm = xprev*y - yprev*x", "def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath", "obj, node): \"\"\" return the page number of the destination or None on", "if len(lXY) < 2: raise ValueError(\"Only one point: polygon area is undefined.\") fA", "lo.append(obj) return lo class DecoClickableRectangleSetAttr(DecoBBXYWH): \"\"\"A rectangle clicking on it add/remove an attribute", "chunk = chunk.strip() if not chunk: continue try: sNames, sValues = chunk.split('{') #things", "self.lsFillColor[Nf % iMaxFC] if self.lsLineColor: sLineColor = self.lsLineColor[Nl % iMaxLC] else: sLineColor =", "the decoration and the section name in the config file! xpCtxt is an", "= node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) return self.xpCtxt.xpathEval(xpExpr) except Exception, e: self.xpathError(node, xpExpr, e, \"xpathEval return", "sSurname self.xpMain = cfg.get(sSurname, \"xpath\") # a main XPath that select nodes to", "y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpX2, self.xpY2) return s def draw(self, wxh,", "print self.xpX # for n in node.xpathEval(self.xpX): print n.serialize() lo = DecoREAD.draw(self, wxh,", "= self.xpathToStr(node, self.xpAttrValue, None) if sAttrName and sAttrValue != None: try: initialValue =", "None, None, None, None except: pass return number,x,y,w,h class DecoClickableRectangleJumpToPage(DecoBBXYWH): \"\"\"A rectangle clicking", "Nf = DecoClusterCircle.count Nl = Nf else: Nf = random.randrange(iMaxFC) Nl = random.randrange(iMaxFC)", "the font size so as to fit the polygon and the extent of", "#add the image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if", "= wxh.AddScaledText(txt, (x, -y+iFontSize/6), Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='tl' , Color=sFontColor) lo.append(obj) return", "\"\"\"A rectangle clicking on it jump to a node \"\"\" def __init__(self, cfg,", "wx.BITMAP_TYPE_ANY) obj = wxh.AddScaledBitmap(img, (x,-y), h) lo.append(obj) except Exception, e: self.warning(\"DecoImageBox ERROR: File", "self.xpathToInt(node, self.xpLineWidth, 1) obj = wxh.AddLine( [(self.prevX, -self.prevY), (x, -y)] , LineWidth=iLineWidth ,", "FillStyle=sFillStyle) # obj = wxh.AddRectangle((x, -y), (20, 20), # LineWidth=iLineWidth, # LineColor=sLineColor, #", "obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) \"\"\" return lo", "import etree #import cStringIO import wx sEncoding = \"utf-8\" def setEncoding(s): global sEncoding", "created WX objects\"\"\" lo = [] #add the text itself txt = self.getText(wxh,", "self._y-self._inc self._w,self._h = self._w+2*self._inc, self._h+2*self._inc self._node = node return (self._x, self._y, self._w, self._h,", "= cfg.get(sSurname, \"xpath_incr\") #to increase the BB width and height self._node = None", "a separator of decoration in the toolbar \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "within a bounding box (a rectangle) \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self,", "KeyError: pass except KeyError: pass return lo class DecoPolyLine(DecoREAD): \"\"\"A polyline along x1,y1,x2,y2,", "(x, -y+iFontSize/6), Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='tl' , Color=sFontColor) lo.append(obj) return lo def", "1505,390 1505,440 985,440\"/> <Baseline points=\"985,435 1505,435\"/> <TextEquiv> <Unicode>Salgadinhos 12</Unicode> </TextEquiv> </TextLine> \"\"\" def", "/ len(txt) except: self.warning(\"absence of text: cannot compute font size along X axis\")", "yg) = self.getArea_and_CenterOfMass(lxy) r = self.xpathToInt(ndItem, self.xpRadius, 1) self._laxyr.append( (fA, xg, yg, r)", "try: sDir = sFilePath[:sFilePath.rindex(\"_\")] sCandidate = os.path.join(self.sImageFolder, sDir, sFilePath) if os.path.exists(sCandidate): sFilePath =", "fA, (xg, yg) = self.getArea_and_CenterOfMass(lxy) r = self.xpathToInt(ndItem, self.xpRadius, 1) self._laxyr.append( (fA, xg,", "xg, yg, r) ) self._node = node if self._laxyr: iMaxFC = len(self.lsFillColor) iMaxLC", "\"\", \"Missing last '|'\" sArg = self.xpCtxt.xpathEval(xpExprArg)[0] sPythonExpr = \"(%s)(%s)\" % (sLambdaExpr, repr(sArg))", "self.sSurname = sSurname self.xpMain = cfg.get(sSurname, \"xpath\") # a main XPath that select", "self.xpH) return s def runXYWHI(self, node): \"\"\"get the X,Y values for a node", "= sCandidate except ValueError: pass if not os.path.exists(sFilePath): #maybe the image is in", "the declaration of some namespace sEnabled = cfg.get(sSurname, \"enabled\").lower() self.bEnabled = sEnabled in", "type=DecoPolyLine xpath=.//TextLine/Coords xpath_lxy=@points xpath_LineColor=\"RED\" xpath_FillStyle=\"Solid\" <NAME> - March 2016 \"\"\" def __init__(self, cfg,", "self._x1 = self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) self._x2 = self.xpathToInt(node,", "CSS style syntax. We parse this syntax here and return a dictionary of", "lXY): \"\"\" https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone return A, (Xg, Yg) which are the area and the", "sNode s += \"\\n\" + \"-\"*60 + \"\\n\" logging.warning(s) def warning(self, sMsg): \"\"\"report", "= self.xpathToInt(node, self.xpDfltX2, iLARGENEG) xpY2 = self.xpathToStr(node, self.xpEvalY2, '\"\"') self._y2 = self.xpathToInt(node, xpY2,", "it wil remove it. del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName,", "properly a decoration but rather a separator of decoration in the toolbar \"\"\"", "self.xp_hTo and self.xp_wTo: x = self.xpathToInt(ndTo, self.xp_xTo, None) y = self.xpathToInt(ndTo, self.xp_yTo, None)", "__init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpCluster = cfg.get(sSurname, \"xpath\") self.xpContent", "self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) #draw a line obj =", "that let us find the rectangle line and fill colors self.xpLineWidth = cfg.get(sSurname,", "!= iLARGENEG and self._y1 != iLARGENEG and self._x2 != iLARGENEG and self._y2 !=", "def _getCoordList(self, node): sCoords = self.xpathToStr(node, self.xpCoords, \"\") if not sCoords: if node.get(\"id\")", "print node.serialize() # print self.xpX # for n in node.xpathEval(self.xpX): print n.serialize() lo", "self.xpX2, iLARGENEG) self._y2 = self.xpathToInt(node, self.xpY2, iLARGENEG) self._node = node if self._x1 !=", "put them in cache\"\"\" if self._node != node: self._x = self.xpathToInt(node, self.xpX, 1)", "s += \"\\n--- xpath=%s\" % xpExpr s += \"\\n--- Python Exception=%s\" % str(eExcpt)", "\"xpath_h\") self.xpInc = cfg.get(sSurname, \"xpath_incr\") #to increase the BB width and height self._node", "__init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize", "node.serialize() # print self.xpX # for n in node.xpathEval(self.xpX): print n.serialize() iLARGENEG =", "obj = wxh.AddScaledTextBox(txt, (x+x_inc, -y-y_inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return", "self.xpCtxt.setContextNode(node) return self.xpCtxt.xpathEval(xpExpr) except Exception, e: self.xpathError(node, xpExpr, e, \"xpathEval return None\") return", "beginPage(self, node): \"\"\"called before any sequnce of draw for a given page\"\"\" pass", "dc.SetFont(wx.Font(24, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") try: iFontSizeX = 24 *", "the order with lines \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname,", "\"|lambda \", \"Invalid lambda expression %s\"%xpExpr sStartEmpty, sLambdaExpr, xpExprArg, sEndEmpty = xpExpr.split('|') assert", "an attribute value return Deco.toInt(s) except Exception, e: if bShowError: self.xpathError(node, xpExpr, e,", "cfg, sSurname, xpCtxt) #now get the xpath expressions that let us find the", "sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') obj = wxh.AddScaledTextBox(txt, (x+x_inc, -y-y_inc), Size=iFontSize, Family=wx.ROMAN, Position='tl',", "len(self.lsLineColor) if False: Nf = DecoClusterCircle.count Nl = Nf else: Nf = random.randrange(iMaxFC)", "== sAttrValue: #very special case: when an attr was set, then saved, re-clicking", "cfg.get(sSurname, \"xpath_AttrValue\") self.dInitialValue = {} self.xpLineColorSlctd = cfg.get(sSurname, \"xpath_LineColor_Selected\") self.xpLineWidthSlctd = cfg.get(sSurname, \"xpath_LineWidth_Selected\")", "= sMsg def toInt(cls, s): try: return int(s) except ValueError: return int(round(float(s))) toInt", "\"\"\"The given XPath expression should return a string on the given node The", "or a one-node nodeset On error, return the default int value \"\"\" try:", "itself using the wx handle return a list of created WX objects\"\"\" lo", "FillStyle=sFillStyle) lo.append(obj) return lo class DecoTextBox(DecoRectangle): \"\"\"A text within a bounding box (a", "self.xpathToStr(node, self.xpEvalY2, '\"\"') self._y2 = self.xpathToInt(node, xpY2, iLARGENEG, False) #do not show any", "self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return", "number = None x,y,w,h = None, None, None, None bbHighlight = None sToId", "class DecoUnicodeChar(DecoText): \"\"\"A character encoded in Unicode We assume the unicode index is", "class DecoRectangle(DecoBBXYWH): \"\"\"A rectangle \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname,", "# LineWidth=iLineWidth, # LineColor=sLineColor, # FillColor=sFillColor, # FillStyle=sFillStyle) lo.append(obj) \"\"\" lo = DecoBBXYWH.draw(self,", "xpExpr, e, \"xpathToStr return %s as default value\"%sDefault) return sDefault def xpathEval(self, node,", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a config file sSurname", "<TextEquiv> <Unicode>Salgadinhos 12</Unicode> </TextEquiv> </TextLine> \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg,", "of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) #add the text itself", "= int(_dLabel[\"length\"]) x = x0 + Ex * iOffset y = -y0+iFontSize/6 obj", "= [] for _sPair in sCoords.split(' '): (sx, sy) = _sPair.split(',') ltXY.append((Deco.toInt(sx), Deco.toInt(sy)))", "\"xpath_FillStyle\") self.xpAttrToPageNumber = cfg.get(sSurname, \"xpath_ToPageNumber\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self)", "isActionable(self): return True def draw(self, wxh, node): \"\"\"draw itself using the wx handle", "iFontSizeY = 24 * abs(y2-y1) / Ey if sFit == \"x\": iFontSize =", "cfg.get(sSurname, \"xpath_wTo\") self.xp_hTo = cfg.get(sSurname, \"xpath_hTo\") self.xpAttrToId = cfg.get(sSurname, \"xpath_ToId\") self.config = cfg.jl_hack_cfg", "\"\"\"called before any sequnce of draw for a given page\"\"\" pass def draw(self,", "= self.xpathToInt(node, self.xpW, 1) self._h = self.xpathToInt(node, self.xpH, 1) self._inc = self.xpathToInt(node, self.xpInc,", "min(lY)) class DecoREADTextLine(DecoREAD): \"\"\"A TextLine as defined by the PageXml format of the", "cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrToPageNumber = cfg.get(sSurname, \"xpath_ToPageNumber\") def __str__(self): s = \"%s=\"%self.__class__ s +=", "\"%s\\t%s\"%(lXY (fA, (xg, yg))) return fA, (xg, yg) def draw(self, wxh, node): \"\"\"draw", "try: initialValue = self.dInitialValue[node] except KeyError: initialValue = node.prop(sAttrName) #first time self.dInitialValue[node] =", "a bounding box defined by X,Y for its top-left corner and width/height. xpX,", "= cfg.get(sSurname, \"xpath_y_incr\") #to shift the text def draw(self, wxh, node): lo =", "self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: try: img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) obj = wxh.AddScaledBitmap(img,", "got '%s'\"%sKeyVal) sKey = sKey.strip().lower() if bNoCase else sKey.strip() dicValForName[sKey] = sVal.strip() lName", "== sAttrValue: #back to previous value if initialValue == None or initialValue ==", "DecoText.__init__(self, cfg, sSurname, xpCtxt) self.base = int(cfg.get(sSurname, \"code_base\")) def getText(self, wxh, node): sEncodedText", "made on certain XML node using WX \"\"\" import types, os from collections", "return int(s) except ValueError: return int(round(float(s))) toInt = classmethod(toInt) def xpathToInt(self, node, xpExpr,", "= \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def beginPage(self, node): \"\"\"called before any", "\"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) for (x1, y1), (x2, y2) in zip(self._lxy,", "lo class DecoClusterCircle(DecoREAD): \"\"\" [Cluster] type=DecoClusterCircle xpath=.//Cluster xpath_content=@content xpath_radius=40 xpath_item_lxy=./pg:Coords/@points xpath_LineWidth=\"1\" xpath_FillStyle=\"Transparent\" LineColors=\"BLUE", "= wxh.AddCircle((x, -y), r, LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) # obj = wxh.AddRectangle((x, -y),", "of 24 and do proportional dc.SetFont(wx.Font(24, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\")", ", Position='bl' , Color=sFontColor , LineColor=sLineColor , BackgroundColor=sBackgroundColor) lo.append(obj) except KeyError: pass except", "itself x, y = self._lxy[0] x_inc = self.xpathToInt(node, self.xpX_Inc, 0, False) y_inc =", "- yprev*x fA += iTerm xSum += iTerm * (xprev+x) ySum += iTerm", "cfg is a configuration object sSurname is the surname of the decoration and", "sFilePath = sCandidate except ValueError: pass if not os.path.exists(sFilePath): #maybe the image is", "self.xpContent)[0] for sId in sIds.split(): l = self.xpathEval(ndPage, './/*[@id=\"%s\"]'%sId) ndItem = l[0] lxy", "image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: try:", "\"+(coords=%s)\" % (self.xpCoords) return s def draw(self, wxh, node): \"\"\"draw itself using the", "0: obj = wxh.AddScaledBitmap(img, (x,-y), h) else: obj = wxh.AddScaledBitmap(img, (x,-y), img.GetHeight()) lo.append(obj)", "s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return s def draw(self, wxh,", "[] #need to go thru each item ndPage = node.xpath(\"ancestor::*[local-name()='Page']\")[0] sIds = self.xpathEval(node,", ":= \"%s\"'%(sAttrName,sAttrValue) return s class DecoClickableRectangleJump(DecoBBXYWH): \"\"\"A rectangle clicking on it jump to", "# a main XPath that select nodes to be decorated in this way", "value if initialValue == None or initialValue == sAttrValue: #very special case: when", "self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y-h/2.0), Size=iFontSize, Family=wx.ROMAN, Position='cl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj)", "lo def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class DecoUnicodeChar(DecoText): \"\"\"A character", "getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class DecoUnicodeChar(DecoText): \"\"\"A character encoded in", "return self.xpathToStr(node, self.xpContent, \"\") class DecoUnicodeChar(DecoText): \"\"\"A character encoded in Unicode We assume", "text itself txt = self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') # Position", "cfg, sSurname, xpCtxt) self.xpCoords = cfg.get(sSurname, \"xpath_lxy\") def _getCoordList(self, node): sCoords = self.xpathToStr(node,", "self._lxy = self._getCoordList(node) self._node = node #lo = DecoClosedPolyLine.draw(self, wxh, node) #add the", "sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) DecoText .__init__(self, cfg, sSurname, xpCtxt) self.xpX_Inc =", "\"\") try: return eval('u\"\\\\u%04x\"' % int(sEncodedText, self.base)) except ValueError: logging.error(\"DecoUnicodeChar: ERROR: base=%d code=%s\"%(self.base,", "self._x2 != iLARGENEG and self._y2 != iLARGENEG: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth", "declaration of some namespace sEnabled = cfg.get(sSurname, \"enabled\").lower() self.bEnabled = sEnabled in ['1',", "number = max(0, self.xpathToInt(nd, sPageNumberAttr, 1, True) - 1) #maybe we can also", "objects\"\"\" lo = [] #add the text itself txt = self.getText(wxh, node) sFontColor", "__init__(self, cfg, sSurname, xpCtxt): DecoREADTextLine.__init__(self, cfg, sSurname, xpCtxt) self.xpLabel = cfg.get(sSurname, \"xpath_label\") self.xpLineColor", "None if bool(sFilePath): img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) try: if h > 0: obj", "x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"BLACK\") x, y = int(x +", "the associated x,y,w,h values from the selected nodes \"\"\" def __init__(self, cfg, sSurname,", "the text def draw(self, wxh, node): lo = Deco.draw(self, wxh, node) if self._node", "[_y for _x,_y in ltXY] return (min(lX), max(lY)), (max(lX), min(lY)) class DecoREADTextLine(DecoREAD): \"\"\"A", "def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\")", "= 0 # if sMsg != Deco._s_prev_warning and Deco._warning_count < 1000: if sMsg", "= DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth", "count = 0 def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpCluster", "value\"%iDefault) return iDefault def xpathToStr(self, node, xpExpr, sDefault, bShowError=True): \"\"\"The given XPath expression", "print node.serialize() # print self.xpX # for n in node.xpathEval(self.xpX): print n.serialize() iLARGENEG", "cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) DecoText .__init__(self, cfg, sSurname, xpCtxt) self.xpX_Inc", "name in the config file This section should contain the following items: x,", "Unicode We assume the unicode index is given in a certain base, e.g.", "xpExpr, e, \"xpathEval return None\") return None def beginPage(self, node): \"\"\"called before any", "cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrName = cfg.get(sSurname, \"xpath_AttrName\") self.xpAttrValue = cfg.get(sSurname,", "_ldLabel = dCustom[self.xpathToStr(node, self.xpLabel, \"\").lower()] for _dLabel in _ldLabel: try: iOffset = int(_dLabel[\"offset\"])", "#draw a line obj = wxh.AddLine( [(x1, -y1), (x2, -y2)] , LineWidth=iLineWidth ,", "if x==None or y==None or w==None or h==None: x,y,w,h = None, None, None,", "fill colors self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname,", "'x' character for this font size return iFontSize, ExtentX, ExtentY \"\"\" (x1, y1),", "that closes automatically the shape <NAME> - September 2016 \"\"\" def __init__(self, cfg,", "objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) #add the image itself x,y,w,h,inc = self.runXYWHI(node)", "PadSize=0, LineColor=None) lo.append(obj) return lo class DecoText(DecoBBXYWH): \"\"\"A text \"\"\" def __init__(self, cfg,", "obj = wxh.AddScaledText(txt, (x, -y+iFontSize/6), Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='tl' , Color=sFontColor) lo.append(obj)", "self.xpathToInt(node, self.xpY1, iLARGENEG) self._x2 = self.xpathToInt(node, self.xpX2, iLARGENEG) self._y2 = self.xpathToInt(node, self.xpY2, iLARGENEG)", "etree #import cStringIO import wx sEncoding = \"utf-8\" def setEncoding(s): global sEncoding sEncoding", "sNode = str(node) if len(sNode) > iMaxLen: sNode = sNode[:iMaxLen] + \"...\" s", "\"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth,", "Deco._prev_xpath_error_count = 0 iMaxLen = 200 # to truncate the node serialization s", "node.xpath(\"ancestor::*[local-name()='Page']\")[0] sIds = self.xpathEval(node, self.xpContent)[0] for sId in sIds.split(): l = self.xpathEval(ndPage, './/*[@id=\"%s\"]'%sId)", "1505,435\"/> <TextEquiv> <Unicode>Salgadinhos 12</Unicode> </TextEquiv> </TextLine> \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self,", "ltXY[0] (x, _y1), (_x2, y) = self._coordList_to_BB(ltXY) obj = wxh.AddScaledText(txt, (x, -y+iFontSize/6), Size=iFontSize", "(xg, yg) assert fA >0 and xg >0 and yg >0, \"%s\\t%s\"%(lXY (fA,", "show any error if self._x2 == iLARGENEG: self._x2 = self.xpathToInt(node, self.xpDfltX2, iLARGENEG) xpY2", "isEnabled(self): return self.bEnabled def setEnabled(self, b=True): self.bEnabled = b return b def isActionable(self):", "(x1, y1), (x2, y2) = self._coordList_to_BB(ltXY) sFit = self.xpathToStr(node, self.xpFit, 'xy', bShowError=False) try:", "try: return int(s) except ValueError: return int(round(float(s))) toInt = classmethod(toInt) def xpathToInt(self, node,", "width/height. xpX, xpY, xpW, xpH are scalar XPath expressions to get the associated", "sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self): s", "lName = sNames.split(',') for name in lName: name = name.strip().lower() if bNoCase else", "if ln: #find the page number ndTo = nd = ln[0] #while nd", "iLARGENEG and self._y1 != iLARGENEG and self._x2 != iLARGENEG and self._y2 != iLARGENEG:", "bbHighlight = None sToId = self.xpathToStr(node, self.xpAttrToId , None) if sToId: ln =", "for a given page\"\"\" pass def draw(self, wxh, node): \"\"\"draw the associated decorations,", "dicValForName = dict() lsKeyVal = sValues.split(';') #things like \"x:1\" for sKeyVal in lsKeyVal:", "node, xpExpr, sDefault, bShowError=True): \"\"\"The given XPath expression should return a string on", "expressions to get the associated x,y,w,h values from the selected nodes \"\"\" def", "self.xpFillColorSlctd, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyleSlctd, \"Solid\") else: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\")", "+= \"\\n--- xpath=%s\" % xpExpr s += \"\\n--- Python Exception=%s\" % str(eExcpt) if", "sNode = sNode[:iMaxLen] + \"...\" s += \"\\n--- XML node = %s\" %", "= None, None, None, None bbHighlight = None sToId = self.xpathToStr(node, self.xpAttrToId ,", "1) self._y = self.xpathToInt(node, self.xpY, 1) self._w = self.xpathToInt(node, self.xpW, 1) self._h =", "wxh.AddScaledTextBox(txt, (x, -y+inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class", "-h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) \"\"\" return lo class DecoLink(Deco): \"\"\"A link from", "\"\"\" compute the font size so as to fit the polygon and the", "x==None or y==None or w==None or h==None: x,y,w,h = None, None, None, None", "given node The XPath expression should return a scalar or a one-node nodeset", "self.xpathToStr(node, self.xpLineColor, \"#000000\") sBackgroundColor = self.xpathToStr(node, self.xpBackgroundColor, \"#000000\") # Position and computation of", "LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo = [obj] + lo return lo def act(self, obj,", "= xpExpr.split('|') assert sEndEmpty == \"\", \"Missing last '|'\" sArg = self.xpCtxt.xpathEval(xpExprArg)[0] sPythonExpr", "xpath==%s)\" % (self.sSurname, self.xpMain) def getDecoClass(cls, sClass): \"\"\"given a decoration type, return the", "self.warning(\"No coordinates: node id = %s\" % node.get(\"id\")) return [(0,0)] try: ltXY =", "x, y = ltXY[0] (x, _y1), (_x2, y) = self._coordList_to_BB(ltXY) obj = wxh.AddScaledText(txt,", "= cfg.get(sSurname, \"LineColors\").split() self.lsFillColor = cfg.get(sSurname, \"FillColors\").split() #cached values self._node = None self._laxyr", "'@%s := \"%s\"'%(sAttrName,initialValue) else: if not sAttrValue: del node.attrib[sAttrName] s = \"Removal of", "dc return iFontSize, Ex, Ey def draw(self, wxh, node): \"\"\"draw itself using the", "-y1), (x2, -y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoClosedPolyLine(DecoPolyLine): \"\"\"A", "self.xpFillColorSlctd = cfg.get(sSurname, \"xpath_FillColor_Selected\") self.xpFillStyleSlctd = cfg.get(sSurname, \"xpath_FillStyle_Selected\") def __str__(self): s = \"%s=\"%self.__class__", "cannot compute font size along X axis\") iFontSizeX = 8 iFontSizeY = 24", "lChunk = s.split('}') if lChunk: for chunk in lChunk: #things like \"a {x:1\"", "def xpathError(self, node, xpExpr, eExcpt, sMsg=\"\"): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_xpath_error except", "cfg, sSurname, xpCtxt) self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") def __str__(self):", "of created WX objects\"\"\" # print node.serialize() # print self.xpX # for n", "node): return self.xpathToStr(node, self.xpContent, \"\") class DecoUnicodeChar(DecoText): \"\"\"A character encoded in Unicode We", "\"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidthSlctd, 1) sFillColor = self.xpathToStr(node, self.xpFillColorSlctd, \"#000000\") sFillStyle =", "None bbHighlight = None sToId = self.xpathToStr(node, self.xpAttrToId , None) if sToId: ln", "def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpCoords = cfg.get(sSurname, \"xpath_lxy\")", "node): sCoords = self.xpathToStr(node, self.xpCoords, \"\") if not sCoords: if node.get(\"id\") is None:", "before any sequnce of draw for a given page\"\"\" self.bInit = False def", "0.0 xSum, ySum = 0, 0 xprev, yprev = lXY[-1] for x, y", "Deco: \"\"\"A general decoration class\"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is", "cfg, sSurname, xpCtxt): DecoText.__init__(self, cfg, sSurname, xpCtxt) self.base = int(cfg.get(sSurname, \"code_base\")) def getText(self,", "WX objects\"\"\" # print node.serialize() # print self.xpX # for n in node.xpathEval(self.xpX):", "self.xpFit = cfg.get(sSurname, \"xpath_fit_text_size\").lower() def __str__(self): s = \"%s=\"%self.__class__ return s def _getFontSize(self,", "getText(self, wxh, node): sEncodedText = self.xpathToStr(node, self.xpContent, \"\") try: return eval('u\"\\\\u%04x\"' % int(sEncodedText,", "\"xpath\") # a main XPath that select nodes to be decorated in this", "= sFilePath[:sFilePath.rindex(\"_\")] sCandidate = os.path.join(self.sImageFolder, sDir, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate except", "= nd.parent try: #number = max(0, int(nd.prop(\"number\")) - 1) number = max(0, self.xpathToInt(nd,", "itself x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: if self.sImageFolder:", "\"xpath_wTo\") self.xp_hTo = cfg.get(sSurname, \"xpath_hTo\") self.xpAttrToId = cfg.get(sSurname, \"xpath_ToId\") self.config = cfg.jl_hack_cfg #HACK", "= self.xpathToStr(node, self.xpAttrToId , None) if sToId: ln = self.xpathEval(node.doc.getroot(), '//*[@id=\"%s\"]'%sToId.strip()) if ln:", "BB width and height self._node = None def __str__(self): s = Deco.__str__(self) s", "!= sPageTag: nd = nd.parent try: #number = max(0, int(nd.prop(\"number\")) - 1) number", "1505,435\"/> \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpCoords =", "= self.xpathToInt(node, self.xpY1, iLARGENEG) self._x2 = self.xpathToInt(node, self.xpX2, iLARGENEG) self._y2 = self.xpathToInt(node, self.xpY2,", "* abs(y2-y1) / Ey if sFit == \"x\": iFontSize = iFontSizeX elif sFit", "xpCtxt) DecoText .__init__(self, cfg, sSurname, xpCtxt) self.xpX_Inc = cfg.get(sSurname, \"xpath_x_incr\") #to shift the", "def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def beginPage(self, node):", "s except Exception, e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToStr return %s as", "y==None or w==None or h==None: x,y,w,h = None, None, None, None except: pass", "let us find the rectangle line and fill colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\")", "the use wants to specify it via the menu sImageFolder = None def", "for its top-left corner and width/height. xpX, xpY, xpW, xpH are scalar XPath", "sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: try: img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) obj", "self._node = node return (self._x, self._y, self._w, self._h, self._inc) class DecoRectangle(DecoBBXYWH): \"\"\"A rectangle", "chunk: continue try: sNames, sValues = chunk.split('{') #things like: (\"a,b\", \"x:1 ; y:2\")", "def runXYWHI(self, node): \"\"\"get the X,Y values for a node and put them", "def _getFontSize(self, node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE): \"\"\" compute the font size so as", "cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__ s", "assert xpExpr[:8] == \"|lambda \", \"Invalid lambda expression %s\"%xpExpr sStartEmpty, sLambdaExpr, xpExprArg, sEndEmpty", "reflect a decoration to be made on certain XML node using WX \"\"\"", "maybe we have some pattern?? lCandidate = glob.glob(sFilePath) bKO = True for s", "self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) self._x2 = self.xpathToInt(node, self.xpX2, iLARGENEG) self._y2", "node): \"\"\" draw itself using the wx handle return a list of created", "def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def isActionable(self): return", "self.xpContent, \"\") try: return eval('u\"\\\\u%04x\"' % int(sEncodedText, self.base)) except ValueError: logging.error(\"DecoUnicodeChar: ERROR: base=%d", "lo.append(obj) \"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node,", "self.xpW, self.xpH) return s def runXYWHI(self, node): \"\"\"get the X,Y values for a", "self.xpathToStr(node, self.xpContent, \"\") class DecoUnicodeChar(DecoText): \"\"\"A character encoded in Unicode We assume the", "node): \"\"\"called before any sequnce of draw for a given page\"\"\" self.bInit =", "it jump to a node \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg,", "except Exception, e: self.warning(\"DecoImage ERROR: File %s: %s\"%(sFilePath, str(e))) return lo class DecoOrder(DecoBBXYWH):", "is undefined.\") fA = 0.0 xSum, ySum = 0, 0 xprev, yprev =", "(x,-y), h) else: obj = wxh.AddScaledBitmap(img, (x,-y), img.GetHeight()) lo.append(obj) except Exception, e: self.warning(\"DecoImage", "not overload the console. return Deco._s_prev_xpath_error = s Deco._prev_xpath_error_count += 1 if Deco._prev_xpath_error_count", "format of the READ project <TextLine id=\"line_1551946877389_284\" custom=\"readingOrder {index:0;} Item-name {offset:0; length:11;} Item-price", "base, e.g. 10 or 16 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoText.__init__(self, cfg,", "(self.xpX1, self.xpY1, self.xpEvalX2, self.xpEvalY2) return s def draw(self, wxh, node): \"\"\"draw itself using", "the wx handle return a list of created WX objects\"\"\" lo = DecoRectangle.draw(self,", "sCoords: if node.get(\"id\") is None: self.warning(\"No coordinates: node = %s\" % etree.tostring(node)) else:", "s = \"-\"*60 s += \"\\n--- XPath ERROR on class %s\"%self.__class__ s +=", "iTerm xSum += iTerm * (xprev+x) ySum += iTerm * (yprev+y) xprev, yprev", "self.xpathToInt(ndTo, self.xp_hTo, None) if x==None or y==None or w==None or h==None: x,y,w,h =", "= None def __str__(self): s = \"%s=\"%self.__class__ s += \"+(x1=%s y1=%s x2=%s y2=%s)\"", "the shape <NAME> - September 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self,", "width and height self._node = None def __str__(self): s = Deco.__str__(self) s +=", "node): \"\"\"draw the associated decorations, return the list of wx created objects\"\"\" return", "and the section name in the config file! xpCtxt is an XPath context", "Exception, e: self.xpathError(node, xpExpr, e, \"xpathEval return None\") return None def beginPage(self, node):", "expression %s\"%xpExpr sStartEmpty, sLambdaExpr, xpExprArg, sEndEmpty = xpExpr.split('|') assert sEndEmpty == \"\", \"Missing", "sEncodedText = self.xpathToStr(node, self.xpContent, \"\") try: return eval('u\"\\\\u%04x\"' % int(sEncodedText, self.base)) except ValueError:", "self.xpLineWidth, 1) obj = wxh.AddLine( [(self.prevX, -self.prevY), (x, -y)] , LineWidth=iLineWidth , LineColor=sLineColor)", "# s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) return self.xpCtxt.xpathEval(xpExpr) except Exception, e: self.xpathError(node, xpExpr, e,", "0 xprev, yprev = lXY[-1] for x, y in lXY: iTerm = xprev*y", "if self._lxy: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) for", "elif sFit == \"y\": iFontSize = iFontSizeY else: iFontSize = min(iFontSizeX, iFontSizeY) dc.SetFont(wx.Font(iFontSize,", "self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: if self.sImageFolder: sCandidate = os.path.join(self.sImageFolder,", "lo class DecoTextBox(DecoRectangle): \"\"\"A text within a bounding box (a rectangle) \"\"\" def", "\"xpath_FillStyle\") self.xp_xTo = cfg.get(sSurname, \"xpath_xTo\") self.xp_yTo = cfg.get(sSurname, \"xpath_yTo\") self.xp_wTo = cfg.get(sSurname, \"xpath_wTo\")", "a given page\"\"\" self.bInit = False def draw(self, wxh, node): \"\"\"draw itself using", "lo.append(obj) else: self.bInit = True iEllipseParam = min(w,h) / 2 wxh.AddEllipse((x, -y), (iEllipseParam,", "0) self._x,self._y = self._x-self._inc, self._y-self._inc self._w,self._h = self._w+2*self._inc, self._h+2*self._inc self._node = node return", "cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self._node = None def __str__(self): s =", "\"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xp_xTo = cfg.get(sSurname, \"xpath_xTo\")", "Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") del dc return iFontSize, Ex, Ey", "iMaxLen: sNode = sNode[:iMaxLen] + \"...\" s += \"\\n--- XML node = %s\"", "[Cluster] type=DecoClusterCircle xpath=.//Cluster xpath_content=@content xpath_radius=40 xpath_item_lxy=./pg:Coords/@points xpath_LineWidth=\"1\" xpath_FillStyle=\"Transparent\" LineColors=\"BLUE SIENNA YELLOW ORANGE RED", "Ey = dc.GetTextExtent(\"x\") del dc return iFontSize, Ex, Ey def draw(self, wxh, node):", "obj = wxh.AddScaledTextBox(txt, (x, -y-h/2.0), Size=iFontSize, Family=wx.ROMAN, Position='cl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return", "cfg.get(sSurname, \"xpath_x_incr\") #to shift the text self.xpY_Inc = cfg.get(sSurname, \"xpath_y_incr\") #to shift the", "y2=%s)\" % (self.xpX1, self.xpY1, self.xpX2, self.xpY2) return s def draw(self, wxh, node): \"\"\"draw", "node id = %s\" % node.get(\"id\")) return [(0,0)] try: ltXY = [] for", "h) else: obj = wxh.AddScaledBitmap(img, (x,-y), img.GetHeight()) lo.append(obj) except Exception, e: self.warning(\"DecoImage ERROR:", "the toolbar \"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a configuration", "= self.xpCtxt.xpathEval(xpExprArg)[0] sPythonExpr = \"(%s)(%s)\" % (sLambdaExpr, repr(sArg)) s = eval(sPythonExpr) else: s", "if os.path.exists(sCandidate): sFilePath = sCandidate else: # maybe the file is in a", "A, (Xg, Yg) which are the area and the coordinates (float) of the", "text \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpContent =", "self._lxy = self._getCoordList(node) self._node = node if self._lxy: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\")", "= cfg.get(sSurname, \"xpath_LineWidth\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s", "+ lo return lo def act(self, obj, node): \"\"\" Toggle the attribute value", "s.split('}') if lChunk: for chunk in lChunk: #things like \"a {x:1\" chunk =", "= \"do nothing\" sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue = self.xpathToStr(node, self.xpAttrValue,", "= sCandidate else: # maybe the file is in a subfolder ? #", "self._h+2*self._inc self._node = node return (self._x, self._y, self._w, self._h, self._inc) class DecoRectangle(DecoBBXYWH): \"\"\"A", "= ltXY[0] _ldLabel = dCustom[self.xpathToStr(node, self.xpLabel, \"\").lower()] for _dLabel in _ldLabel: try: iOffset", "created objects\"\"\" return [] class DecoBBXYWH(Deco): \"\"\"A decoration with a bounding box defined", "way to encode coordinates. like: <Coords points=\"985,390 1505,390 1505,440 985,440\"/> or <Baseline points=\"985,435", "\"xpath_fit_text_size\").lower() def __str__(self): s = \"%s=\"%self.__class__ return s def _getFontSize(self, node, ltXY, txt,", "text itself txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor", "lo = DecoREAD.draw(self, wxh, node) if self._node != node: self._lxy = self._getCoordList(node) self._node", "lo.append(obj) return lo class DecoClusterCircle(DecoREAD): \"\"\" [Cluster] type=DecoClusterCircle xpath=.//Cluster xpath_content=@content xpath_radius=40 xpath_item_lxy=./pg:Coords/@points xpath_LineWidth=\"1\"", "'.//*[@id=\"%s\"]'%sId) ndItem = l[0] lxy = self._getCoordList(ndItem) fA, (xg, yg) = self.getArea_and_CenterOfMass(lxy) r", "#the following expression must be evaluated twice self.xpEvalX2, self.xpEvalY2 = cfg.get(sSurname, \"eval_xpath_x2\"), cfg.get(sSurname,", "if node.prop(sAttrName) == sAttrValue: sLineColor = self.xpathToStr(node, self.xpLineColorSlctd, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidthSlctd,", "is in a folder with same name as XML file? (Transkribus style) sUrl", ", LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoClickableRectangleSetAttr(DecoBBXYWH): \"\"\"A rectangle clicking on", "class DecoREADTextLine(DecoREAD): \"\"\"A TextLine as defined by the PageXml format of the READ", "== iLARGENEG: self._y2 = self.xpathToInt(node, self.xpDfltY2, iLARGENEG) self._node = node if self._x1 !=", "self.lsLineColor: sLineColor = self.lsLineColor[Nl % iMaxLC] else: sLineColor = sFillColor obj = wxh.AddCircle((x,", "to x2,y2 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpX1,", "points=\"985,390 1505,390 1505,440 985,440\"/> or <Baseline points=\"985,435 1505,435\"/> \"\"\" def __init__(self, cfg, sSurname,", "DecoRectangle(DecoBBXYWH): \"\"\"A rectangle \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt)", "iTerm * (yprev+y) xprev, yprev = x, y if fA == 0.0: raise", "FillStyle=sFillStyle) \"\"\" return lo class DecoLink(Deco): \"\"\"A link from x1,y1 to x2,y2 \"\"\"", "font size along X axis\") iFontSizeX = 8 iFontSizeY = 24 * abs(y2-y1)", "self.xpathToInt(node, self.xpLineWidth, 1) sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") for (_a, x, y, r)", "= DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"BLACK\") x,", "self._w+2*self._inc, self._h+2*self._inc self._node = node return (self._x, self._y, self._w, self._h, self._inc) class DecoRectangle(DecoBBXYWH):", "def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class DecoUnicodeChar(DecoText): \"\"\"A character encoded", "Ey = self._getFontSize(node, ltXY, txt , Family=wx.FONTFAMILY_TELETYPE) dCustom = self.parseCustomAttr(node.get(\"custom\"), bNoCase=True) try: x0,", "class that reflect a decoration to be made on certain XML node using", "'yes', 'true'] def isSeparator(cls): return False isSeparator = classmethod(isSeparator) def __str__(self): return \"(Surname=%s", "(sLambdaExpr, repr(sArg)) s = eval(sPythonExpr) else: s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType:", "decoration and the section name in the config file! xpCtxt is an XPath", "(self.xpCoords) return s def draw(self, wxh, node): \"\"\"draw itself using the wx handle", "self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") def __str__(self): s = \"%s=\"%self.__class__", "__str__(self): return \"--------\" def isSeparator(self): return True def setXPathContext(self, xpCtxt): pass class Deco:", ", (x, y) , Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='bl' , Color=sFontColor , LineColor=sLineColor", "wxh.AddScaledBitmap(img, (x,-y), h) else: obj = wxh.AddScaledBitmap(img, (x,-y), img.GetHeight()) lo.append(obj) except Exception, e:", "#add the text itself txt = self.getText(wxh, node) iFontSize = self.xpathToInt(node, self.xpFontSize, 8)", "points=\"985,390 1505,390 1505,440 985,440\"/> <Baseline points=\"985,435 1505,435\"/> <TextEquiv> <Unicode>Salgadinhos 12</Unicode> </TextEquiv> </TextLine> \"\"\"", "DecoREADTextLine_custom_offset(DecoREADTextLine, READ_custom): \"\"\" Here we show the annotation by offset found in the", "iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) self._x2 = self.xpathToInt(node, self.xpX2, iLARGENEG) self._y2 =", "self.xpEvalY2, '\"\"') self._y2 = self.xpathToInt(node, xpY2, iLARGENEG, False) #do not show any error", "around it \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef", "xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\")", "\"\"\"given a decoration type, return the associated class\"\"\" c = globals()[sClass] if type(c)", "except AttributeError: s = s[0] return s except Exception, e: if bShowError: self.xpathError(node,", "self.xpY1, self.xpX2, self.xpY2) return s def draw(self, wxh, node): \"\"\"draw itself using the", "return int(round(float(s))) toInt = classmethod(toInt) def xpathToInt(self, node, xpExpr, iDefault=0, bShowError=True): \"\"\"The given", "cfg, sSurname, xpCtxt) DecoText .__init__(self, cfg, sSurname, xpCtxt) self.xpX_Inc = cfg.get(sSurname, \"xpath_x_incr\") #to", "iFontSizeX elif sFit == \"y\": iFontSize = iFontSizeY else: iFontSize = min(iFontSizeX, iFontSizeY)", "remove it. del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName, initialValue) s", "ln = self.xpathEval(node.doc.getroot(), '//*[@id=\"%s\"]'%sToId.strip()) if ln: #find the page number ndTo = nd", "!= Deco._s_prev_warning and Deco._warning_count < 1000: if sMsg != Deco._s_prev_warning: logging.warning(sMsg) Deco._warning_count +=", "None) w = self.xpathToInt(ndTo, self.xp_wTo, None) h = self.xpathToInt(ndTo, self.xp_hTo, None) if x==None", "dc = wx.ScreenDC() # compute for font size of 24 and do proportional", "XPath expression should return a scalar or a one-node nodeset On error, return", "= self.xpathToInt(node, self.xpY_Inc, 0, False) txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node,", "rectangle line and fill colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\")", "self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') obj", "LineWidth=iLineWidth, # LineColor=sLineColor, # FillColor=sFillColor, # FillStyle=sFillStyle) lo.append(obj) \"\"\" lo = DecoBBXYWH.draw(self, wxh,", "\"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) s = self.xpCtxt.xpathEval(xpExpr) if type(s) ==", "PadSize=0, LineColor=None) lo.append(obj) return lo def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\")", "bNoCase else sKey.strip() dicValForName[sKey] = sVal.strip() lName = sNames.split(',') for name in lName:", "the decoration surname and the section name in the config file This section", "to previous value if initialValue == None or initialValue == sAttrValue: #very special", "return \"(Surname=%s xpath==%s)\" % (self.sSurname, self.xpMain) def getDecoClass(cls, sClass): \"\"\"given a decoration type,", "self.xpFillStyleSlctd = cfg.get(sSurname, \"xpath_FillStyle_Selected\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return", "return False def setXPathContext(self, xpCtxt): self.xpCtxt = xpCtxt def xpathError(self, node, xpExpr, eExcpt,", "wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"BLACK\") x, y =", "else: sLineColor = sFillColor obj = wxh.AddCircle((x, -y), r, LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle)", "LineColor=sLineColor, LineWidth=5, FillStyle=\"Transparent\") self.prevX, self.prevY = x, y return lo class DecoLine(Deco): \"\"\"A", "= Deco.__str__(self) s += \"+(x=%s y=%s w=%s h=%s)\" % (self.xpX, self.xpY, self.xpW, self.xpH)", "not sCoords: if node.get(\"id\") is None: self.warning(\"No coordinates: node = %s\" % etree.tostring(node))", "lXY[-1] for x, y in lXY: iTerm = xprev*y - yprev*x fA +=", "= cfg.get(sSurname, \"eval_xpath_x2\"), cfg.get(sSurname, \"eval_xpath_y2\") self.xpDfltX2, self.xpDfltY2 = cfg.get(sSurname, \"xpath_x2_default\"), cfg.get(sSurname, \"xpath_y2_default\") #now", "xpExpr.split('|') assert sEndEmpty == \"\", \"Missing last '|'\" sArg = self.xpCtxt.xpathEval(xpExprArg)[0] sPythonExpr =", "wxh, node): \"\"\"draw the associated decorations, return the list of wx created objects\"\"\"", "node) #add the text itself txt = self.getText(wxh, node) iFontSize = self.xpathToInt(node, self.xpFontSize,", "<Unicode>Salgadinhos 12</Unicode> </TextEquiv> </TextLine> \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname,", "Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") #the following", "of config: [TextLine] type=DecoPolyLine xpath=.//TextLine/Coords xpath_lxy=@points xpath_LineColor=\"RED\" xpath_FillStyle=\"Solid\" <NAME> - March 2016 \"\"\"", "lo return lo def act(self, obj, node): \"\"\" return the page number of", "xpY2, iLARGENEG, False) #do not show any error if self._y2 == iLARGENEG: self._y2", "s = \"do nothing\" sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue = self.xpathToStr(node,", "values self._node = None self._laxyr = None print \"DecoClusterCircle lsLineColor = \", self.lsLineColor", "if not sCoords: if node.get(\"id\") is None: self.warning(\"No coordinates: node = %s\" %", "indicative of the presence/absence of the attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "\"DecoClusterCircle lsLineColor = \", self.lsLineColor print \"DecoClusterCircle lsFillColor = \", self.lsFillColor def __str__(self):", "iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') obj = wxh.AddScaledTextBox(txt,", "but rather a separator of decoration in the toolbar \"\"\" def __init__(self, cfg,", "#the dictionary for that name dicValForName = dict() lsKeyVal = sValues.split(';') #things like", "def __init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) def _getCoordList(self, node): lCoord", "not exists: '%s'\"%sFilePath) sFilePath = None if bool(sFilePath): img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) try:", "polygon and the extent of the 'x' character for this font size return", "on certain XML node using WX \"\"\" import types, os from collections import", "\"\"\"An image with a box around it \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "+ h/2.0) if self.bInit: #draw a line iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) obj", "default value\"%iDefault) return iDefault def xpathToStr(self, node, xpExpr, sDefault, bShowError=True): \"\"\"The given XPath", "cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def", "self._laxyr: iMaxFC = len(self.lsFillColor) iMaxLC = len(self.lsLineColor) if False: Nf = DecoClusterCircle.count Nl", "None, None except: pass return number,x,y,w,h class DecoClickableRectangleJumpToPage(DecoBBXYWH): \"\"\"A rectangle clicking on it", "x1,y1,x2,y2, ...,xn,yn or x1,y1 x2,y2 .... xn,yn Example of config: [TextLine] type=DecoPolyLine xpath=.//TextLine/Coords", "on error \"\"\" sPageTag = self.config.getPageTag() sPageNumberAttr = self.config.getPageNumberAttr() number = None x,y,w,h", "color is indicative of the presence/absence of the attribute \"\"\" def __init__(self, cfg,", "way self.xpCtxt = xpCtxt #this context may include the declaration of some namespace", "in Unicode We assume the unicode index is given in a certain base,", "annotation by offset found in the custom attribute \"\"\" def __init__(self, cfg, sSurname,", "= sFillColor obj = wxh.AddCircle((x, -y), r, LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) # obj", "* (yprev+y) xprev, yprev = x, y if fA == 0.0: raise ValueError(\"surface", "raise Exception(\"No such decoration type: '%s'\"%sClass) return c getDecoClass = classmethod(getDecoClass) def getSurname(self):", "\"xpath_y1\") #the following expression must be evaluated twice self.xpEvalX2, self.xpEvalY2 = cfg.get(sSurname, \"eval_xpath_x2\"),", "= self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE) # x, y", "from x1,y1 to x2,y2 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname,", "= cfg.get(sSurname, \"xpath_w\"), cfg.get(sSurname, \"xpath_h\") self.xpInc = cfg.get(sSurname, \"xpath_incr\") #to increase the BB", "= None def __str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return", "<Coords points=\"985,390 1505,390 1505,440 985,440\"/> or <Baseline points=\"985,435 1505,435\"/> \"\"\" def __init__(self, cfg,", "= self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y-h/2.0), Size=iFontSize,", "wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class READ_custom: \"\"\" Everything related to the", "class DecoClickableRectangleSetAttr(DecoBBXYWH): \"\"\"A rectangle clicking on it add/remove an attribute the rectangle color", "obj = wxh.AddCircle((x, -y), r, LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) # obj = wxh.AddRectangle((x,", "node.get(sAttrName) == sAttrValue: #back to previous value if initialValue == None or initialValue", "node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName, sAttrValue) s = '@%s :=", "iMaxLen = 200 # to truncate the node serialization s = \"-\"*60 s", "self.xpCoords, \"\") if not sCoords: if node.get(\"id\") is None: self.warning(\"No coordinates: node =", "DecoClosedPolyLine.draw(self, wxh, node) #add the text itself x, y = self._lxy[0] x_inc =", "#cached values self._node = None self._lxy = None def __str__(self): s = \"%s=\"%self.__class__", "the associated decorations, return the list of wx created objects\"\"\" return [] class", "self.xpRadius = cfg.get(sSurname, \"xpath_radius\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.lsLineColor", "= Deco.draw(self, wxh, node) if self._node != node: self._x1 = self.xpathToInt(node, self.xpX1, iLARGENEG)", "try: iFontSizeX = 24 * abs(x2-x1) / Ex / len(txt) except: self.warning(\"absence of", "'BLACK') # Position and computation of font size ltXY = self._getCoordList(node) iFontSize, Ex,", "Deco._warning_count += 1 Deco._s_prev_warning = sMsg def toInt(cls, s): try: return int(s) except", "\"\"\" count = 0 def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt)", "cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrName = cfg.get(sSurname,", "None on error \"\"\" sPageTag = self.config.getPageTag() sPageNumberAttr = self.config.getPageNumberAttr() number = None", "return False isSeparator = classmethod(isSeparator) def __str__(self): return \"(Surname=%s xpath==%s)\" % (self.sSurname, self.xpMain)", "Deco._s_prev_warning: logging.warning(sMsg) Deco._warning_count += 1 Deco._s_prev_warning = sMsg def toInt(cls, s): try: return", "wxh, node) x,y,w,h,inc = self.runXYWHI(node) sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue =", "READ_custom): \"\"\" Here we show the annotation by offset found in the custom", "text within a bounding box (a rectangle) \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "= int(cfg.get(sSurname, \"code_base\")) def getText(self, wxh, node): sEncodedText = self.xpathToStr(node, self.xpContent, \"\") try:", "lCandidate = glob.glob(sFilePath) bKO = True for s in lCandidate: if os.path.exists(s): sFilePath", "= self.xpathToInt(node, self.xpX_Inc, 0, False) y_inc = self.xpathToInt(node, self.xpY_Inc, 0, False) txt =", "cfg.get(sSurname, \"xpath_LineColor\") self.xpBackgroundColor = cfg.get(sSurname, \"xpath_background_color\") def draw(self, wxh, node): \"\"\" draw itself", "x1,y1 x2,y2 .... xn,yn Example of config: [TextLine] type=DecoPolyLine xpath=.//TextLine/Coords xpath_lxy=@points xpath_LineColor=\"RED\" xpath_FillStyle=\"Solid\"", "+ \"\\n\" logging.warning(s) def warning(self, sMsg): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_warning except", "0 # if sMsg != Deco._s_prev_warning and Deco._warning_count < 1000: if sMsg !=", "<TextLine id=\"line_1551946877389_284\" custom=\"readingOrder {index:0;} Item-name {offset:0; length:11;} Item-price {offset:12; length:2;}\"> <Coords points=\"985,390 1505,390", "id=\"line_1551946877389_284\" custom=\"readingOrder {index:0;} Item-name {offset:0; length:11;} Item-price {offset:12; length:2;}\"> <Coords points=\"985,390 1505,390 1505,440", ">0 and xg >0 and yg >0, \"%s\\t%s\"%(lXY (fA, (xg, yg))) return fA,", "self.xpathToStr(node, self.xpLineColorSlctd, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidthSlctd, 1) sFillColor = self.xpathToStr(node, self.xpFillColorSlctd, \"#000000\")", "cfg.get(sSurname, \"xpath\") # a main XPath that select nodes to be decorated in", "context \"\"\" self.sSurname = sSurname self.xpMain = cfg.get(sSurname, \"xpath\") # a main XPath", "xpath_lxy=@points xpath_LineColor=\"RED\" xpath_FillStyle=\"Solid\" <NAME> - March 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "= self.xpathToInt(ndItem, self.xpRadius, 1) self._laxyr.append( (fA, xg, yg, r) ) self._node = node", "attribute contains data in a CSS style syntax. We parse this syntax here", "= self.xpathToInt(node, self.xpY2, iLARGENEG) self._node = node if self._x1 != iLARGENEG and self._y1", "wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") try: iFontSizeX = 24 * abs(x2-x1) / Ex", "return a list of created WX objects\"\"\" lo = [] #add the image", "error \"\"\" index,x,y,w,h = None,None,None,None,None sToPageNum = self.xpathToStr(node, self.xpAttrToPageNumber , None) if sToPageNum:", "return number,x,y,w,h class DecoClickableRectangleJumpToPage(DecoBBXYWH): \"\"\"A rectangle clicking on it jump to a page", "abs(y2-y1) / Ey if sFit == \"x\": iFontSize = iFontSizeX elif sFit ==", "may include the declaration of some namespace sEnabled = cfg.get(sSurname, \"enabled\").lower() self.bEnabled =", "for a node and put them in cache\"\"\" if self._node != node: self._x", "wx handle return a list of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh,", "= [obj] + lo return lo def act(self, obj, node): \"\"\" Toggle the", "s[0].text except AttributeError: s = s[0] #should be an attribute value return Deco.toInt(s)", "the precise arrival point? if self.xp_xTo and self.xp_yTo and self.xp_hTo and self.xp_wTo: x", "self.xpFit, 'xy', bShowError=False) try: iFontSize = int(sFit) Ex, Ey = None, None except", "self.xpAttrToPageNumber = cfg.get(sSurname, \"xpath_ToPageNumber\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return", "-y), (iEllipseParam, -iEllipseParam), LineColor=sLineColor, LineWidth=5, FillStyle=\"Transparent\") self.prevX, self.prevY = x, y return lo", "\"Solid\") obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) \"\"\" return", "default int value \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) s = self.xpCtxt.xpathEval(xpExpr)", "lo.append(obj) return lo def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class READ_custom:", "= wxh.AddLine( [(x1, -y1), (x2, -y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo", "wxh.AddScaledBitmap(img, (x,-y), img.GetHeight()) lo.append(obj) except Exception, e: self.warning(\"DecoImage ERROR: File %s: %s\"%(sFilePath, str(e)))", "= dCustom[self.xpathToStr(node, self.xpLabel, \"\").lower()] for _dLabel in _ldLabel: try: iOffset = int(_dLabel[\"offset\"]) iLength", "self._laxyr.append( (fA, xg, yg, r) ) self._node = node if self._laxyr: iMaxFC =", "chunk.split('{') #things like: (\"a,b\", \"x:1 ; y:2\") except Exception: raise ValueError(\"Expected a '{'", "!= Deco._s_prev_warning: logging.warning(sMsg) Deco._warning_count += 1 Deco._s_prev_warning = sMsg def toInt(cls, s): try:", "cfg.get(sSurname, \"FillColors\").split() #cached values self._node = None self._laxyr = None print \"DecoClusterCircle lsLineColor", "return the page number of the destination or None on error \"\"\" index,x,y,w,h", "add/remove an attribute the rectangle color is indicative of the presence/absence of the", "AttributeError: Deco._s_prev_warning = \"\" Deco._warning_count = 0 # if sMsg != Deco._s_prev_warning and", "the extent of the 'x' character for this font size return iFontSize, ExtentX,", "y1), (x2, y2) = self._coordList_to_BB(ltXY) sFit = self.xpathToStr(node, self.xpFit, 'xy', bShowError=False) try: iFontSize", "_ldLabel: try: iOffset = int(_dLabel[\"offset\"]) iLength = int(_dLabel[\"length\"]) x = x0 + Ex", "DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpCluster = cfg.get(sSurname, \"xpath\") self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpRadius", "= wxh.AddScaledTextBox(txt, (x, -y-h/2.0), Size=iFontSize, Family=wx.ROMAN, Position='cl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo", "cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize =", "some pattern?? lCandidate = glob.glob(sFilePath) bKO = True for s in lCandidate: if", "return Deco._s_prev_xpath_error = s Deco._prev_xpath_error_count += 1 if Deco._prev_xpath_error_count > 10: return try:", "\"-\"*60 + \"\\n\" logging.warning(s) def warning(self, sMsg): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_warning", "cfg.get(sSurname, \"xpath_FillStyle\") self.xp_xTo = cfg.get(sSurname, \"xpath_xTo\") self.xp_yTo = cfg.get(sSurname, \"xpath_yTo\") self.xp_wTo = cfg.get(sSurname,", "self.xpX_Inc = cfg.get(sSurname, \"xpath_x_incr\") #to shift the text self.xpY_Inc = cfg.get(sSurname, \"xpath_y_incr\") #to", "else: s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try: s = s[0].text except", "def __str__(self): s = \"%s=\"%self.__class__ s += \"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1,", "nodeset On error, return the default int value \"\"\" try: # s =", "find x,y,w,h from a selected node self.xpX, self.xpY = cfg.get(sSurname, \"xpath_x\"), cfg.get(sSurname, \"xpath_y\")", "node, xpExpr, iDefault=0, bShowError=True): \"\"\"The given XPath expression should return an int on", "node self.xpX, self.xpY = cfg.get(sSurname, \"xpath_x\"), cfg.get(sSurname, \"xpath_y\") self.xpW, self.xpH = cfg.get(sSurname, \"xpath_w\"),", "None self._lxy = None def __str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" %", "assert fA >0 and xg >0 and yg >0, \"%s\\t%s\"%(lXY (fA, (xg, yg)))", "xpCtxt) self.base = int(cfg.get(sSurname, \"code_base\")) def getText(self, wxh, node): sEncodedText = self.xpathToStr(node, self.xpContent,", "Exception=%s\" % str(eExcpt) if sMsg: s += \"\\n--- Info: %s\" % sMsg if", "FillColor=sFillColor, FillStyle=sFillStyle) # obj = wxh.AddRectangle((x, -y), (20, 20), # LineWidth=iLineWidth, # LineColor=sLineColor,", "lo.append(obj) except Exception, e: self.warning(\"DecoImage ERROR: File %s: %s\"%(sFilePath, str(e))) return lo class", "return iFontSize, Ex, Ey def draw(self, wxh, node): \"\"\"draw itself using the wx", ", None) sAttrValue = self.xpathToStr(node, self.xpAttrValue, None) if sAttrName and sAttrValue != None:", "Deco._prev_xpath_error_count > 10: return try: sNode = etree.tostring(node) except: sNode = str(node) if", "ValueError: logging.error(\"DecoUnicodeChar: ERROR: base=%d code=%s\"%(self.base, sEncodedText)) return \"\" class DecoImageBox(DecoRectangle): \"\"\"An image with", "and sAttrValue != None: try: initialValue = self.dInitialValue[node] except KeyError: initialValue = node.prop(sAttrName)", "of the READ project <TextLine id=\"line_1551946877389_284\" custom=\"readingOrder {index:0;} Item-name {offset:0; length:11;} Item-price {offset:12;", "colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") #cached values self._node =", "length:2;}\"> <Coords points=\"985,390 1505,390 1505,440 985,440\"/> <Baseline points=\"985,435 1505,435\"/> <TextEquiv> <Unicode>Salgadinhos 12</Unicode> </TextEquiv>", "xg >0 and yg >0, \"%s\\t%s\"%(lXY (fA, (xg, yg))) return fA, (xg, yg)", "handle return a list of created WX objects\"\"\" DecoClusterCircle.count = DecoClusterCircle.count + 1", "Ex * iOffset y = -y0+iFontSize/6 obj = wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength] , (x, y) ,", "Deco._s_prev_xpath_error except AttributeError: Deco._s_prev_xpath_error = \"\" Deco._prev_xpath_error_count = 0 iMaxLen = 200 #", "LineColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" FillColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" enabled=1", "1505,440 985,440\"/> <Baseline points=\"985,435 1505,435\"/> <TextEquiv> <Unicode>Salgadinhos 12</Unicode> </TextEquiv> </TextLine> \"\"\" def __init__(self,", "l[0] lxy = self._getCoordList(ndItem) fA, (xg, yg) = self.getArea_and_CenterOfMass(lxy) r = self.xpathToInt(ndItem, self.xpRadius,", "cfg.get(sSurname, \"xpath_incr\") #to increase the BB width and height self._node = None def", "len(self.lsFillColor) iMaxLC = len(self.lsLineColor) if False: Nf = DecoClusterCircle.count Nl = Nf else:", "\"\"\"A decoration with a bounding box defined by X,Y for its top-left corner", "try: s = s[0].text except AttributeError: s = s[0] #should be an attribute", "= sKey.strip().lower() if bNoCase else sKey.strip() dicValForName[sKey] = sVal.strip() lName = sNames.split(',') for", "cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xp_xTo = cfg.get(sSurname,", "print self.xpX # for n in node.xpathEval(self.xpX): print n.serialize() iLARGENEG = -9999 lo", "Deco.draw(self, wxh, node) if self._node != node: self._lxy = self._getCoordList(node) self._node = node", "Ey if sFit == \"x\": iFontSize = iFontSizeX elif sFit == \"y\": iFontSize", "or w==None or h==None: x,y,w,h = None, None, None, None except: pass return", "for s in lCandidate: if os.path.exists(s): sFilePath = s bKO = False break", "self.xpathError(node, xpExpr, e, \"xpathToInt return %d as default value\"%iDefault) return iDefault def xpathToStr(self,", "= min(w,h) / 2 wxh.AddEllipse((x, -y), (iEllipseParam, -iEllipseParam), LineColor=sLineColor, LineWidth=5, FillStyle=\"Transparent\") self.prevX, self.prevY", "LineColor=sLineColor) lo.append(obj) else: self.bInit = True iEllipseParam = min(w,h) / 2 wxh.AddEllipse((x, -y),", "s += DecoRectangle.__str__(self) return s def draw(self, wxh, node): \"\"\"draw itself using the", "self._node != node: self._x1 = self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG)", "</TextLine> \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpContent =", "__init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a configuration object sSurname is the", "txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node,", "s Deco._prev_xpath_error_count += 1 if Deco._prev_xpath_error_count > 10: return try: sNode = etree.tostring(node)", "iDefault=0, bShowError=True): \"\"\"The given XPath expression should return an int on the given", "wxh.AddScaledBitmap(img, (x,-y), h) lo.append(obj) except Exception, e: self.warning(\"DecoImageBox ERROR: File %s: %s\"%(sFilePath, str(e)))", "!= iLARGENEG and self._x2 != iLARGENEG and self._y2 != iLARGENEG: sLineColor = self.xpathToStr(node,", "cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrToPageNumber = cfg.get(sSurname, \"xpath_ToPageNumber\") def __str__(self): s", "attribute the rectangle color is indicative of the presence/absence of the attribute \"\"\"", "-y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo = [obj] + lo return", "else: node.set(sAttrName, sAttrValue) s = '@%s := \"%s\"'%(sAttrName,sAttrValue) return s class DecoClickableRectangleJump(DecoBBXYWH): \"\"\"A", "s == Deco._s_prev_xpath_error: # let's not overload the console. return Deco._s_prev_xpath_error = s", "= cfg.get(sSurname, \"xpath_content\") self.xpRadius = cfg.get(sSurname, \"xpath_radius\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillStyle =", "DecoBBXYWH.__str__(self) return s def isActionable(self): return True def draw(self, wxh, node): \"\"\"draw itself", "return A, (Xg, Yg) which are the area and the coordinates (float) of", "xSum/6/fA, ySum/6/fA if fA <0: return -fA, (xg, yg) else: return fA, (xg,", "(x, -y-h/2.0), Size=iFontSize, Family=wx.ROMAN, Position='cl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo def getText(self,", "Position='tl' , Color=sFontColor) lo.append(obj) return lo def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent,", "xpW, xpH are scalar XPath expressions to get the associated x,y,w,h values from", "sFilePath = s bKO = False break if bKO: self.warning(\"WARNING: deco Image: file", "Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class DecoClusterCircle(DecoREAD): \"\"\" [Cluster]", "\"\").lower()] for _dLabel in _ldLabel: try: iOffset = int(_dLabel[\"offset\"]) iLength = int(_dLabel[\"length\"]) x", "(self._x2, -self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoREAD(Deco): \"\"\" READ", "size ltXY = self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt , Family=wx.FONTFAMILY_TELETYPE)", "else name.strip() dic[name].append(dicValForName) return dic class DecoREADTextLine_custom_offset(DecoREADTextLine, READ_custom): \"\"\" Here we show the", "self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.lsLineColor = cfg.get(sSurname, \"LineColors\").split() self.lsFillColor", "x, y in lXY: iTerm = xprev*y - yprev*x fA += iTerm xSum", "self.xp_xTo = cfg.get(sSurname, \"xpath_xTo\") self.xp_yTo = cfg.get(sSurname, \"xpath_yTo\") self.xp_wTo = cfg.get(sSurname, \"xpath_wTo\") self.xp_hTo", "class DecoImageBox(DecoRectangle): \"\"\"An image with a box around it \"\"\" def __init__(self, cfg,", "pattern?? lCandidate = glob.glob(sFilePath) bKO = True for s in lCandidate: if os.path.exists(s):", "/ Ey if sFit == \"x\": iFontSize = iFontSizeX elif sFit == \"y\":", "return lo class DecoText(DecoBBXYWH): \"\"\"A text \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self,", "class DecoTextPolyLine(DecoPolyLine, DecoText): \"\"\"A polyline that closes automatically the shape <NAME> - September", "sValues.split(';') #things like \"x:1\" for sKeyVal in lsKeyVal: if not sKeyVal.strip(): continue #empty", "maybe the file is in a subfolder ? # e.g. \"S_Aicha_an_der_Donau_004-03_0005.jpg\" is in", "else: return fA, (xg, yg) assert fA >0 and xg >0 and yg", "ln: #find the page number ndTo = nd = ln[0] #while nd and", "error \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) return self.xpCtxt.xpathEval(xpExpr) except Exception, e:", "txt = self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') # Position and computation", "overload the console. return Deco._s_prev_xpath_error = s Deco._prev_xpath_error_count += 1 if Deco._prev_xpath_error_count >", "\"\"\" (x1, y1), (x2, y2) = self._coordList_to_BB(ltXY) sFit = self.xpathToStr(node, self.xpFit, 'xy', bShowError=False)", "re-clicking on it wil remove it. del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName", "= cfg.get(sSurname, \"xpath_xTo\") self.xp_yTo = cfg.get(sSurname, \"xpath_yTo\") self.xp_wTo = cfg.get(sSurname, \"xpath_wTo\") self.xp_hTo =", "= node if self._x1 != iLARGENEG and self._y1 != iLARGENEG and self._x2 !=", "x,y,w,h = None, None, None, None except: pass return number,x,y,w,h class DecoClickableRectangleJumpToPage(DecoBBXYWH): \"\"\"A", "sFillColor obj = wxh.AddCircle((x, -y), r, LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) # obj =", "s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return s def draw(self, wxh, node): \"\"\"draw", "name dicValForName = dict() lsKeyVal = sValues.split(';') #things like \"x:1\" for sKeyVal in", "self.xpInc, 0) self._x,self._y = self._x-self._inc, self._y-self._inc self._w,self._h = self._w+2*self._inc, self._h+2*self._inc self._node = node", "raise ValueError(\"Only one point: polygon area is undefined.\") fA = 0.0 xSum, ySum", "sPythonExpr = \"(%s)(%s)\" % (sLambdaExpr, repr(sArg)) s = eval(sPythonExpr) else: s = self.xpCtxt.xpathEval(xpExpr)", "the BB width and height self._node = None def __str__(self): s = Deco.__str__(self)", "cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize =", "__init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize", "sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) for (x1, y1),", "\"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpEvalX2, self.xpEvalY2) return s def draw(self,", "!= iLARGENEG: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) #draw", "if fA <0: return -fA, (xg, yg) else: return fA, (xg, yg) assert", "\"\") if not sCoords: if node.get(\"id\") is None: self.warning(\"No coordinates: node = %s\"", "= sSurname self.xpMain = cfg.get(sSurname, \"xpath\") # a main XPath that select nodes", "if sAttrName and sAttrValue != None: try: initialValue = self.dInitialValue[node] except KeyError: initialValue", "name.strip() dic[name].append(dicValForName) return dic class DecoREADTextLine_custom_offset(DecoREADTextLine, READ_custom): \"\"\" Here we show the annotation", "exists: '%s'\"%sFilePath) sFilePath = None if bool(sFilePath): img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) try: if", "24 and do proportional dc.SetFont(wx.Font(24, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") try:", "sFillColor = self.lsFillColor[Nf % iMaxFC] if self.lsLineColor: sLineColor = self.lsLineColor[Nl % iMaxLC] else:", "iMaxFC] if self.lsLineColor: sLineColor = self.lsLineColor[Nl % iMaxLC] else: sLineColor = sFillColor obj", "\"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") #the following expression must be evaluated twice self.xpEvalX2, self.xpEvalY2 =", "\"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self)", "-y+inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class DecoText(DecoBBXYWH): \"\"\"A", "\"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return s def draw(self, wxh, node): \"\"\"draw", "x0 + Ex * iOffset y = -y0+iFontSize/6 obj = wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength] , (x,", "lo return lo def act(self, obj, node): \"\"\" Toggle the attribute value \"\"\"", "initialValue) s = '@%s := \"%s\"'%(sAttrName,initialValue) else: if not sAttrValue: del node.attrib[sAttrName] s", "Deco.__str__(self) s += \"+(x=%s y=%s w=%s h=%s)\" % (self.xpX, self.xpY, self.xpW, self.xpH) return", "self.xpathToStr(node, self.xpAttrValue, None) if sAttrName and sAttrValue != None: if node.prop(sAttrName) == sAttrValue:", "= globals()[sClass] if type(c) != types.ClassType: raise Exception(\"No such decoration type: '%s'\"%sClass) return", "Ey = None, None except ValueError: dc = wx.ScreenDC() # compute for font", "and nd.name != \"PAGE\": nd = nd.parent while nd and nd.name != sPageTag:", "node and put them in cache\"\"\" if self._node != node: self._x = self.xpathToInt(node,", "sToId = self.xpathToStr(node, self.xpAttrToId , None) if sToId: ln = self.xpathEval(node.doc.getroot(), '//*[@id=\"%s\"]'%sToId.strip()) if", "\"Missing last '|'\" sArg = self.xpCtxt.xpathEval(xpExprArg)[0] sPythonExpr = \"(%s)(%s)\" % (sLambdaExpr, repr(sArg)) s", "= sValues.split(';') #things like \"x:1\" for sKeyVal in lsKeyVal: if not sKeyVal.strip(): continue", "is in folder \"S_Aicha_an_der_Donau_004-03\" try: sDir = sFilePath[:sFilePath.rindex(\"_\")] sCandidate = os.path.join(self.sImageFolder, sDir, sFilePath)", "__str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def isActionable(self): return True", "(xg, yg) def draw(self, wxh, node): \"\"\"draw itself using the wx handle return", "\"%s=\"%self.__class__ s += \"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpEvalX2, self.xpEvalY2) return", "DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"BLACK\") x, y", "self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xp_xTo = cfg.get(sSurname, \"xpath_xTo\") self.xp_yTo", "\"DecoClusterCircle lsFillColor = \", self.lsFillColor def __str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\"", "break if not os.path.exists(sFilePath): # maybe we have some pattern?? lCandidate = glob.glob(sFilePath)", "= xprev*y - yprev*x fA += iTerm xSum += iTerm * (xprev+x) ySum", "self.xpAttrToId = cfg.get(sSurname, \"xpath_ToId\") self.config = cfg.jl_hack_cfg #HACK def __str__(self): s = \"%s=\"%self.__class__", "\"xpath_font_size\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self)", "wx handle return a list of created WX objects \"\"\" lo = []", "(x2, y2) \"\"\" lX = [_x for _x,_y in ltXY] lY = [_y", "the rectangle line and fill colors self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname,", "s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try: s", "x,y,w,h,inc = self.runXYWHI(node) sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue = self.xpathToStr(node, self.xpAttrValue,", "does not exists: '%s'\"%sFilePath) sFilePath = None if bool(sFilePath): img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY)", "node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"BLACK\") x, y = int(x", "sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions that let", "a box around it \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname,", "Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpCoords = cfg.get(sSurname, \"xpath_lxy\") def _getCoordList(self, node): sCoords =", "(\"a,b\", \"x:1 ; y:2\") except Exception: raise ValueError(\"Expected a '{' in '%s'\"%chunk) #the", "in _ldLabel: try: iOffset = int(_dLabel[\"offset\"]) iLength = int(_dLabel[\"length\"]) x = x0 +", "iLARGENEG) xpY2 = self.xpathToStr(node, self.xpEvalY2, '\"\"') self._y2 = self.xpathToInt(node, xpY2, iLARGENEG, False) #do", "we can also indicate the precise arrival point? if self.xp_xTo and self.xp_yTo and", "cfg.get(sSurname, \"xpath_y1\") self.xpX2, self.xpY2 = cfg.get(sSurname, \"xpath_x2\"), cfg.get(sSurname, \"xpath_y2\") #now get the xpath", "values self._node = None self._lxy = None def __str__(self): s = \"%s=\"%self.__class__ s", "s = s[0] return s except Exception, e: if bShowError: self.xpathError(node, xpExpr, e,", "\"\\n--- XPath ERROR on class %s\"%self.__class__ s += \"\\n--- xpath=%s\" % xpExpr s", "-y0+iFontSize/6 obj = wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength] , (x, y) , Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='bl'", "(float) of the center of mass of the polygon \"\"\" if len(lXY) <", "ltXY, txt , Family=wx.FONTFAMILY_TELETYPE) dCustom = self.parseCustomAttr(node.get(\"custom\"), bNoCase=True) try: x0, y0 = ltXY[0]", "warning(self, sMsg): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_warning except AttributeError: Deco._s_prev_warning = \"\"", "cfg.get(sSurname, \"xpath_radius\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.lsLineColor = cfg.get(sSurname,", "LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo = [obj] + lo return lo def act(self,", "return None on error \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) return self.xpCtxt.xpathEval(xpExpr)", "\"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self)", "None on error \"\"\" index,x,y,w,h = None,None,None,None,None sToPageNum = self.xpathToStr(node, self.xpAttrToPageNumber , None)", "xpCtxt def xpathError(self, node, xpExpr, eExcpt, sMsg=\"\"): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_xpath_error", "for _x,_y in ltXY] lY = [_y for _x,_y in ltXY] return (min(lX),", "section name in the config file This section should contain the following items:", "obj = wxh.AddScaledBitmap(img, (x,-y), img.GetHeight()) lo.append(obj) except Exception, e: self.warning(\"DecoImage ERROR: File %s:", "985,440\"/> <Baseline points=\"985,435 1505,435\"/> <TextEquiv> <Unicode>Salgadinhos 12</Unicode> </TextEquiv> </TextLine> \"\"\" def __init__(self, cfg,", "nothing\" sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue = self.xpathToStr(node, self.xpAttrValue, None) if", "text itself txt = self.getText(wxh, node) iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor =", "(x+x_inc, -y-y_inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class DecoClusterCircle(DecoREAD):", "node, xpExpr): \"\"\" evaluate the xpath expression return None on error \"\"\" try:", "wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo = [obj] + lo", "Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class DecoClusterCircle(DecoREAD): \"\"\" [Cluster] type=DecoClusterCircle", "= \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def draw(self, wxh, node): \"\"\"draw itself", "self._laxyr = None print \"DecoClusterCircle lsLineColor = \", self.lsLineColor print \"DecoClusterCircle lsFillColor =", "int(_dLabel[\"offset\"]) iLength = int(_dLabel[\"length\"]) x = x0 + Ex * iOffset y =", "sFilePath: if self.sImageFolder: sCandidate = os.path.join(self.sImageFolder, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate else:", "September 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) DecoText", "the associated class\"\"\" c = globals()[sClass] if type(c) != types.ClassType: raise Exception(\"No such", "parseCustomAttr( \"readingOrder {index:4;} structure {type:catch-word;}\" ) --> { 'readingOrder': [{ 'index':'4' }], 'structure':[{'type':'catch-word'}]", "Ey def draw(self, wxh, node): \"\"\"draw itself using the wx handle return a", "return \"--------\" def isSeparator(self): return True def setXPathContext(self, xpCtxt): pass class Deco: \"\"\"A", "= 0 iMaxLen = 200 # to truncate the node serialization s =", "% sNode s += \"\\n\" + \"-\"*60 + \"\\n\" logging.warning(s) def warning(self, sMsg):", "= DecoClosedPolyLine.draw(self, wxh, node) #add the text itself x, y = self._lxy[0] x_inc", "dic[name].append(dicValForName) return dic class DecoREADTextLine_custom_offset(DecoREADTextLine, READ_custom): \"\"\" Here we show the annotation by", "it add/remove an attribute the rectangle color is indicative of the presence/absence of", "page number of the destination or None on error \"\"\" sPageTag = self.config.getPageTag()", "get the associated x,y,w,h values from the selected nodes \"\"\" def __init__(self, cfg,", "% int(sEncodedText, self.base)) except ValueError: logging.error(\"DecoUnicodeChar: ERROR: base=%d code=%s\"%(self.base, sEncodedText)) return \"\" class", "assert sEndEmpty == \"\", \"Missing last '|'\" sArg = self.xpCtxt.xpathEval(xpExprArg)[0] sPythonExpr = \"(%s)(%s)\"", "value \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) s = self.xpCtxt.xpathEval(xpExpr) if type(s)", "= x, y return lo class DecoLine(Deco): \"\"\"A line from x1,y1 to x2,y2", "self.lsLineColor[Nl % iMaxLC] else: sLineColor = sFillColor obj = wxh.AddCircle((x, -y), r, LineWidth=iLineWidth,", "globals()[sClass] if type(c) != types.ClassType: raise Exception(\"No such decoration type: '%s'\"%sClass) return c", "DecoBBXYWH(Deco): \"\"\"A decoration with a bounding box defined by X,Y for its top-left", "class Deco: \"\"\"A general decoration class\"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg", "self.bEnabled = sEnabled in ['1', 'yes', 'true'] def isSeparator(cls): return False isSeparator =", "offset found in the custom attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREADTextLine.__init__(self,", "sKeyVal in lsKeyVal: if not sKeyVal.strip(): continue #empty try: sKey, sVal = sKeyVal.split(':')", "\"\\n--- xpath=%s\" % xpExpr s += \"\\n--- Python Exception=%s\" % str(eExcpt) if sMsg:", "WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) #add the image itself x,y,w,h,inc =", "#things like \"x:1\" for sKeyVal in lsKeyVal: if not sKeyVal.strip(): continue #empty try:", "sPageNumberAttr = self.config.getPageNumberAttr() number = None x,y,w,h = None, None, None, None bbHighlight", "sCoords)) raise e return ltXY def _coordList_to_BB(self, ltXY): \"\"\" return (x1, y1), (x2,", "wxh.AddLine( [(x1, -y1), (x2, -y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class", "list of created WX objects\"\"\" DecoClusterCircle.count = DecoClusterCircle.count + 1 lo = DecoREAD.draw(self,", "__str__(self): return \"(Surname=%s xpath==%s)\" % (self.sSurname, self.xpMain) def getDecoClass(cls, sClass): \"\"\"given a decoration", "self.xpMain def isEnabled(self): return self.bEnabled def setEnabled(self, b=True): self.bEnabled = b return b", "def xpathToInt(self, node, xpExpr, iDefault=0, bShowError=True): \"\"\"The given XPath expression should return an", "xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") self.xpX2, self.xpY2 = cfg.get(sSurname, \"xpath_x2\"),", "lo def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class READ_custom: \"\"\" Everything", "= DecoREAD.draw(self, wxh, node) if self._node != node: self._laxyr = [] #need to", "#maybe we can also indicate the precise arrival point? if self.xp_xTo and self.xp_yTo", "nodes to be decorated in this way self.xpCtxt = xpCtxt #this context may", "b return b def isActionable(self): return False def setXPathContext(self, xpCtxt): self.xpCtxt = xpCtxt", "any sequnce of draw for a given page\"\"\" pass def endPage(self, node): \"\"\"called", "DecoClickableRectangleJump(DecoBBXYWH): \"\"\"A rectangle clicking on it jump to a node \"\"\" def __init__(self,", "not os.path.exists(sFilePath): #maybe the image is in a folder with same name as", "\"\"\"draw the associated decorations, return the list of wx created objects\"\"\" return []", "\"xpath_hTo\") self.xpAttrToId = cfg.get(sSurname, \"xpath_ToId\") self.config = cfg.jl_hack_cfg #HACK def __str__(self): s =", "and fill colors self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor =", "certain base, e.g. 10 or 16 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoText.__init__(self,", "0, False) txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) def _getCoordList(self, node):", "XPath that select nodes to be decorated in this way self.xpCtxt = xpCtxt", "for sPrefix in [\"file://\", \"file:/\"]: if sUrl[0:len(sPrefix)] == sPrefix: sLocalDir = os.path.dirname(sUrl[len(sPrefix):]) sDir,_", "raise e return ltXY def _coordList_to_BB(self, ltXY): \"\"\" return (x1, y1), (x2, y2)", "to a page \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt)", "cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") def __str__(self): s = \"%s=\"%self.__class__ s +=", "node if self._x1 != iLARGENEG and self._y1 != iLARGENEG and self._x2 != iLARGENEG", "False: Nf = DecoClusterCircle.count Nl = Nf else: Nf = random.randrange(iMaxFC) Nl =", "img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) try: if h > 0: obj = wxh.AddScaledBitmap(img, (x,-y),", "-9999 lo = Deco.draw(self, wxh, node) if self._node != node: self._x1 = self.xpathToInt(node,", "s bKO = False break if bKO: self.warning(\"WARNING: deco Image: file does not", "wxh.AddLine( [(self._x1, -self._y1), (self._x2, -self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class", "s += \"+(coords=%s)\" % (self.xpCoords) return s def draw(self, wxh, node): \"\"\"draw itself", "'\"\"') self._y2 = self.xpathToInt(node, xpY2, iLARGENEG, False) #do not show any error if", "if bKO: self.warning(\"WARNING: deco Image: file does not exists: '%s'\"%sFilePath) sFilePath = None", "_y1), (_x2, y) = self._coordList_to_BB(ltXY) obj = wxh.AddScaledText(txt, (x, -y+iFontSize/6), Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE", "\"\"\"A polyline that closes automatically the shape <NAME> - September 2016 \"\"\" def", "that let us find the rectangle line and fill colors self.xpLineColor = cfg.get(sSurname,", "= self.xpathToInt(ndTo, self.xp_yTo, None) w = self.xpathToInt(ndTo, self.xp_wTo, None) h = self.xpathToInt(ndTo, self.xp_hTo,", "x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1)", "int value \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) if xpExpr[0] == \"|\":", "= \"%s=\"%self.__class__ s += \"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpEvalX2, self.xpEvalY2)", "iFontSize, ExtentX, ExtentY \"\"\" (x1, y1), (x2, y2) = self._coordList_to_BB(ltXY) sFit = self.xpathToStr(node,", "the page number of the destination or None on error \"\"\" sPageTag =", "in the config file! xpCtxt is an XPath context \"\"\" self.sSurname = sSurname", "if not os.path.exists(sFilePath): # maybe we have some pattern?? lCandidate = glob.glob(sFilePath) bKO", "xpath expressions that let us find the rectangle line and fill colors self.xpLineColor", "\"\\n\" + \"-\"*60 + \"\\n\" logging.warning(s) def warning(self, sMsg): \"\"\"report an xpath error\"\"\"", "self.xpathToInt(node, self.xpX, 1) self._y = self.xpathToInt(node, self.xpY, 1) self._w = self.xpathToInt(node, self.xpW, 1)", "\"xpath_LineColor\") #cached values self._node = None self._lxy = None def __str__(self): s =", "bounding box (a rectangle) \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname,", "= self.xpathToInt(node, self.xpX2, iLARGENEG) self._y2 = self.xpathToInt(node, self.xpY2, iLARGENEG) self._node = node if", "\"\"\"A line from x1,y1 to x2,y2 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self,", "types.ClassType: raise Exception(\"No such decoration type: '%s'\"%sClass) return c getDecoClass = classmethod(getDecoClass) def", "if lCoord: lCoord.append(lCoord[0]) return lCoord class DecoTextPolyLine(DecoPolyLine, DecoText): \"\"\"A polyline that closes automatically", "increase the BB width and height self._node = None def __str__(self): s =", ":= \"%s\"'%(sAttrName,initialValue) else: if not sAttrValue: del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName", "be an attribute value return Deco.toInt(s) except Exception, e: if bShowError: self.xpathError(node, xpExpr,", "return s class DecoClickableRectangleJump(DecoBBXYWH): \"\"\"A rectangle clicking on it jump to a node", "by X,Y for its top-left corner and width/height. xpX, xpY, xpW, xpH are", "DecoTextBox(DecoRectangle): \"\"\"A text within a bounding box (a rectangle) \"\"\" def __init__(self, cfg,", "rectangle) \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpContent =", "self.xpathEval(node.doc.getroot(), '//*[@id=\"%s\"]'%sToId.strip()) if ln: #find the page number ndTo = nd = ln[0]", "list of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) #add the image", "\"xpath_AttrValue\") self.dInitialValue = {} self.xpLineColorSlctd = cfg.get(sSurname, \"xpath_LineColor_Selected\") self.xpLineWidthSlctd = cfg.get(sSurname, \"xpath_LineWidth_Selected\") self.xpFillColorSlctd", "s def runXYWHI(self, node): \"\"\"get the X,Y values for a node and put", "[] for _sPair in sCoords.split(' '): (sx, sy) = _sPair.split(',') ltXY.append((Deco.toInt(sx), Deco.toInt(sy))) except", "of font size ltXY = self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt,", "self.xpY, 1) self._w = self.xpathToInt(node, self.xpW, 1) self._h = self.xpathToInt(node, self.xpH, 1) self._inc", "DecoTextPolyLine(DecoPolyLine, DecoText): \"\"\"A polyline that closes automatically the shape <NAME> - September 2016", "sMsg if s == Deco._s_prev_xpath_error: # let's not overload the console. return Deco._s_prev_xpath_error", "if node.get(\"id\") is None: self.warning(\"No coordinates: node = %s\" % etree.tostring(node)) else: self.warning(\"No", "can also indicate the precise arrival point? if self.xp_xTo and self.xp_yTo and self.xp_hTo", "self.xpathToInt(node, self.xpY_Inc, 0, False) txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize,", "Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='bl' , Color=sFontColor , LineColor=sLineColor , BackgroundColor=sBackgroundColor) lo.append(obj) except", "cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) def _getCoordList(self, node): lCoord = DecoPolyLine._getCoordList(self,", "random.randrange(iMaxFC) iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") for (_a,", "x, y, r) in self._laxyr: #draw a circle sFillColor = self.lsFillColor[Nf % iMaxFC]", "and self.xp_wTo: x = self.xpathToInt(ndTo, self.xp_xTo, None) y = self.xpathToInt(ndTo, self.xp_yTo, None) w", "x = x0 + Ex * iOffset y = -y0+iFontSize/6 obj = wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength]", "type(s) == types.ListType: try: s = s[0].text except AttributeError: s = s[0] #should", "self.xpCtxt.setContextNode(node) if xpExpr[0] == \"|\": #must be a lambda assert xpExpr[:8] == \"|lambda", "self.xpCtxt.setContextNode(node) s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try: s = s[0].text except", "lo class DecoClosedPolyLine(DecoPolyLine): \"\"\"A polyline that closes automatically the shape <NAME> - September", "try: #number = max(0, int(nd.prop(\"number\")) - 1) number = max(0, self.xpathToInt(nd, sPageNumberAttr, 1,", "xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize = cfg.get(sSurname, \"xpath_font_size\")", "self.xpathError(node, xpExpr, e, \"xpathToStr return %s as default value\"%sDefault) return sDefault def xpathEval(self,", "self.xpathToInt(node, self.xpW, 1) self._h = self.xpathToInt(node, self.xpH, 1) self._inc = self.xpathToInt(node, self.xpInc, 0)", "<NAME> - March 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname,", "!= types.ClassType: raise Exception(\"No such decoration type: '%s'\"%sClass) return c getDecoClass = classmethod(getDecoClass)", "None: if node.prop(sAttrName) == sAttrValue: sLineColor = self.xpathToStr(node, self.xpLineColorSlctd, \"#000000\") iLineWidth = self.xpathToInt(node,", "24 * abs(x2-x1) / Ex / len(txt) except: self.warning(\"absence of text: cannot compute", "self.xpEvalY2 = cfg.get(sSurname, \"eval_xpath_x2\"), cfg.get(sSurname, \"eval_xpath_y2\") self.xpDfltX2, self.xpDfltY2 = cfg.get(sSurname, \"xpath_x2_default\"), cfg.get(sSurname, \"xpath_y2_default\")", "__str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def draw(self, wxh, node):", "precise arrival point? if self.xp_xTo and self.xp_yTo and self.xp_hTo and self.xp_wTo: x =", "iLARGENEG: self._y2 = self.xpathToInt(node, self.xpDfltY2, iLARGENEG) self._node = node if self._x1 != iLARGENEG", "objects\"\"\" return [] class DecoBBXYWH(Deco): \"\"\"A decoration with a bounding box defined by", "self._coordList_to_BB(ltXY) obj = wxh.AddScaledText(txt, (x, -y+iFontSize/6), Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='tl' , Color=sFontColor)", "if sMsg: s += \"\\n--- Info: %s\" % sMsg if s == Deco._s_prev_xpath_error:", "= self.config.getPageNumberAttr() number = None x,y,w,h = None, None, None, None bbHighlight =", "wx created objects\"\"\" return [] class DecoBBXYWH(Deco): \"\"\"A decoration with a bounding box", "if self._laxyr: iMaxFC = len(self.lsFillColor) iMaxLC = len(self.lsLineColor) if False: Nf = DecoClusterCircle.count", "if bNoCase else name.strip() dic[name].append(dicValForName) return dic class DecoREADTextLine_custom_offset(DecoREADTextLine, READ_custom): \"\"\" Here we", "print n.serialize() lo = DecoREAD.draw(self, wxh, node) if self._node != node: self._lxy =", "\"BLACK\") x, y = int(x + w/2.0), int(y + h/2.0) if self.bInit: #draw", "'BLACK') sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") sBackgroundColor = self.xpathToStr(node, self.xpBackgroundColor, \"#000000\") # Position", "\"\"\"A link from x1,y1 to x2,y2 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self,", "lName: name = name.strip().lower() if bNoCase else name.strip() dic[name].append(dicValForName) return dic class DecoREADTextLine_custom_offset(DecoREADTextLine,", "lCoord class DecoTextPolyLine(DecoPolyLine, DecoText): \"\"\"A polyline that closes automatically the shape <NAME> -", "that name dicValForName = dict() lsKeyVal = sValues.split(';') #things like \"x:1\" for sKeyVal", "= iFontSizeX elif sFit == \"y\": iFontSize = iFontSizeY else: iFontSize = min(iFontSizeX,", "def getDecoClass(cls, sClass): \"\"\"given a decoration type, return the associated class\"\"\" c =", "in a certain base, e.g. 10 or 16 \"\"\" def __init__(self, cfg, sSurname,", "RED GREEN\" FillColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" enabled=1 \"\"\" count = 0", "h) lo.append(obj) except Exception, e: self.warning(\"DecoImageBox ERROR: File %s: %s\"%(sFilePath, str(e))) lo.append( DecoRectangle.draw(self,", "= \"-\"*60 s += \"\\n--- XPath ERROR on class %s\"%self.__class__ s += \"\\n---", "find the rectangle line and fill colors self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth =", "sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname,", "xpCtxt) def _getCoordList(self, node): lCoord = DecoPolyLine._getCoordList(self, node) if lCoord: lCoord.append(lCoord[0]) return lCoord", "LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoREAD(Deco): \"\"\" READ PageXml has a", "abs(x2-x1) / Ex / len(txt) except: self.warning(\"absence of text: cannot compute font size", "get the xpath expressions that let uis find x,y,w,h from a selected node", "Position='cl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo def getText(self, wxh, node): return self.xpathToStr(node,", "dc.SetFont(wx.Font(iFontSize, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") del dc return iFontSize, Ex,", "= self.dInitialValue[node] except KeyError: initialValue = node.prop(sAttrName) #first time self.dInitialValue[node] = initialValue if", "logging.error(\"DecoUnicodeChar: ERROR: base=%d code=%s\"%(self.base, sEncodedText)) return \"\" class DecoImageBox(DecoRectangle): \"\"\"An image with a", "logging.error(\"ERROR: polyline coords are bad: '%s' -> '%s'\" % ( self.xpCoords, sCoords)) raise", "wil remove it. del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName, initialValue)", "Python Exception=%s\" % str(eExcpt) if sMsg: s += \"\\n--- Info: %s\" % sMsg", "-y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoClosedPolyLine(DecoPolyLine): \"\"\"A polyline that", "\"Solid\") else: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillColor", "if os.path.exists(sCandidate): sFilePath = sCandidate except ValueError: pass if not os.path.exists(sFilePath): #maybe the", "evaluate the xpath expression return None on error \"\"\" try: # s =", "sSurname, xpCtxt): DecoREADTextLine.__init__(self, cfg, sSurname, xpCtxt) self.xpLabel = cfg.get(sSurname, \"xpath_label\") self.xpLineColor = cfg.get(sSurname,", "self.xpathToInt(node, self.xpX2, iLARGENEG) self._y2 = self.xpathToInt(node, self.xpY2, iLARGENEG) self._node = node if self._x1", "should contain the following items: x, y, w, h \"\"\" Deco.__init__(self, cfg, sSurname,", "_dLabel in _ldLabel: try: iOffset = int(_dLabel[\"offset\"]) iLength = int(_dLabel[\"length\"]) x = x0", "<0: return -fA, (xg, yg) else: return fA, (xg, yg) assert fA >0", "sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self): s", "e, \"xpathToInt return %d as default value\"%iDefault) return iDefault def xpathToStr(self, node, xpExpr,", "self.xpCtxt = xpCtxt #this context may include the declaration of some namespace sEnabled", "\"xpath_yTo\") self.xp_wTo = cfg.get(sSurname, \"xpath_wTo\") self.xp_hTo = cfg.get(sSurname, \"xpath_hTo\") self.xpAttrToId = cfg.get(sSurname, \"xpath_ToId\")", "< 2: raise ValueError(\"Only one point: polygon area is undefined.\") fA = 0.0", "= cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrToPageNumber = cfg.get(sSurname, \"xpath_ToPageNumber\") def __str__(self):", "unicode index is given in a certain base, e.g. 10 or 16 \"\"\"", "; y:2\") except Exception: raise ValueError(\"Expected a '{' in '%s'\"%chunk) #the dictionary for", "self._lxy: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) for (x1,", "self._y = self.xpathToInt(node, self.xpY, 1) self._w = self.xpathToInt(node, self.xpW, 1) self._h = self.xpathToInt(node,", "\"(%s)(%s)\" % (sLambdaExpr, repr(sArg)) s = eval(sPythonExpr) else: s = self.xpCtxt.xpathEval(xpExpr) if type(s)", "text def draw(self, wxh, node): lo = Deco.draw(self, wxh, node) if self._node !=", "iLARGENEG, False) #do not show any error if self._y2 == iLARGENEG: self._y2 =", "1) sFillColor = self.xpathToStr(node, self.xpFillColor, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") obj =", "line obj = wxh.AddLine( [(self._x1, -self._y1), (self._x2, -self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj)", "dCustom[self.xpathToStr(node, self.xpLabel, \"\").lower()] for _dLabel in _ldLabel: try: iOffset = int(_dLabel[\"offset\"]) iLength =", "= {} self.xpLineColorSlctd = cfg.get(sSurname, \"xpath_LineColor_Selected\") self.xpLineWidthSlctd = cfg.get(sSurname, \"xpath_LineWidth_Selected\") self.xpFillColorSlctd = cfg.get(sSurname,", "self.xpLineWidth, 1) sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") for (_a, x, y, r) in", "r = self.xpathToInt(ndItem, self.xpRadius, 1) self._laxyr.append( (fA, xg, yg, r) ) self._node =", "+= iTerm * (xprev+x) ySum += iTerm * (yprev+y) xprev, yprev = x,", "ndItem = l[0] lxy = self._getCoordList(ndItem) fA, (xg, yg) = self.getArea_and_CenterOfMass(lxy) r =", "cfg, sSurname, xpCtxt): \"\"\" cfg is a configuration object sSurname is the surname", "cfg.get(sSurname, \"xpath_y2_default\") #now get the xpath expressions that let us find the rectangle", "obj = wxh.AddLine( [(self.prevX, -self.prevY), (x, -y)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) else:", "self.xpathToInt(node, xpX2, iLARGENEG, False) #do not show any error if self._x2 == iLARGENEG:", "'true'] def isSeparator(cls): return False isSeparator = classmethod(isSeparator) def __str__(self): return \"(Surname=%s xpath==%s)\"", "return c getDecoClass = classmethod(getDecoClass) def getSurname(self): return self.sSurname def getMainXPath(self): return self.xpMain", "\"\"\" dic = defaultdict(list) s = s.strip() lChunk = s.split('}') if lChunk: for", "self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj =", "\"enabled\").lower() self.bEnabled = sEnabled in ['1', 'yes', 'true'] def isSeparator(cls): return False isSeparator", "#number = max(0, int(nd.prop(\"number\")) - 1) number = max(0, self.xpathToInt(nd, sPageNumberAttr, 1, True)", "return the list of wx created objects\"\"\" return [] class DecoBBXYWH(Deco): \"\"\"A decoration", "obj = wxh.AddLine( [(self._x1, -self._y1), (self._x2, -self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return", "\"\"\"A text \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpContent", "self.xpY2, iLARGENEG) self._node = node if self._x1 != iLARGENEG and self._y1 != iLARGENEG", "Example of config: [TextLine] type=DecoPolyLine xpath=.//TextLine/Coords xpath_lxy=@points xpath_LineColor=\"RED\" xpath_FillStyle=\"Solid\" <NAME> - March 2016", "h > 0: obj = wxh.AddScaledBitmap(img, (x,-y), h) else: obj = wxh.AddScaledBitmap(img, (x,-y),", "if self._x2 == iLARGENEG: self._x2 = self.xpathToInt(node, self.xpDfltX2, iLARGENEG) xpY2 = self.xpathToStr(node, self.xpEvalY2,", "#double evaluation, and a default value if necessary xpX2 = self.xpathToStr(node, self.xpEvalX2, '\"\"')", "sAttrValue) s = '@%s := \"%s\"'%(sAttrName,sAttrValue) return s class DecoClickableRectangleJump(DecoBBXYWH): \"\"\"A rectangle clicking", "= '@%s := \"%s\"'%(sAttrName,initialValue) else: if not sAttrValue: del node.attrib[sAttrName] s = \"Removal", "'%s'\"%chunk) #the dictionary for that name dicValForName = dict() lsKeyVal = sValues.split(';') #things", "using WX \"\"\" import types, os from collections import defaultdict import glob import", "font size ltXY = self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE)", "sSurname, xpCtxt) DecoText .__init__(self, cfg, sSurname, xpCtxt) self.xpX_Inc = cfg.get(sSurname, \"xpath_x_incr\") #to shift", "shape <NAME> - September 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg,", "self.lsFillColor = cfg.get(sSurname, \"FillColors\").split() #cached values self._node = None self._laxyr = None print", "= self.lsFillColor[Nf % iMaxFC] if self.lsLineColor: sLineColor = self.lsLineColor[Nl % iMaxLC] else: sLineColor", "self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillColor =", "self.xpAttrValue, None) if sAttrName and sAttrValue != None: try: initialValue = self.dInitialValue[node] except", "xpCtxt) #now get the xpath expressions that let uis find x,y,w,h from a", "This section should contain the following items: x, y, w, h \"\"\" Deco.__init__(self,", "DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth =", "class DecoSeparator: \"\"\" this is not properly a decoration but rather a separator", "\"xpath_x2_default\"), cfg.get(sSurname, \"xpath_y2_default\") #now get the xpath expressions that let us find the", "wx handle return a list of created WX objects\"\"\" lo = [] #add", "\"xpath_content\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") self.xpFit = cfg.get(sSurname, \"xpath_fit_text_size\").lower() def __str__(self): s =", "= b return b def isActionable(self): return False def setXPathContext(self, xpCtxt): self.xpCtxt =", "itself txt = self.getText(wxh, node) iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node,", "#very special case: when an attr was set, then saved, re-clicking on it", "node): \"\"\"get the X,Y values for a node and put them in cache\"\"\"", "a decoration type, return the associated class\"\"\" c = globals()[sClass] if type(c) !=", "error if self._y2 == iLARGENEG: self._y2 = self.xpathToInt(node, self.xpDfltY2, iLARGENEG) self._node = node", "itself using the wx handle return a list of created WX objects \"\"\"", "Color=sFontColor , LineColor=sLineColor , BackgroundColor=sBackgroundColor) lo.append(obj) except KeyError: pass except KeyError: pass return", "= cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle =", "polyline coords are bad: '%s' -> '%s'\" % ( self.xpCoords, sCoords)) raise e", "cfg.get(sSurname, \"xpath_x2_default\"), cfg.get(sSurname, \"xpath_y2_default\") #now get the xpath expressions that let us find", "= cfg.get(sSurname, \"xpath_lxy\") def _getCoordList(self, node): sCoords = self.xpathToStr(node, self.xpCoords, \"\") if not", "self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y+inc), Size=iFontSize, Family=wx.ROMAN, Position='tl',", "\"xpath_x_incr\") #to shift the text self.xpY_Inc = cfg.get(sSurname, \"xpath_y_incr\") #to shift the text", "\"\"\" Everything related to the PageXML custom attribute \"\"\" @classmethod def parseCustomAttr(cls, s,", "dCustom = self.parseCustomAttr(node.get(\"custom\"), bNoCase=True) try: x0, y0 = ltXY[0] _ldLabel = dCustom[self.xpathToStr(node, self.xpLabel,", "None) if sAttrName and sAttrValue != None: if node.prop(sAttrName) == sAttrValue: sLineColor =", "not sKeyVal.strip(): continue #empty try: sKey, sVal = sKeyVal.split(':') except Exception: raise ValueError(\"Expected", "created WX objects\"\"\" # print node.serialize() # print self.xpX # for n in", "xpCtxt): \"\"\" cfg is a config file sSurname is the decoration surname and", "= sKeyVal.split(':') except Exception: raise ValueError(\"Expected a comma-separated string, got '%s'\"%sKeyVal) sKey =", "= wxh.AddScaledTextBox(txt, (x+x_inc, -y-y_inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo", "import wx sEncoding = \"utf-8\" def setEncoding(s): global sEncoding sEncoding = s class", ", Family=wx.FONTFAMILY_TELETYPE , Position='tl' , Color=sFontColor) lo.append(obj) return lo def getText(self, wxh, node):", "node. The XPath expression should return a scalar or a one-node nodeset On", "return the default int value \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) if", "LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoClickableRectangleSetAttr(DecoBBXYWH): \"\"\"A rectangle clicking on it", "to truncate the node serialization s = \"-\"*60 s += \"\\n--- XPath ERROR", "1, True) - 1) #maybe we can also indicate the precise arrival point?", "FillStyle=\"Transparent\") self.prevX, self.prevY = x, y return lo class DecoLine(Deco): \"\"\"A line from", "0.0\") fA = fA / 2 xg, yg = xSum/6/fA, ySum/6/fA if fA", "https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone return A, (Xg, Yg) which are the area and the coordinates (float)", "return eval('u\"\\\\u%04x\"' % int(sEncodedText, self.base)) except ValueError: logging.error(\"DecoUnicodeChar: ERROR: base=%d code=%s\"%(self.base, sEncodedText)) return", "DecoBBXYWH.__str__(self) return s def draw(self, wxh, node): \"\"\"draw itself using the wx handle", "the surname of the decoration and the section name in the config file!", "self.xpW, 1) self._h = self.xpathToInt(node, self.xpH, 1) self._inc = self.xpathToInt(node, self.xpInc, 0) self._x,self._y", "'\"\"') self._x2 = self.xpathToInt(node, xpX2, iLARGENEG, False) #do not show any error if", "to encode coordinates. like: <Coords points=\"985,390 1505,390 1505,440 985,440\"/> or <Baseline points=\"985,435 1505,435\"/>", "= max(0, self.xpathToInt(nd, sPageNumberAttr, 1, True) - 1) #maybe we can also indicate", "'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y-h/2.0), Size=iFontSize, Family=wx.ROMAN, Position='cl', Color=sFontColor,", "\"\"\" import types, os from collections import defaultdict import glob import logging import", "s = s[0].text except AttributeError: s = s[0] #should be an attribute value", "sFilePath)) if os.path.exists(sCandidate): sFilePath = sCandidate print(sFilePath) break if not os.path.exists(sFilePath): # maybe", "self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") #the following expression must be evaluated twice", "xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self)", "= os.path.dirname(sUrl[len(sPrefix):]) sDir,_ = os.path.splitext(os.path.basename(sUrl)) sCandidate = os.path.abspath(os.path.join(sLocalDir, sDir, sFilePath)) if os.path.exists(sCandidate): sFilePath", "r) ) self._node = node if self._laxyr: iMaxFC = len(self.lsFillColor) iMaxLC = len(self.lsLineColor)", "def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname,", "polyline along x1,y1,x2,y2, ...,xn,yn or x1,y1 x2,y2 .... xn,yn Example of config: [TextLine]", "cfg.get(sSurname, \"xpath_y_incr\") #to shift the text def draw(self, wxh, node): lo = Deco.draw(self,", "self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc", "node: self._x = self.xpathToInt(node, self.xpX, 1) self._y = self.xpathToInt(node, self.xpY, 1) self._w =", "xpath expressions that let uis find x,y,w,h from a selected node self.xpX, self.xpY", "== sAttrValue: sLineColor = self.xpathToStr(node, self.xpLineColorSlctd, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidthSlctd, 1) sFillColor", "= self._lxy[0] x_inc = self.xpathToInt(node, self.xpX_Inc, 0, False) y_inc = self.xpathToInt(node, self.xpY_Inc, 0,", "(x2, y2) = self._coordList_to_BB(ltXY) sFit = self.xpathToStr(node, self.xpFit, 'xy', bShowError=False) try: iFontSize =", "it jump to a page \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg,", "name in the config file! xpCtxt is an XPath context \"\"\" self.sSurname =", "along X axis\") iFontSizeX = 8 iFontSizeY = 24 * abs(y2-y1) / Ey", "{} self.xpLineColorSlctd = cfg.get(sSurname, \"xpath_LineColor_Selected\") self.xpLineWidthSlctd = cfg.get(sSurname, \"xpath_LineWidth_Selected\") self.xpFillColorSlctd = cfg.get(sSurname, \"xpath_FillColor_Selected\")", "iFontSize = int(sFit) Ex, Ey = None, None except ValueError: dc = wx.ScreenDC()", "DecoRectangle.draw(self, wxh, node) #add the text itself txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize", "node: self._lxy = self._getCoordList(node) self._node = node if self._lxy: sLineColor = self.xpathToStr(node, self.xpLineColor,", "self.xpathToStr(node, self.xpBackgroundColor, \"#000000\") # Position and computation of font size ltXY = self._getCoordList(node)", ">0 and yg >0, \"%s\\t%s\"%(lXY (fA, (xg, yg))) return fA, (xg, yg) def", "this is not properly a decoration but rather a separator of decoration in", "\"\"\"A rectangle clicking on it add/remove an attribute the rectangle color is indicative", "#HACK def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def isActionable(self):", "length:11;} Item-price {offset:12; length:2;}\"> <Coords points=\"985,390 1505,390 1505,440 985,440\"/> <Baseline points=\"985,435 1505,435\"/> <TextEquiv>", "box (a rectangle) \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt)", "y_inc = self.xpathToInt(node, self.xpY_Inc, 0, False) txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize =", "= True for s in lCandidate: if os.path.exists(s): sFilePath = s bKO =", "try: iOffset = int(_dLabel[\"offset\"]) iLength = int(_dLabel[\"length\"]) x = x0 + Ex *", "node = %s\" % sNode s += \"\\n\" + \"-\"*60 + \"\\n\" logging.warning(s)", "getArea_and_CenterOfMass(self, lXY): \"\"\" https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone return A, (Xg, Yg) which are the area and", "cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") def __str__(self): s = \"%s=\"%self.__class__ s +=", "of list of dictionary Example: parseCustomAttr( \"readingOrder {index:4;} structure {type:catch-word;}\" ) --> {", "os.path.exists(s): sFilePath = s bKO = False break if bKO: self.warning(\"WARNING: deco Image:", "for this font size return iFontSize, ExtentX, ExtentY \"\"\" (x1, y1), (x2, y2)", "node return (self._x, self._y, self._w, self._h, self._inc) class DecoRectangle(DecoBBXYWH): \"\"\"A rectangle \"\"\" def", "= dc.GetTextExtent(\"x\") try: iFontSizeX = 24 * abs(x2-x1) / Ex / len(txt) except:", "itself using the wx handle return a list of created WX objects\"\"\" DecoClusterCircle.count", "nd = ln[0] #while nd and nd.name != \"PAGE\": nd = nd.parent while", "s = \"%s=\"%self.__class__ return s def _getFontSize(self, node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE): \"\"\" compute", "sCandidate else: # maybe the file is in a subfolder ? # e.g.", "node if self._lxy: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1)", "Deco._warning_count = 0 # if sMsg != Deco._s_prev_warning and Deco._warning_count < 1000: if", "of the 'x' character for this font size return iFontSize, ExtentX, ExtentY \"\"\"", "# let's not overload the console. return Deco._s_prev_xpath_error = s Deco._prev_xpath_error_count += 1", "s = '@%s := \"%s\"'%(sAttrName,sAttrValue) return s class DecoClickableRectangleJump(DecoBBXYWH): \"\"\"A rectangle clicking on", "= self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') # Position and computation of", "ValueError(\"Expected a comma-separated string, got '%s'\"%sKeyVal) sKey = sKey.strip().lower() if bNoCase else sKey.strip()", "'%s'\"%sClass) return c getDecoClass = classmethod(getDecoClass) def getSurname(self): return self.sSurname def getMainXPath(self): return", "= 0, 0 xprev, yprev = lXY[-1] for x, y in lXY: iTerm", "= [obj] + lo return lo def act(self, obj, node): \"\"\" return the", "sCoords.split(' '): (sx, sy) = _sPair.split(',') ltXY.append((Deco.toInt(sx), Deco.toInt(sy))) except Exception as e: logging.error(\"ERROR:", "return True def setXPathContext(self, xpCtxt): pass class Deco: \"\"\"A general decoration class\"\"\" def", "= Deco.draw(self, wxh, node) if self._node != node: self._lxy = self._getCoordList(node) self._node =", "\"\"\" lo = [] #add the text itself txt = self.getText(wxh, node) sFontColor", "(x, -y)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) else: self.bInit = True iEllipseParam =", "rectangle color is indicative of the presence/absence of the attribute \"\"\" def __init__(self,", "bKO = True for s in lCandidate: if os.path.exists(s): sFilePath = s bKO", "cfg.get(sSurname, \"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def", "uis find x,y,w,h from a selected node self.xpX, self.xpY = cfg.get(sSurname, \"xpath_x\"), cfg.get(sSurname,", "return iDefault def xpathToStr(self, node, xpExpr, sDefault, bShowError=True): \"\"\"The given XPath expression should", "attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREADTextLine.__init__(self, cfg, sSurname, xpCtxt) self.xpLabel =", "are scalar XPath expressions to get the associated x,y,w,h values from the selected", "self._node != node: self._laxyr = [] #need to go thru each item ndPage", "sToId: ln = self.xpathEval(node.doc.getroot(), '//*[@id=\"%s\"]'%sToId.strip()) if ln: #find the page number ndTo =", "= self.getArea_and_CenterOfMass(lxy) r = self.xpathToInt(ndItem, self.xpRadius, 1) self._laxyr.append( (fA, xg, yg, r) )", "def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\")", "node): return self.xpathToStr(node, self.xpContent, \"\") class READ_custom: \"\"\" Everything related to the PageXML", "dictionary of list of dictionary Example: parseCustomAttr( \"readingOrder {index:4;} structure {type:catch-word;}\" ) -->", "2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) DecoText .__init__(self,", "error\"\"\" try: Deco._s_prev_warning except AttributeError: Deco._s_prev_warning = \"\" Deco._warning_count = 0 # if", "\"\\n--- Python Exception=%s\" % str(eExcpt) if sMsg: s += \"\\n--- Info: %s\" %", "self._getCoordList(node) self._node = node #lo = DecoClosedPolyLine.draw(self, wxh, node) #add the text itself", "coordinates (float) of the center of mass of the polygon \"\"\" if len(lXY)", "self._y2 == iLARGENEG: self._y2 = self.xpathToInt(node, self.xpDfltY2, iLARGENEG) self._node = node if self._x1", "sDir,_ = os.path.splitext(os.path.basename(sUrl)) sCandidate = os.path.abspath(os.path.join(sLocalDir, sDir, sFilePath)) if os.path.exists(sCandidate): sFilePath = sCandidate", "using the wx handle return a list of created WX objects \"\"\" lo", "decoration but rather a separator of decoration in the toolbar \"\"\" def __init__(self,", "of created WX objects\"\"\" lo = DecoRectangle.draw(self, wxh, node) #add the text itself", "try: Deco._s_prev_xpath_error except AttributeError: Deco._s_prev_xpath_error = \"\" Deco._prev_xpath_error_count = 0 iMaxLen = 200", "from lxml import etree #import cStringIO import wx sEncoding = \"utf-8\" def setEncoding(s):", "base=%d code=%s\"%(self.base, sEncodedText)) return \"\" class DecoImageBox(DecoRectangle): \"\"\"An image with a box around", "wxh, node) if self._node != node: self._lxy = self._getCoordList(node) self._node = node if", "= chunk.strip() if not chunk: continue try: sNames, sValues = chunk.split('{') #things like:", "cfg, sSurname, xpCtxt) #now get the xpath expressions that let uis find x,y,w,h", "return dic class DecoREADTextLine_custom_offset(DecoREADTextLine, READ_custom): \"\"\" Here we show the annotation by offset", "self.xpathToStr(node, self.xpFillStyle, \"Solid\") obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle)", "= cfg.get(sSurname, \"xpath_FillStyle\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s", "self.xpathToStr(node, self.xpFontColor, 'BLACK') obj = wxh.AddScaledTextBox(txt, (x+x_inc, -y-y_inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0,", "Nl = Nf else: Nf = random.randrange(iMaxFC) Nl = random.randrange(iMaxFC) iLineWidth = self.xpathToInt(node,", "__init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpCoords = cfg.get(sSurname, \"xpath_lxy\") def", "and the coordinates (float) of the center of mass of the polygon \"\"\"", "s = '@%s := \"%s\"'%(sAttrName,initialValue) else: if not sAttrValue: del node.attrib[sAttrName] s =", "return a list of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc", "y = ltXY[0] (x, _y1), (_x2, y) = self._coordList_to_BB(ltXY) obj = wxh.AddScaledText(txt, (x,", "\", self.lsLineColor print \"DecoClusterCircle lsFillColor = \", self.lsFillColor def __str__(self): s = \"%s=\"%self.__class__", "self.xpMain) def getDecoClass(cls, sClass): \"\"\"given a decoration type, return the associated class\"\"\" c", "along x1,y1,x2,y2, ...,xn,yn or x1,y1 x2,y2 .... xn,yn Example of config: [TextLine] type=DecoPolyLine", "self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.lsLineColor = cfg.get(sSurname, \"LineColors\").split() self.lsFillColor = cfg.get(sSurname, \"FillColors\").split() #cached", "__str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return s def draw(self,", "= DecoClusterCircle.count Nl = Nf else: Nf = random.randrange(iMaxFC) Nl = random.randrange(iMaxFC) iLineWidth", "try: iFontSize = int(sFit) Ex, Ey = None, None except ValueError: dc =", "XML node = %s\" % sNode s += \"\\n\" + \"-\"*60 + \"\\n\"", "= cfg.get(sSurname, \"xpath_yTo\") self.xp_wTo = cfg.get(sSurname, \"xpath_wTo\") self.xp_hTo = cfg.get(sSurname, \"xpath_hTo\") self.xpAttrToId =", "the center of mass of the polygon \"\"\" if len(lXY) < 2: raise", "DecoClusterCircle.count Nl = Nf else: Nf = random.randrange(iMaxFC) Nl = random.randrange(iMaxFC) iLineWidth =", "= DecoBBXYWH.draw(self, wxh, node) #add the text itself txt = self.getText(wxh, node) iFontSize", "(x2, y2) in zip(self._lxy, self._lxy[1:]): #draw a line obj = wxh.AddLine( [(x1, -y1),", "return a list of created WX objects \"\"\" lo = [] #add the", "self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) self._x2 = self.xpathToInt(node, self.xpX2, iLARGENEG) self._y2 = self.xpathToInt(node,", "if self.bInit: #draw a line iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) obj = wxh.AddLine(", "context \"\"\" self.sSurname = sSurname def __str__(self): return \"--------\" def isSeparator(self): return True", "decoration type: '%s'\"%sClass) return c getDecoClass = classmethod(getDecoClass) def getSurname(self): return self.sSurname def", "\"...\" s += \"\\n--- XML node = %s\" % sNode s += \"\\n\"", "<Coords points=\"985,390 1505,390 1505,440 985,440\"/> <Baseline points=\"985,435 1505,435\"/> <TextEquiv> <Unicode>Salgadinhos 12</Unicode> </TextEquiv> </TextLine>", "False break if bKO: self.warning(\"WARNING: deco Image: file does not exists: '%s'\"%sFilePath) sFilePath", "fill colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") #cached values self._node", "Family=wx.FONTFAMILY_TELETYPE): \"\"\" compute the font size so as to fit the polygon and", "Deco._s_prev_warning = \"\" Deco._warning_count = 0 # if sMsg != Deco._s_prev_warning and Deco._warning_count", "cfg.get(sSurname, \"xpath_LineWidth\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def", "and fill colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self._node =", "self.lsLineColor print \"DecoClusterCircle lsFillColor = \", self.lsFillColor def __str__(self): s = \"%s=\"%self.__class__ s", "str(e))) lo.append( DecoRectangle.draw(self, wxh, node) ) return lo class DecoImage(DecoBBXYWH): \"\"\"An image \"\"\"", "self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) #double evaluation, and a default value if necessary", "object sSurname is the surname of the decoration and the section name in", "self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle", "sSurname, xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") #the following expression must", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpCoords = cfg.get(sSurname,", "size so as to fit the polygon and the extent of the 'x'", "self.xpCtxt = xpCtxt def xpathError(self, node, xpExpr, eExcpt, sMsg=\"\"): \"\"\"report an xpath error\"\"\"", "a '{' in '%s'\"%chunk) #the dictionary for that name dicValForName = dict() lsKeyVal", "def getMainXPath(self): return self.xpMain def isEnabled(self): return self.bEnabled def setEnabled(self, b=True): self.bEnabled =", "int(cfg.get(sSurname, \"code_base\")) def getText(self, wxh, node): sEncodedText = self.xpathToStr(node, self.xpContent, \"\") try: return", "self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') # Position and computation of font", "\"xpath_y_incr\") #to shift the text def draw(self, wxh, node): lo = Deco.draw(self, wxh,", "% iMaxLC] else: sLineColor = sFillColor obj = wxh.AddCircle((x, -y), r, LineWidth=iLineWidth, LineColor=sLineColor,", "try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) if xpExpr[0] == \"|\": #must be a", "of some namespace sEnabled = cfg.get(sSurname, \"enabled\").lower() self.bEnabled = sEnabled in ['1', 'yes',", "self.config.getPageTag() sPageNumberAttr = self.config.getPageNumberAttr() number = None x,y,w,h = None, None, None, None", "cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") self.xpFit =", "node) #add the text itself x, y = self._lxy[0] x_inc = self.xpathToInt(node, self.xpX_Inc,", "type(c) != types.ClassType: raise Exception(\"No such decoration type: '%s'\"%sClass) return c getDecoClass =", "of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) #add the image itself", "ySum = 0, 0 xprev, yprev = lXY[-1] for x, y in lXY:", "is not properly a decoration but rather a separator of decoration in the", "False def setXPathContext(self, xpCtxt): self.xpCtxt = xpCtxt def xpathError(self, node, xpExpr, eExcpt, sMsg=\"\"):", "def isSeparator(cls): return False isSeparator = classmethod(isSeparator) def __str__(self): return \"(Surname=%s xpath==%s)\" %", "cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrToPageNumber = cfg.get(sSurname,", "os from collections import defaultdict import glob import logging import random from lxml", "have some pattern?? lCandidate = glob.glob(sFilePath) bKO = True for s in lCandidate:", "DecoText): \"\"\"A polyline that closes automatically the shape <NAME> - September 2016 \"\"\"", "def _coordList_to_BB(self, ltXY): \"\"\" return (x1, y1), (x2, y2) \"\"\" lX = [_x", "if bool(sFilePath): img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) try: if h > 0: obj =", "sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillColor = self.xpathToStr(node,", "def __init__(self, cfg, sSurname, xpCtxt): DecoText.__init__(self, cfg, sSurname, xpCtxt) self.base = int(cfg.get(sSurname, \"code_base\"))", "%s\" % sNode s += \"\\n\" + \"-\"*60 + \"\\n\" logging.warning(s) def warning(self,", "self.xpY2) return s def draw(self, wxh, node): \"\"\"draw itself using the wx handle", "def isSeparator(self): return True def setXPathContext(self, xpCtxt): pass class Deco: \"\"\"A general decoration", "node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') # Position and computation of font size", "= wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength] , (x, y) , Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='bl' , Color=sFontColor", "the text itself txt = self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') sLineColor", "False) #do not show any error if self._y2 == iLARGENEG: self._y2 = self.xpathToInt(node,", "= self.xpathToStr(node, self.xpAttrToPageNumber , None) if sToPageNum: index = int(sToPageNum) - 1 return", "value \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) if xpExpr[0] == \"|\": #must", "= xpCtxt #this context may include the declaration of some namespace sEnabled =", "return lo class DecoClosedPolyLine(DecoPolyLine): \"\"\"A polyline that closes automatically the shape <NAME> -", "Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='tl' , Color=sFontColor) lo.append(obj) return lo def getText(self, wxh,", "self.xpBackgroundColor = cfg.get(sSurname, \"xpath_background_color\") def draw(self, wxh, node): \"\"\" draw itself using the", "0 iMaxLen = 200 # to truncate the node serialization s = \"-\"*60", "list of created WX objects\"\"\" lo = DecoRectangle.draw(self, wxh, node) #add the text", "x, y return lo class DecoLine(Deco): \"\"\"A line from x1,y1 to x2,y2 \"\"\"", "xpCtxt) self.xpX_Inc = cfg.get(sSurname, \"xpath_x_incr\") #to shift the text self.xpY_Inc = cfg.get(sSurname, \"xpath_y_incr\")", "when an attr was set, then saved, re-clicking on it wil remove it.", "setEncoding(s): global sEncoding sEncoding = s class DecoSeparator: \"\"\" this is not properly", "s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try: s = s[0].text except AttributeError:", "node) #add the text itself txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node,", "self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return", "of the center of mass of the polygon \"\"\" if len(lXY) < 2:", "arrival point? if self.xp_xTo and self.xp_yTo and self.xp_hTo and self.xp_wTo: x = self.xpathToInt(ndTo,", "self.prevY = x, y return lo class DecoLine(Deco): \"\"\"A line from x1,y1 to", "return lo def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class DecoUnicodeChar(DecoText): \"\"\"A", "XPath expression should return a string on the given node The XPath expression", "be evaluated twice self.xpEvalX2, self.xpEvalY2 = cfg.get(sSurname, \"eval_xpath_x2\"), cfg.get(sSurname, \"eval_xpath_y2\") self.xpDfltX2, self.xpDfltY2 =", "s += \"+(x=%s y=%s w=%s h=%s)\" % (self.xpX, self.xpY, self.xpW, self.xpH) return s", "= self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: try: img = wx.Image(sFilePath,", "self.xpathToStr(node, self.xpFontColor, 'BLACK') # Position and computation of font size ltXY = self._getCoordList(node)", "the xpath expressions that let us find the rectangle line and fill colors", "obj = wxh.AddLine( [(x1, -y1), (x2, -y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return", "associated x,y,w,h values from the selected nodes \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "= %s\" % etree.tostring(node)) else: self.warning(\"No coordinates: node id = %s\" % node.get(\"id\"))", "fA / 2 xg, yg = xSum/6/fA, ySum/6/fA if fA <0: return -fA,", "if necessary xpX2 = self.xpathToStr(node, self.xpEvalX2, '\"\"') self._x2 = self.xpathToInt(node, xpX2, iLARGENEG, False)", "list of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) #add the text", "cfg.get(sSurname, \"xpath_yTo\") self.xp_wTo = cfg.get(sSurname, \"xpath_wTo\") self.xp_hTo = cfg.get(sSurname, \"xpath_hTo\") self.xpAttrToId = cfg.get(sSurname,", "r, LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) # obj = wxh.AddRectangle((x, -y), (20, 20), #", "= 0 def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpCluster =", "cfg.get(sSurname, \"xpath_FillStyle\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def", "sValues = chunk.split('{') #things like: (\"a,b\", \"x:1 ; y:2\") except Exception: raise ValueError(\"Expected", "DecoREADTextLine.__init__(self, cfg, sSurname, xpCtxt) self.xpLabel = cfg.get(sSurname, \"xpath_label\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpBackgroundColor", "self.lsLineColor = cfg.get(sSurname, \"LineColors\").split() self.lsFillColor = cfg.get(sSurname, \"FillColors\").split() #cached values self._node = None", "sAttrValue: del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName, sAttrValue) s =", "page number of the destination or None on error \"\"\" index,x,y,w,h = None,None,None,None,None", "last '|'\" sArg = self.xpCtxt.xpathEval(xpExprArg)[0] sPythonExpr = \"(%s)(%s)\" % (sLambdaExpr, repr(sArg)) s =", "the text itself txt = self.getText(wxh, node) iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor", "text itself txt = self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') sLineColor =", "not sAttrValue: del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName, sAttrValue) s", "automatically the shape <NAME> - September 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "\"\"\" cfg is a configuration object sSurname is the surname of the decoration", "DecoRectangle.__str__(self) return s def draw(self, wxh, node): \"\"\"draw itself using the wx handle", "related to the PageXML custom attribute \"\"\" @classmethod def parseCustomAttr(cls, s, bNoCase=True): \"\"\"", "wxh.AddScaledText(txt, (x, -y+iFontSize/6), Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='tl' , Color=sFontColor) lo.append(obj) return lo", "\"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") #cached values self._node = None self._lxy = None", ", Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='bl' , Color=sFontColor , LineColor=sLineColor , BackgroundColor=sBackgroundColor) lo.append(obj)", "bKO: self.warning(\"WARNING: deco Image: file does not exists: '%s'\"%sFilePath) sFilePath = None if", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) DecoText .__init__(self, cfg,", "+= \"+(coords=%s)\" % (self.xpCoords) return s def getArea_and_CenterOfMass(self, lXY): \"\"\" https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone return A,", "points=\"985,435 1505,435\"/> <TextEquiv> <Unicode>Salgadinhos 12</Unicode> </TextEquiv> </TextLine> \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "custom attribute \"\"\" @classmethod def parseCustomAttr(cls, s, bNoCase=True): \"\"\" The custom attribute contains", "= dc.GetTextExtent(\"x\") del dc return iFontSize, Ex, Ey def draw(self, wxh, node): \"\"\"draw", "0 def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpCluster = cfg.get(sSurname,", "= [_y for _x,_y in ltXY] return (min(lX), max(lY)), (max(lX), min(lY)) class DecoREADTextLine(DecoREAD):", "obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo.append(obj) return lo", "cfg, sSurname, xpCtxt) self.base = int(cfg.get(sSurname, \"code_base\")) def getText(self, wxh, node): sEncodedText =", "% iMaxFC] if self.lsLineColor: sLineColor = self.lsLineColor[Nl % iMaxLC] else: sLineColor = sFillColor", "\"\"\" return (x1, y1), (x2, y2) \"\"\" lX = [_x for _x,_y in", "os.path.exists(sCandidate): sFilePath = sCandidate except ValueError: pass if not os.path.exists(sFilePath): #maybe the image", "self.xpAttrName , None) sAttrValue = self.xpathToStr(node, self.xpAttrValue, None) if sAttrName and sAttrValue !=", "\"\"\" READ PageXml has a special way to encode coordinates. like: <Coords points=\"985,390", "'%s'\"%sKeyVal) sKey = sKey.strip().lower() if bNoCase else sKey.strip() dicValForName[sKey] = sVal.strip() lName =", "the page number of the destination or None on error \"\"\" index,x,y,w,h =", "LineWidth=5, FillStyle=\"Transparent\") self.prevX, self.prevY = x, y return lo class DecoLine(Deco): \"\"\"A line", "n.serialize() iLARGENEG = -9999 lo = Deco.draw(self, wxh, node) if self._node != node:", "class DecoText(DecoBBXYWH): \"\"\"A text \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname,", "\"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrName = cfg.get(sSurname, \"xpath_AttrName\") self.xpAttrValue = cfg.get(sSurname, \"xpath_AttrValue\")", "\"xpath_LineWidth\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def beginPage(self,", "iLARGENEG and self._x2 != iLARGENEG and self._y2 != iLARGENEG: sLineColor = self.xpathToStr(node, self.xpLineColor,", "Here we show the annotation by offset found in the custom attribute \"\"\"", "Deco._s_prev_xpath_error = s Deco._prev_xpath_error_count += 1 if Deco._prev_xpath_error_count > 10: return try: sNode", "bShowError=True): \"\"\"The given XPath expression should return an int on the given node.", "shift the text self.xpY_Inc = cfg.get(sSurname, \"xpath_y_incr\") #to shift the text def draw(self,", "if not sAttrValue: del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName, sAttrValue)", "return lo class DecoOrder(DecoBBXYWH): \"\"\"Show the order with lines \"\"\" def __init__(self, cfg,", "RED GREEN\" enabled=1 \"\"\" count = 0 def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self,", "__init__(self, cfg, sSurname, xpCtxt): DecoText.__init__(self, cfg, sSurname, xpCtxt) self.base = int(cfg.get(sSurname, \"code_base\")) def", "of @%s\"%sAttrName else: node.set(sAttrName, sAttrValue) s = '@%s := \"%s\"'%(sAttrName,sAttrValue) return s class", "wxh, node) #add the text itself txt = self.getText(wxh, node) iFontSize = self.xpathToInt(node,", "def parseCustomAttr(cls, s, bNoCase=True): \"\"\" The custom attribute contains data in a CSS", "if not chunk: continue try: sNames, sValues = chunk.split('{') #things like: (\"a,b\", \"x:1", "sPrefix: sLocalDir = os.path.dirname(sUrl[len(sPrefix):]) sDir,_ = os.path.splitext(os.path.basename(sUrl)) sCandidate = os.path.abspath(os.path.join(sLocalDir, sDir, sFilePath)) if", "#back to previous value if initialValue == None or initialValue == sAttrValue: #very", "s = eval(sPythonExpr) else: s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try: s", "some namespace sEnabled = cfg.get(sSurname, \"enabled\").lower() self.bEnabled = sEnabled in ['1', 'yes', 'true']", "self._y2 = self.xpathToInt(node, self.xpY2, iLARGENEG) self._node = node if self._x1 != iLARGENEG and", "None) y = self.xpathToInt(ndTo, self.xp_yTo, None) w = self.xpathToInt(ndTo, self.xp_wTo, None) h =", "cfg.get(sSurname, \"xpath_fit_text_size\").lower() def __str__(self): s = \"%s=\"%self.__class__ return s def _getFontSize(self, node, ltXY,", "return the associated class\"\"\" c = globals()[sClass] if type(c) != types.ClassType: raise Exception(\"No", "node: self._laxyr = [] #need to go thru each item ndPage = node.xpath(\"ancestor::*[local-name()='Page']\")[0]", "ERROR: File %s: %s\"%(sFilePath, str(e))) return lo class DecoOrder(DecoBBXYWH): \"\"\"Show the order with", "= node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try: s =", "sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpCoords = cfg.get(sSurname, \"xpath_lxy\") def _getCoordList(self, node):", "os.path.dirname(sUrl[len(sPrefix):]) sDir,_ = os.path.splitext(os.path.basename(sUrl)) sCandidate = os.path.abspath(os.path.join(sLocalDir, sDir, sFilePath)) if os.path.exists(sCandidate): sFilePath =", "y=%s w=%s h=%s)\" % (self.xpX, self.xpY, self.xpW, self.xpH) return s def runXYWHI(self, node):", "= self.xpathToStr(node, self.xpEvalY2, '\"\"') self._y2 = self.xpathToInt(node, xpY2, iLARGENEG, False) #do not show", "self.bInit = False def draw(self, wxh, node): \"\"\"draw itself using the wx handle", "A class that reflect a decoration to be made on certain XML node", "xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize = cfg.get(sSurname, \"xpath_font_size\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\")", "% etree.tostring(node)) else: self.warning(\"No coordinates: node id = %s\" % node.get(\"id\")) return [(0,0)]", "= node return (self._x, self._y, self._w, self._h, self._inc) class DecoRectangle(DecoBBXYWH): \"\"\"A rectangle \"\"\"", "= int(sFit) Ex, Ey = None, None except ValueError: dc = wx.ScreenDC() #", "2 xg, yg = xSum/6/fA, ySum/6/fA if fA <0: return -fA, (xg, yg)", "8 iFontSizeY = 24 * abs(y2-y1) / Ey if sFit == \"x\": iFontSize", "proportional dc.SetFont(wx.Font(24, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") try: iFontSizeX = 24", "so as to fit the polygon and the extent of the 'x' character", "\"\"\"report an xpath error\"\"\" try: Deco._s_prev_xpath_error except AttributeError: Deco._s_prev_xpath_error = \"\" Deco._prev_xpath_error_count =", "cfg.get(sSurname, \"xpath_LineColor\") #cached values self._node = None self._lxy = None def __str__(self): s", "\", self.lsFillColor def __str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return", "sFillStyle = self.xpathToStr(node, self.xpFillStyleSlctd, \"Solid\") else: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth =", "x, y = int(x + w/2.0), int(y + h/2.0) if self.bInit: #draw a", "parse this syntax here and return a dictionary of list of dictionary Example:", "error\"\"\" try: Deco._s_prev_xpath_error except AttributeError: Deco._s_prev_xpath_error = \"\" Deco._prev_xpath_error_count = 0 iMaxLen =", "= self.xpathToInt(node, self.xpLineWidthSlctd, 1) sFillColor = self.xpathToStr(node, self.xpFillColorSlctd, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyleSlctd,", "xpExpr, iDefault=0, bShowError=True): \"\"\"The given XPath expression should return an int on the", "the image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath:", "\"|\": #must be a lambda assert xpExpr[:8] == \"|lambda \", \"Invalid lambda expression", "random from lxml import etree #import cStringIO import wx sEncoding = \"utf-8\" def", "sFilePath = sCandidate else: # maybe the file is in a subfolder ?", "bNoCase else name.strip() dic[name].append(dicValForName) return dic class DecoREADTextLine_custom_offset(DecoREADTextLine, READ_custom): \"\"\" Here we show", "cfg, sSurname, xpCtxt): DecoREADTextLine.__init__(self, cfg, sSurname, xpCtxt) self.xpLabel = cfg.get(sSurname, \"xpath_label\") self.xpLineColor =", "= wxh.AddLine( [(self.prevX, -self.prevY), (x, -y)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) else: self.bInit", "if self.lsLineColor: sLineColor = self.lsLineColor[Nl % iMaxLC] else: sLineColor = sFillColor obj =", "False) #do not show any error if self._x2 == iLARGENEG: self._x2 = self.xpathToInt(node,", "cfg.get(sSurname, \"xpath_y1\") #the following expression must be evaluated twice self.xpEvalX2, self.xpEvalY2 = cfg.get(sSurname,", "for sId in sIds.split(): l = self.xpathEval(ndPage, './/*[@id=\"%s\"]'%sId) ndItem = l[0] lxy =", "LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) else: self.bInit = True iEllipseParam = min(w,h) / 2", "self.xpathToStr(node, self.xpFit, 'xy', bShowError=False) try: iFontSize = int(sFit) Ex, Ey = None, None", "\"\"\"A polyline along x1,y1,x2,y2, ...,xn,yn or x1,y1 x2,y2 .... xn,yn Example of config:", "+ \"-\"*60 + \"\\n\" logging.warning(s) def warning(self, sMsg): \"\"\"report an xpath error\"\"\" try:", "a circle sFillColor = self.lsFillColor[Nf % iMaxFC] if self.lsLineColor: sLineColor = self.lsLineColor[Nl %", "in a subfolder ? # e.g. \"S_Aicha_an_der_Donau_004-03_0005.jpg\" is in folder \"S_Aicha_an_der_Donau_004-03\" try: sDir", "'readingOrder': [{ 'index':'4' }], 'structure':[{'type':'catch-word'}] } \"\"\" dic = defaultdict(list) s = s.strip()", "sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") sBackgroundColor = self.xpathToStr(node, self.xpBackgroundColor, \"#000000\") # Position and", "\"xpath_FillStyle\") self.lsLineColor = cfg.get(sSurname, \"LineColors\").split() self.lsFillColor = cfg.get(sSurname, \"FillColors\").split() #cached values self._node =", "2: raise ValueError(\"Only one point: polygon area is undefined.\") fA = 0.0 xSum,", "== \"y\": iFontSize = iFontSizeY else: iFontSize = min(iFontSizeX, iFontSizeY) dc.SetFont(wx.Font(iFontSize, Family, wx.FONTSTYLE_NORMAL,", "None) if x==None or y==None or w==None or h==None: x,y,w,h = None, None,", "self.xpathToStr(node, self.xpContent, \"\") class READ_custom: \"\"\" Everything related to the PageXML custom attribute", "--> { 'readingOrder': [{ 'index':'4' }], 'structure':[{'type':'catch-word'}] } \"\"\" dic = defaultdict(list) s", "= x0 + Ex * iOffset y = -y0+iFontSize/6 obj = wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength] ,", "Nf else: Nf = random.randrange(iMaxFC) Nl = random.randrange(iMaxFC) iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1)", "pass def draw(self, wxh, node): \"\"\"draw the associated decorations, return the list of", "Ey = self._getFontSize(node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE) # x, y = ltXY[0] (x, _y1),", "self.xpathToStr(node, self.xpAttrToId , None) if sToId: ln = self.xpathEval(node.doc.getroot(), '//*[@id=\"%s\"]'%sToId.strip()) if ln: #find", "= cfg.get(sSurname, \"xpath_ToId\") self.config = cfg.jl_hack_cfg #HACK def __str__(self): s = \"%s=\"%self.__class__ s", "\"code_base\")) def getText(self, wxh, node): sEncodedText = self.xpathToStr(node, self.xpContent, \"\") try: return eval('u\"\\\\u%04x\"'", "of the destination or None on error \"\"\" sPageTag = self.config.getPageTag() sPageNumberAttr =", "previous value if initialValue == None or initialValue == sAttrValue: #very special case:", "h=%s)\" % (self.xpX, self.xpY, self.xpW, self.xpH) return s def runXYWHI(self, node): \"\"\"get the", "wx sEncoding = \"utf-8\" def setEncoding(s): global sEncoding sEncoding = s class DecoSeparator:", "self.xpCtxt.xpathEval(xpExprArg)[0] sPythonExpr = \"(%s)(%s)\" % (sLambdaExpr, repr(sArg)) s = eval(sPythonExpr) else: s =", "16 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoText.__init__(self, cfg, sSurname, xpCtxt) self.base =", "/ 2 wxh.AddEllipse((x, -y), (iEllipseParam, -iEllipseParam), LineColor=sLineColor, LineWidth=5, FillStyle=\"Transparent\") self.prevX, self.prevY = x,", "os.path.exists(sFilePath): #maybe the image is in a folder with same name as XML", "jump to a node \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname,", "+= \"\\n--- Info: %s\" % sMsg if s == Deco._s_prev_xpath_error: # let's not", "certain XML node using WX \"\"\" import types, os from collections import defaultdict", "\"\"\" self.sSurname = sSurname self.xpMain = cfg.get(sSurname, \"xpath\") # a main XPath that", "xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize = cfg.get(sSurname, \"xpath_font_size\")", "= os.path.join(self.sImageFolder, sDir, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate except ValueError: pass if", "\"readingOrder {index:4;} structure {type:catch-word;}\" ) --> { 'readingOrder': [{ 'index':'4' }], 'structure':[{'type':'catch-word'}] }", "if not os.path.exists(sFilePath): #maybe the image is in a folder with same name", "sSurname, xpCtxt) self.xpX_Inc = cfg.get(sSurname, \"xpath_x_incr\") #to shift the text self.xpY_Inc = cfg.get(sSurname,", "cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname,", "-iEllipseParam), LineColor=sLineColor, LineWidth=5, FillStyle=\"Transparent\") self.prevX, self.prevY = x, y return lo class DecoLine(Deco):", "and return a dictionary of list of dictionary Example: parseCustomAttr( \"readingOrder {index:4;} structure", "self._node = None def __str__(self): s = Deco.__str__(self) s += \"+(x=%s y=%s w=%s", "lsKeyVal: if not sKeyVal.strip(): continue #empty try: sKey, sVal = sKeyVal.split(':') except Exception:", "initialValue == sAttrValue: #very special case: when an attr was set, then saved,", "self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xp_xTo", "cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize = cfg.get(sSurname, \"xpath_font_size\") self.xpFontColor =", "Deco.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions that let uis find", "custom attribute contains data in a CSS style syntax. We parse this syntax", "= None, None, None, None except: pass return number,x,y,w,h class DecoClickableRectangleJumpToPage(DecoBBXYWH): \"\"\"A rectangle", "self._node != node: self._x = self.xpathToInt(node, self.xpX, 1) self._y = self.xpathToInt(node, self.xpY, 1)", "FillColor=sFillColor, FillStyle=sFillStyle) lo.append(obj) return lo class DecoTextBox(DecoRectangle): \"\"\"A text within a bounding box", "try: if h > 0: obj = wxh.AddScaledBitmap(img, (x,-y), h) else: obj =", "= self.xpathToInt(node, self.xpLineWidth, 1) #draw a line obj = wxh.AddLine( [(self._x1, -self._y1), (self._x2,", "self.xpY, self.xpW, self.xpH) return s def runXYWHI(self, node): \"\"\"get the X,Y values for", "lChunk: #things like \"a {x:1\" chunk = chunk.strip() if not chunk: continue try:", "node) if lCoord: lCoord.append(lCoord[0]) return lCoord class DecoTextPolyLine(DecoPolyLine, DecoText): \"\"\"A polyline that closes", "cfg.get(sSurname, \"xpath_y\") self.xpW, self.xpH = cfg.get(sSurname, \"xpath_w\"), cfg.get(sSurname, \"xpath_h\") self.xpInc = cfg.get(sSurname, \"xpath_incr\")", "sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") for (_a, x, y, r) in self._laxyr: #draw", "WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) #add the text itself txt =", "a list of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) #add the", "+= \"+(coords=%s)\" % (self.xpCoords) return s def draw(self, wxh, node): \"\"\"draw itself using", "(self.xpCoords) return s def getArea_and_CenterOfMass(self, lXY): \"\"\" https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone return A, (Xg, Yg) which", "sLineColor = self.xpathToStr(node, self.xpLineColorSlctd, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidthSlctd, 1) sFillColor = self.xpathToStr(node,", "False def draw(self, wxh, node): \"\"\"draw itself using the wx handle return a", "self.xpDfltX2, iLARGENEG) xpY2 = self.xpathToStr(node, self.xpEvalY2, '\"\"') self._y2 = self.xpathToInt(node, xpY2, iLARGENEG, False)", "return self.xpCtxt.xpathEval(xpExpr) except Exception, e: self.xpathError(node, xpExpr, e, \"xpathEval return None\") return None", "expressions that let uis find x,y,w,h from a selected node self.xpX, self.xpY =", "\"xpath_LineWidth_Selected\") self.xpFillColorSlctd = cfg.get(sSurname, \"xpath_FillColor_Selected\") self.xpFillStyleSlctd = cfg.get(sSurname, \"xpath_FillStyle_Selected\") def __str__(self): s =", "self.xp_yTo and self.xp_hTo and self.xp_wTo: x = self.xpathToInt(ndTo, self.xp_xTo, None) y = self.xpathToInt(ndTo,", "def __str__(self): s = Deco.__str__(self) s += \"+(x=%s y=%s w=%s h=%s)\" % (self.xpX,", "DecoClosedPolyLine(DecoPolyLine): \"\"\"A polyline that closes automatically the shape <NAME> - September 2016 \"\"\"", "h==None: x,y,w,h = None, None, None, None except: pass return number,x,y,w,h class DecoClickableRectangleJumpToPage(DecoBBXYWH):", "lY = [_y for _x,_y in ltXY] return (min(lX), max(lY)), (max(lX), min(lY)) class", "of the destination or None on error \"\"\" index,x,y,w,h = None,None,None,None,None sToPageNum =", "return a dictionary of list of dictionary Example: parseCustomAttr( \"readingOrder {index:4;} structure {type:catch-word;}\"", "sEncoding sEncoding = s class DecoSeparator: \"\"\" this is not properly a decoration", "list of dictionary Example: parseCustomAttr( \"readingOrder {index:4;} structure {type:catch-word;}\" ) --> { 'readingOrder':", "getDecoClass = classmethod(getDecoClass) def getSurname(self): return self.sSurname def getMainXPath(self): return self.xpMain def isEnabled(self):", "to the PageXML custom attribute \"\"\" @classmethod def parseCustomAttr(cls, s, bNoCase=True): \"\"\" The", "axis\") iFontSizeX = 8 iFontSizeY = 24 * abs(y2-y1) / Ey if sFit", "attr was set, then saved, re-clicking on it wil remove it. del node.attrib[sAttrName]", "\"xpath_background_color\") def draw(self, wxh, node): \"\"\" draw itself using the wx handle return", "and do proportional dc.SetFont(wx.Font(24, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") try: iFontSizeX", "# FillColor=sFillColor, # FillStyle=sFillStyle) lo.append(obj) \"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc =", "= ltXY[0] (x, _y1), (_x2, y) = self._coordList_to_BB(ltXY) obj = wxh.AddScaledText(txt, (x, -y+iFontSize/6),", "sMsg != Deco._s_prev_warning: logging.warning(sMsg) Deco._warning_count += 1 Deco._s_prev_warning = sMsg def toInt(cls, s):", "__init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth", "for font size of 24 and do proportional dc.SetFont(wx.Font(24, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex,", "selected node self.xpX, self.xpY = cfg.get(sSurname, \"xpath_x\"), cfg.get(sSurname, \"xpath_y\") self.xpW, self.xpH = cfg.get(sSurname,", "= self.xpathEval(node.doc.getroot(), '//*[@id=\"%s\"]'%sToId.strip()) if ln: #find the page number ndTo = nd =", "self.xpInc = cfg.get(sSurname, \"xpath_incr\") #to increase the BB width and height self._node =", "xprev, yprev = x, y if fA == 0.0: raise ValueError(\"surface == 0.0\")", "sSurname is the surname of the decoration and the section name in the", ", LineColor=sLineColor) lo.append(obj) return lo class DecoREAD(Deco): \"\"\" READ PageXml has a special", "'structure':[{'type':'catch-word'}] } \"\"\" dic = defaultdict(list) s = s.strip() lChunk = s.split('}') if", "def xpathToStr(self, node, xpExpr, sDefault, bShowError=True): \"\"\"The given XPath expression should return a", "for n in node.xpathEval(self.xpX): print n.serialize() iLARGENEG = -9999 lo = Deco.draw(self, wxh,", "SIENNA YELLOW ORANGE RED GREEN\" FillColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" enabled=1 \"\"\"", "a list of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc =", "iFontSize, Ex, Ey def draw(self, wxh, node): \"\"\"draw itself using the wx handle", "= classmethod(toInt) def xpathToInt(self, node, xpExpr, iDefault=0, bShowError=True): \"\"\"The given XPath expression should", "\"\"\"An image \"\"\" # in case the use wants to specify it via", "iFontSizeY) dc.SetFont(wx.Font(iFontSize, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") del dc return iFontSize,", "* (xprev+x) ySum += iTerm * (yprev+y) xprev, yprev = x, y if", "\"xpath_lxy\") def _getCoordList(self, node): sCoords = self.xpathToStr(node, self.xpCoords, \"\") if not sCoords: if", "try: return eval('u\"\\\\u%04x\"' % int(sEncodedText, self.base)) except ValueError: logging.error(\"DecoUnicodeChar: ERROR: base=%d code=%s\"%(self.base, sEncodedText))", "xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self)", "None print \"DecoClusterCircle lsLineColor = \", self.lsLineColor print \"DecoClusterCircle lsFillColor = \", self.lsFillColor", "self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) #double evaluation, and a default value", "obj = wxh.AddScaledBitmap(img, (x,-y), h) lo.append(obj) except Exception, e: self.warning(\"DecoImageBox ERROR: File %s:", "self.xpCluster = cfg.get(sSurname, \"xpath\") self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpRadius = cfg.get(sSurname, \"xpath_radius\") self.xpLineWidth", "XPath ERROR on class %s\"%self.__class__ s += \"\\n--- xpath=%s\" % xpExpr s +=", "except KeyError: pass except KeyError: pass return lo class DecoPolyLine(DecoREAD): \"\"\"A polyline along", "= \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return s def draw(self, wxh, node):", "self.xpFillStyle, \"Solid\") obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo", "wxh.AddCircle((x, -y), r, LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) # obj = wxh.AddRectangle((x, -y), (20,", "WX objects\"\"\" lo = DecoRectangle.draw(self, wxh, node) #add the text itself txt =", "str(e))) return lo class DecoOrder(DecoBBXYWH): \"\"\"Show the order with lines \"\"\" def __init__(self,", "(_x2, y) = self._coordList_to_BB(ltXY) obj = wxh.AddScaledText(txt, (x, -y+iFontSize/6), Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE ,", "if os.path.exists(sCandidate): sFilePath = sCandidate print(sFilePath) break if not os.path.exists(sFilePath): # maybe we", "iLARGENEG, False) #do not show any error if self._x2 == iLARGENEG: self._x2 =", "WX objects\"\"\" lo = [] #add the text itself txt = self.getText(wxh, node)", "defined by X,Y for its top-left corner and width/height. xpX, xpY, xpW, xpH", "types.ListType: try: s = s[0].text except AttributeError: s = s[0] return s except", "of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sAttrName", "xpExpr s += \"\\n--- Python Exception=%s\" % str(eExcpt) if sMsg: s += \"\\n---", "sFilePath: try: img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) obj = wxh.AddScaledBitmap(img, (x,-y), h) lo.append(obj) except", "x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: if self.sImageFolder: sCandidate", "DecoREAD.draw(self, wxh, node) if self._node != node: self._lxy = self._getCoordList(node) self._node = node", "return s except Exception, e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToStr return %s", "Item-name {offset:0; length:11;} Item-price {offset:12; length:2;}\"> <Coords points=\"985,390 1505,390 1505,440 985,440\"/> <Baseline points=\"985,435", "#find the page number ndTo = nd = ln[0] #while nd and nd.name", "node): lCoord = DecoPolyLine._getCoordList(self, node) if lCoord: lCoord.append(lCoord[0]) return lCoord class DecoTextPolyLine(DecoPolyLine, DecoText):", "compute font size along X axis\") iFontSizeX = 8 iFontSizeY = 24 *", "and put them in cache\"\"\" if self._node != node: self._x = self.xpathToInt(node, self.xpX,", "self.xpFillStyle, \"Solid\") for (_a, x, y, r) in self._laxyr: #draw a circle sFillColor", "destination or None on error \"\"\" sPageTag = self.config.getPageTag() sPageNumberAttr = self.config.getPageNumberAttr() number", "with same name as XML file? (Transkribus style) sUrl = node.getroottree().docinfo.URL.decode('utf-8') # py2", "\"#000000\") # Position and computation of font size ltXY = self._getCoordList(node) iFontSize, Ex,", "it \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef =", "w==None or h==None: x,y,w,h = None, None, None, None except: pass return number,x,y,w,h", "= \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def isActionable(self): return True def draw(self,", "[TextLine] type=DecoPolyLine xpath=.//TextLine/Coords xpath_lxy=@points xpath_LineColor=\"RED\" xpath_FillStyle=\"Solid\" <NAME> - March 2016 \"\"\" def __init__(self,", "\"\"\" s = \"do nothing\" sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue =", "self.bInit = True iEllipseParam = min(w,h) / 2 wxh.AddEllipse((x, -y), (iEllipseParam, -iEllipseParam), LineColor=sLineColor,", "an XPath context \"\"\" self.sSurname = sSurname self.xpMain = cfg.get(sSurname, \"xpath\") # a", "using the wx handle return a list of created WX objects\"\"\" DecoClusterCircle.count =", "xpH are scalar XPath expressions to get the associated x,y,w,h values from the", "box around it \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt)", "a subfolder ? # e.g. \"S_Aicha_an_der_Donau_004-03_0005.jpg\" is in folder \"S_Aicha_an_der_Donau_004-03\" try: sDir =", "= cfg.get(sSurname, \"xpath_font_color\") self.xpFit = cfg.get(sSurname, \"xpath_fit_text_size\").lower() def __str__(self): s = \"%s=\"%self.__class__ return", "Position='bl' , Color=sFontColor , LineColor=sLineColor , BackgroundColor=sBackgroundColor) lo.append(obj) except KeyError: pass except KeyError:", "area and the coordinates (float) of the center of mass of the polygon", "expression should return an int on the given node. The XPath expression should", "(20, 20), # LineWidth=iLineWidth, # LineColor=sLineColor, # FillColor=sFillColor, # FillStyle=sFillStyle) lo.append(obj) \"\"\" lo", "show any error if self._y2 == iLARGENEG: self._y2 = self.xpathToInt(node, self.xpDfltY2, iLARGENEG) self._node", "READ PageXml has a special way to encode coordinates. like: <Coords points=\"985,390 1505,390", "lo = [] #add the text itself txt = self.getText(wxh, node) sFontColor =", "max(0, int(nd.prop(\"number\")) - 1) number = max(0, self.xpathToInt(nd, sPageNumberAttr, 1, True) - 1)", "y, w, h \"\"\" Deco.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions", "s = s[0].text except AttributeError: s = s[0] return s except Exception, e:", "self._laxyr = [] #need to go thru each item ndPage = node.xpath(\"ancestor::*[local-name()='Page']\")[0] sIds", "#must be a lambda assert xpExpr[:8] == \"|lambda \", \"Invalid lambda expression %s\"%xpExpr", "Yg) which are the area and the coordinates (float) of the center of", "= cfg.get(sSurname, \"xpath_font_size\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__ s", "cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") #the following expression must be evaluated twice self.xpEvalX2, self.xpEvalY2", "cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpCoords = cfg.get(sSurname, \"xpath_lxy\") def _getCoordList(self,", "return lo def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class READ_custom: \"\"\"", "self.config.getPageNumberAttr() number = None x,y,w,h = None, None, None, None bbHighlight = None", "isActionable(self): return False def setXPathContext(self, xpCtxt): self.xpCtxt = xpCtxt def xpathError(self, node, xpExpr,", "e: self.xpathError(node, xpExpr, e, \"xpathEval return None\") return None def beginPage(self, node): \"\"\"called", "the config file! xpCtxt is an XPath context \"\"\" self.sSurname = sSurname def", "values from the selected nodes \"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg", "sNode = etree.tostring(node) except: sNode = str(node) if len(sNode) > iMaxLen: sNode =", "# py2 ... for sPrefix in [\"file://\", \"file:/\"]: if sUrl[0:len(sPrefix)] == sPrefix: sLocalDir", "main XPath that select nodes to be decorated in this way self.xpCtxt =", "= \"\" Deco._prev_xpath_error_count = 0 iMaxLen = 200 # to truncate the node", "is an XPath context \"\"\" self.sSurname = sSurname def __str__(self): return \"--------\" def", "self._node = None self._laxyr = None print \"DecoClusterCircle lsLineColor = \", self.lsLineColor print", "\"xpath_y1\") self.xpX2, self.xpY2 = cfg.get(sSurname, \"xpath_x2\"), cfg.get(sSurname, \"xpath_y2\") #now get the xpath expressions", "\"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrToPageNumber = cfg.get(sSurname, \"xpath_ToPageNumber\") def __str__(self): s =", "self.getText(wxh, node) iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc", "xpExpr[0] == \"|\": #must be a lambda assert xpExpr[:8] == \"|lambda \", \"Invalid", "# print self.xpX # for n in node.xpathEval(self.xpX): print n.serialize() iLARGENEG = -9999", "Deco._s_prev_xpath_error: # let's not overload the console. return Deco._s_prev_xpath_error = s Deco._prev_xpath_error_count +=", "We assume the unicode index is given in a certain base, e.g. 10", "lxml import etree #import cStringIO import wx sEncoding = \"utf-8\" def setEncoding(s): global", "sAttrValue: sLineColor = self.xpathToStr(node, self.xpLineColorSlctd, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidthSlctd, 1) sFillColor =", "__init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def", "None on error \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) return self.xpCtxt.xpathEval(xpExpr) except", "point? if self.xp_xTo and self.xp_yTo and self.xp_hTo and self.xp_wTo: x = self.xpathToInt(ndTo, self.xp_xTo,", "bad: '%s' -> '%s'\" % ( self.xpCoords, sCoords)) raise e return ltXY def", "self.xpLineWidth, 1) sFillColor = self.xpathToStr(node, self.xpFillColor, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") obj", "xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpCoords = cfg.get(sSurname, \"xpath_lxy\") def _getCoordList(self, node): sCoords", "not chunk: continue try: sNames, sValues = chunk.split('{') #things like: (\"a,b\", \"x:1 ;", "return (x1, y1), (x2, y2) \"\"\" lX = [_x for _x,_y in ltXY]", "surname of the decoration and the section name in the config file! xpCtxt", "corner and width/height. xpX, xpY, xpW, xpH are scalar XPath expressions to get", "#empty try: sKey, sVal = sKeyVal.split(':') except Exception: raise ValueError(\"Expected a comma-separated string,", "rather a separator of decoration in the toolbar \"\"\" def __init__(self, cfg, sSurname,", "= self.xpathToStr(node, self.xpLineColor, \"#000000\") sBackgroundColor = self.xpathToStr(node, self.xpBackgroundColor, \"#000000\") # Position and computation", "self.xpX, self.xpY = cfg.get(sSurname, \"xpath_x\"), cfg.get(sSurname, \"xpath_y\") self.xpW, self.xpH = cfg.get(sSurname, \"xpath_w\"), cfg.get(sSurname,", "= cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return s", "None) if sToId: ln = self.xpathEval(node.doc.getroot(), '//*[@id=\"%s\"]'%sToId.strip()) if ln: #find the page number", "default value\"%sDefault) return sDefault def xpathEval(self, node, xpExpr): \"\"\" evaluate the xpath expression", "s def beginPage(self, node): \"\"\"called before any sequnce of draw for a given", "self.xpLineColorSlctd, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidthSlctd, 1) sFillColor = self.xpathToStr(node, self.xpFillColorSlctd, \"#000000\") sFillStyle", "the coordinates (float) of the center of mass of the polygon \"\"\" if", "draw(self, wxh, node): lo = Deco.draw(self, wxh, node) if self._node != node: self._lxy", "(xg, yg))) return fA, (xg, yg) def draw(self, wxh, node): \"\"\"draw itself using", "max(lY)), (max(lX), min(lY)) class DecoREADTextLine(DecoREAD): \"\"\"A TextLine as defined by the PageXml format", "%s as default value\"%sDefault) return sDefault def xpathEval(self, node, xpExpr): \"\"\" evaluate the", "self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: if self.sImageFolder: sCandidate = os.path.join(self.sImageFolder, sFilePath) if os.path.exists(sCandidate):", "- March 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt)", "xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") #the following expression must be", "\"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self._node = None def __str__(self): s = \"%s=\"%self.__class__", "runXYWHI(self, node): \"\"\"get the X,Y values for a node and put them in", "assume the unicode index is given in a certain base, e.g. 10 or", "iMaxLC] else: sLineColor = sFillColor obj = wxh.AddCircle((x, -y), r, LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor,", "+= \"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpEvalX2, self.xpEvalY2) return s def", "nd.parent while nd and nd.name != sPageTag: nd = nd.parent try: #number =", "print \"DecoClusterCircle lsLineColor = \", self.lsLineColor print \"DecoClusterCircle lsFillColor = \", self.lsFillColor def", "sSurname, xpCtxt): \"\"\" cfg is a configuration object sSurname is the surname of", "self._node = node if self._laxyr: iMaxFC = len(self.lsFillColor) iMaxLC = len(self.lsLineColor) if False:", "the polygon and the extent of the 'x' character for this font size", "= self.xpathToInt(node, self.xpX, 1) self._y = self.xpathToInt(node, self.xpY, 1) self._w = self.xpathToInt(node, self.xpW,", "self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"BLACK\") x, y = int(x + w/2.0), int(y", "lambda assert xpExpr[:8] == \"|lambda \", \"Invalid lambda expression %s\"%xpExpr sStartEmpty, sLambdaExpr, xpExprArg,", "lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\")", "try: ltXY = [] for _sPair in sCoords.split(' '): (sx, sy) = _sPair.split(',')", "objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) #add the text itself txt = self.getText(wxh,", "#do not show any error if self._y2 == iLARGENEG: self._y2 = self.xpathToInt(node, self.xpDfltY2,", "an XPath context \"\"\" self.sSurname = sSurname def __str__(self): return \"--------\" def isSeparator(self):", "cfg, sSurname, xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") self.xpX2, self.xpY2 =", "Exception: raise ValueError(\"Expected a comma-separated string, got '%s'\"%sKeyVal) sKey = sKey.strip().lower() if bNoCase", "self._w = self.xpathToInt(node, self.xpW, 1) self._h = self.xpathToInt(node, self.xpH, 1) self._inc = self.xpathToInt(node,", "# if sMsg != Deco._s_prev_warning and Deco._warning_count < 1000: if sMsg != Deco._s_prev_warning:", "except ValueError: pass if not os.path.exists(sFilePath): #maybe the image is in a folder", "beginPage(self, node): \"\"\"called before any sequnce of draw for a given page\"\"\" self.bInit", "self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xp_xTo = cfg.get(sSurname, \"xpath_xTo\") self.xp_yTo = cfg.get(sSurname, \"xpath_yTo\") self.xp_wTo", "LineColor=sLineColor) lo.append(obj) return lo class DecoREAD(Deco): \"\"\" READ PageXml has a special way", "and sAttrValue != None: if node.prop(sAttrName) == sAttrValue: sLineColor = self.xpathToStr(node, self.xpLineColorSlctd, \"#000000\")", "presence/absence of the attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname,", "in node.xpathEval(self.xpX): print n.serialize() iLARGENEG = -9999 lo = Deco.draw(self, wxh, node) if", "self.dInitialValue[node] except KeyError: initialValue = node.prop(sAttrName) #first time self.dInitialValue[node] = initialValue if node.get(sAttrName)", "= \"Removal of @%s\"%sAttrName else: node.set(sAttrName, initialValue) s = '@%s := \"%s\"'%(sAttrName,initialValue) else:", "rectangle clicking on it jump to a page \"\"\" def __init__(self, cfg, sSurname,", "= self.xpathToInt(ndTo, self.xp_hTo, None) if x==None or y==None or w==None or h==None: x,y,w,h", "None: try: initialValue = self.dInitialValue[node] except KeyError: initialValue = node.prop(sAttrName) #first time self.dInitialValue[node]", "- 1) #maybe we can also indicate the precise arrival point? if self.xp_xTo", "self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") #cached values self._node = None", "created WX objects\"\"\" DecoClusterCircle.count = DecoClusterCircle.count + 1 lo = DecoREAD.draw(self, wxh, node)", "wxh, node) #add the text itself txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize =", "\"S_Aicha_an_der_Donau_004-03_0005.jpg\" is in folder \"S_Aicha_an_der_Donau_004-03\" try: sDir = sFilePath[:sFilePath.rindex(\"_\")] sCandidate = os.path.join(self.sImageFolder, sDir,", "(iEllipseParam, -iEllipseParam), LineColor=sLineColor, LineWidth=5, FillStyle=\"Transparent\") self.prevX, self.prevY = x, y return lo class", "is the surname of the decoration and the section name in the config", "sKeyVal.split(':') except Exception: raise ValueError(\"Expected a comma-separated string, got '%s'\"%sKeyVal) sKey = sKey.strip().lower()", "dicValForName[sKey] = sVal.strip() lName = sNames.split(',') for name in lName: name = name.strip().lower()", "area is undefined.\") fA = 0.0 xSum, ySum = 0, 0 xprev, yprev", "to specify it via the menu sImageFolder = None def __init__(self, cfg, sSurname,", "Exception, e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToStr return %s as default value\"%sDefault)", "self.xpathToInt(node, self.xpLineWidth, 1) for (x1, y1), (x2, y2) in zip(self._lxy, self._lxy[1:]): #draw a", "self._w, self._h, self._inc) class DecoRectangle(DecoBBXYWH): \"\"\"A rectangle \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "= s[0].text except AttributeError: s = s[0] #should be an attribute value return", "a bounding box (a rectangle) \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg,", "(x, y) , Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='bl' , Color=sFontColor , LineColor=sLineColor ,", "int on the given node. The XPath expression should return a scalar or", "def getText(self, wxh, node): sEncodedText = self.xpathToStr(node, self.xpContent, \"\") try: return eval('u\"\\\\u%04x\"' %", "get the xpath expressions that let us find the rectangle line and fill", "name = name.strip().lower() if bNoCase else name.strip() dic[name].append(dicValForName) return dic class DecoREADTextLine_custom_offset(DecoREADTextLine, READ_custom):", "given node. The XPath expression should return a scalar or a one-node nodeset", "eval(sPythonExpr) else: s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try: s = s[0].text", "int(x + w/2.0), int(y + h/2.0) if self.bInit: #draw a line iLineWidth =", "\"Removal of @%s\"%sAttrName else: node.set(sAttrName, sAttrValue) s = '@%s := \"%s\"'%(sAttrName,sAttrValue) return s", "= sEnabled in ['1', 'yes', 'true'] def isSeparator(cls): return False isSeparator = classmethod(isSeparator)", "for a given page\"\"\" pass def endPage(self, node): \"\"\"called before any sequnce of", "the text itself x, y = self._lxy[0] x_inc = self.xpathToInt(node, self.xpX_Inc, 0, False)", "class DecoTextBox(DecoRectangle): \"\"\"A text within a bounding box (a rectangle) \"\"\" def __init__(self,", "ndPage = node.xpath(\"ancestor::*[local-name()='Page']\")[0] sIds = self.xpathEval(node, self.xpContent)[0] for sId in sIds.split(): l =", "-y)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) else: self.bInit = True iEllipseParam = min(w,h)", "except Exception, e: self.xpathError(node, xpExpr, e, \"xpathEval return None\") return None def beginPage(self,", "= -9999 lo = Deco.draw(self, wxh, node) if self._node != node: self._x1 =", "self.xpLineWidthSlctd = cfg.get(sSurname, \"xpath_LineWidth_Selected\") self.xpFillColorSlctd = cfg.get(sSurname, \"xpath_FillColor_Selected\") self.xpFillStyleSlctd = cfg.get(sSurname, \"xpath_FillStyle_Selected\") def", "print(sFilePath) break if not os.path.exists(sFilePath): # maybe we have some pattern?? lCandidate =", "= int(x + w/2.0), int(y + h/2.0) if self.bInit: #draw a line iLineWidth", "node): \"\"\" return the page number of the destination or None on error", "x,y,w,h from a selected node self.xpX, self.xpY = cfg.get(sSurname, \"xpath_x\"), cfg.get(sSurname, \"xpath_y\") self.xpW,", "number,x,y,w,h class DecoClickableRectangleJumpToPage(DecoBBXYWH): \"\"\"A rectangle clicking on it jump to a page \"\"\"", "cfg.get(sSurname, \"xpath_content\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") self.xpFit = cfg.get(sSurname, \"xpath_fit_text_size\").lower() def __str__(self): s", "self.bInit: #draw a line iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) obj = wxh.AddLine( [(self.prevX,", "if sUrl[0:len(sPrefix)] == sPrefix: sLocalDir = os.path.dirname(sUrl[len(sPrefix):]) sDir,_ = os.path.splitext(os.path.basename(sUrl)) sCandidate = os.path.abspath(os.path.join(sLocalDir,", "else: obj = wxh.AddScaledBitmap(img, (x,-y), img.GetHeight()) lo.append(obj) except Exception, e: self.warning(\"DecoImage ERROR: File", "\"\" Deco._prev_xpath_error_count = 0 iMaxLen = 200 # to truncate the node serialization", "self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") def", "= s[0] #should be an attribute value return Deco.toInt(s) except Exception, e: if", "\"xpath_LineColor\") self.xpBackgroundColor = cfg.get(sSurname, \"xpath_background_color\") def draw(self, wxh, node): \"\"\" draw itself using", "syntax. We parse this syntax here and return a dictionary of list of", "self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y+inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj)", "config file! xpCtxt is an XPath context \"\"\" self.sSurname = sSurname def __str__(self):", "in '%s'\"%chunk) #the dictionary for that name dicValForName = dict() lsKeyVal = sValues.split(';')", "wxh, node) if self._node != node: self._laxyr = [] #need to go thru", "str(eExcpt) if sMsg: s += \"\\n--- Info: %s\" % sMsg if s ==", "== \"|\": #must be a lambda assert xpExpr[:8] == \"|lambda \", \"Invalid lambda", "FillStyle=sFillStyle) lo = [obj] + lo return lo def act(self, obj, node): \"\"\"", "def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\")", "self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrName", "self.parseCustomAttr(node.get(\"custom\"), bNoCase=True) try: x0, y0 = ltXY[0] _ldLabel = dCustom[self.xpathToStr(node, self.xpLabel, \"\").lower()] for", "glob import logging import random from lxml import etree #import cStringIO import wx", "(a rectangle) \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpContent", "w, h \"\"\" Deco.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions that", "del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName, initialValue) s = '@%s", "decorations, return the list of wx created objects\"\"\" return [] class DecoBBXYWH(Deco): \"\"\"A", "for chunk in lChunk: #things like \"a {x:1\" chunk = chunk.strip() if not", "SIENNA YELLOW ORANGE RED GREEN\" enabled=1 \"\"\" count = 0 def __init__(self, cfg,", "attribute value \"\"\" s = \"do nothing\" sAttrName = self.xpathToStr(node, self.xpAttrName , None)", "Deco.toInt(s) except Exception, e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToInt return %d as", "the file is in a subfolder ? # e.g. \"S_Aicha_an_der_Donau_004-03_0005.jpg\" is in folder", "self.xpRadius, 1) self._laxyr.append( (fA, xg, yg, r) ) self._node = node if self._laxyr:", "\"xpath\") self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpRadius = cfg.get(sSurname, \"xpath_radius\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\")", "act(self, obj, node): \"\"\" return the page number of the destination or None", "draw for a given page\"\"\" pass def endPage(self, node): \"\"\"called before any sequnce", "\"\"\" index,x,y,w,h = None,None,None,None,None sToPageNum = self.xpathToStr(node, self.xpAttrToPageNumber , None) if sToPageNum: index", "!= node: self._x1 = self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) #double", "enabled=1 \"\"\" count = 0 def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname,", "+ 1 lo = DecoREAD.draw(self, wxh, node) if self._node != node: self._laxyr =", "\"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return s def draw(self,", "= x, y if fA == 0.0: raise ValueError(\"surface == 0.0\") fA =", "as XML file? (Transkribus style) sUrl = node.getroottree().docinfo.URL.decode('utf-8') # py2 ... for sPrefix", "\"Solid\") obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo =", "None def beginPage(self, node): \"\"\"called before any sequnce of draw for a given", "= self.xpathToStr(node, self.xpFontColor, 'BLACK') # Position and computation of font size ltXY =", "= self.xpathToInt(node, xpX2, iLARGENEG, False) #do not show any error if self._x2 ==", "= self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) self._x2 = self.xpathToInt(node, self.xpX2,", "sequnce of draw for a given page\"\"\" pass def endPage(self, node): \"\"\"called before", "_sPair.split(',') ltXY.append((Deco.toInt(sx), Deco.toInt(sy))) except Exception as e: logging.error(\"ERROR: polyline coords are bad: '%s'", "return lo def act(self, obj, node): \"\"\" Toggle the attribute value \"\"\" s", "list of created WX objects\"\"\" lo = [] #add the text itself txt", "wx.BITMAP_TYPE_ANY) try: if h > 0: obj = wxh.AddScaledBitmap(img, (x,-y), h) else: obj", "__init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"),", "the area and the coordinates (float) of the center of mass of the", "node if self._laxyr: iMaxFC = len(self.lsFillColor) iMaxLC = len(self.lsLineColor) if False: Nf =", "ltXY, txt, Family=wx.FONTFAMILY_TELETYPE) # x, y = ltXY[0] (x, _y1), (_x2, y) =", "self._node != node: self._lxy = self._getCoordList(node) self._node = node #lo = DecoClosedPolyLine.draw(self, wxh,", "cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.lsLineColor = cfg.get(sSurname, \"LineColors\").split() self.lsFillColor = cfg.get(sSurname,", "\"(Surname=%s xpath==%s)\" % (self.sSurname, self.xpMain) def getDecoClass(cls, sClass): \"\"\"given a decoration type, return", "return %s as default value\"%sDefault) return sDefault def xpathEval(self, node, xpExpr): \"\"\" evaluate", "FillColor=sFillColor, # FillStyle=sFillStyle) lo.append(obj) \"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node)", "WX \"\"\" import types, os from collections import defaultdict import glob import logging", "#to shift the text self.xpY_Inc = cfg.get(sSurname, \"xpath_y_incr\") #to shift the text def", "None or initialValue == sAttrValue: #very special case: when an attr was set,", "= cfg.get(sSurname, \"xpath_content\") self.xpFontSize = cfg.get(sSurname, \"xpath_font_size\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") def __str__(self):", "s += \"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpEvalX2, self.xpEvalY2) return s", "if sMsg != Deco._s_prev_warning and Deco._warning_count < 1000: if sMsg != Deco._s_prev_warning: logging.warning(sMsg)", "s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def isActionable(self): return True def", "ValueError(\"surface == 0.0\") fA = fA / 2 xg, yg = xSum/6/fA, ySum/6/fA", "= DecoClusterCircle.count + 1 lo = DecoREAD.draw(self, wxh, node) if self._node != node:", "#things like \"a {x:1\" chunk = chunk.strip() if not chunk: continue try: sNames,", "None) sAttrValue = self.xpathToStr(node, self.xpAttrValue, None) if sAttrName and sAttrValue != None: try:", "the destination or None on error \"\"\" sPageTag = self.config.getPageTag() sPageNumberAttr = self.config.getPageNumberAttr()", "lo class DecoText(DecoBBXYWH): \"\"\"A text \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg,", "lo = DecoREAD.draw(self, wxh, node) if self._node != node: self._laxyr = [] #need", "DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize = cfg.get(sSurname, \"xpath_font_size\") self.xpFontColor", "TextLine as defined by the PageXml format of the READ project <TextLine id=\"line_1551946877389_284\"", "x2,y2 .... xn,yn Example of config: [TextLine] type=DecoPolyLine xpath=.//TextLine/Coords xpath_lxy=@points xpath_LineColor=\"RED\" xpath_FillStyle=\"Solid\" <NAME>", "def warning(self, sMsg): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_warning except AttributeError: Deco._s_prev_warning =", "wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) \"\"\" return lo class DecoLink(Deco):", "self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrName = cfg.get(sSurname, \"xpath_AttrName\") self.xpAttrValue = cfg.get(sSurname, \"xpath_AttrValue\") self.dInitialValue", "xpath_LineWidth=\"1\" xpath_FillStyle=\"Transparent\" LineColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" FillColors=\"BLUE SIENNA YELLOW ORANGE RED", "node.prop(sAttrName) == sAttrValue: sLineColor = self.xpathToStr(node, self.xpLineColorSlctd, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidthSlctd, 1)", "= self.xpathToInt(node, self.xpLineWidth, 1) obj = wxh.AddLine( [(self.prevX, -self.prevY), (x, -y)] , LineWidth=iLineWidth", "polygon \"\"\" if len(lXY) < 2: raise ValueError(\"Only one point: polygon area is", "!= node: self._x = self.xpathToInt(node, self.xpX, 1) self._y = self.xpathToInt(node, self.xpY, 1) self._w", "DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) DecoText .__init__(self, cfg, sSurname, xpCtxt) self.xpX_Inc = cfg.get(sSurname, \"xpath_x_incr\")", "sequnce of draw for a given page\"\"\" self.bInit = False def draw(self, wxh,", "iMaxFC = len(self.lsFillColor) iMaxLC = len(self.lsLineColor) if False: Nf = DecoClusterCircle.count Nl =", "of font size ltXY = self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt", "def __init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) DecoText .__init__(self, cfg, sSurname,", "y0 = ltXY[0] _ldLabel = dCustom[self.xpathToStr(node, self.xpLabel, \"\").lower()] for _dLabel in _ldLabel: try:", "March 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) #now", "return b def isActionable(self): return False def setXPathContext(self, xpCtxt): self.xpCtxt = xpCtxt def", "of created WX objects\"\"\" lo = [] #add the image itself x,y,w,h,inc =", "xSum, ySum = 0, 0 xprev, yprev = lXY[-1] for x, y in", "self.xpathToStr(node, self.xpAttrName , None) sAttrValue = self.xpathToStr(node, self.xpAttrValue, None) if sAttrName and sAttrValue", "return lo class DecoLine(Deco): \"\"\"A line from x1,y1 to x2,y2 \"\"\" def __init__(self,", "self.warning(\"DecoImage ERROR: File %s: %s\"%(sFilePath, str(e))) return lo class DecoOrder(DecoBBXYWH): \"\"\"Show the order", "as e: logging.error(\"ERROR: polyline coords are bad: '%s' -> '%s'\" % ( self.xpCoords,", "READ_custom: \"\"\" Everything related to the PageXML custom attribute \"\"\" @classmethod def parseCustomAttr(cls,", "the wx handle return a list of created WX objects \"\"\" lo =", "item ndPage = node.xpath(\"ancestor::*[local-name()='Page']\")[0] sIds = self.xpathEval(node, self.xpContent)[0] for sId in sIds.split(): l", "\"\\n\" logging.warning(s) def warning(self, sMsg): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_warning except AttributeError:", "= 24 * abs(y2-y1) / Ey if sFit == \"x\": iFontSize = iFontSizeX", "node.serialize() # print self.xpX # for n in node.xpathEval(self.xpX): print n.serialize() lo =", "return lo class DecoClickableRectangleSetAttr(DecoBBXYWH): \"\"\"A rectangle clicking on it add/remove an attribute the", "= None sToId = self.xpathToStr(node, self.xpAttrToId , None) if sToId: ln = self.xpathEval(node.doc.getroot(),", "#add the text itself x, y = self._lxy[0] x_inc = self.xpathToInt(node, self.xpX_Inc, 0,", "> iMaxLen: sNode = sNode[:iMaxLen] + \"...\" s += \"\\n--- XML node =", "sSurname, xpCtxt) #now get the xpath expressions that let uis find x,y,w,h from", "xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self): s =", "or None on error \"\"\" index,x,y,w,h = None,None,None,None,None sToPageNum = self.xpathToStr(node, self.xpAttrToPageNumber ,", "extent of the 'x' character for this font size return iFontSize, ExtentX, ExtentY", "and self.xp_yTo and self.xp_hTo and self.xp_wTo: x = self.xpathToInt(ndTo, self.xp_xTo, None) y =", "xpExpr, sDefault, bShowError=True): \"\"\"The given XPath expression should return a string on the", "pass return number,x,y,w,h class DecoClickableRectangleJumpToPage(DecoBBXYWH): \"\"\"A rectangle clicking on it jump to a", "and Deco._warning_count < 1000: if sMsg != Deco._s_prev_warning: logging.warning(sMsg) Deco._warning_count += 1 Deco._s_prev_warning", "# s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) if xpExpr[0] == \"|\": #must be a lambda", "= cfg.get(sSurname, \"xpath_radius\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.lsLineColor =", "class DecoBBXYWH(Deco): \"\"\"A decoration with a bounding box defined by X,Y for its", "= fA / 2 xg, yg = xSum/6/fA, ySum/6/fA if fA <0: return", "def __str__(self): s = \"%s=\"%self.__class__ return s def _getFontSize(self, node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE):", "sCandidate print(sFilePath) break if not os.path.exists(sFilePath): # maybe we have some pattern?? lCandidate", "using the wx handle return a list of created WX objects\"\"\" # print", "iOffset = int(_dLabel[\"offset\"]) iLength = int(_dLabel[\"length\"]) x = x0 + Ex * iOffset", "wxh.AddScaledTextBox(txt, (x, -y-h/2.0), Size=iFontSize, Family=wx.ROMAN, Position='cl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo def", "pass if not os.path.exists(sFilePath): #maybe the image is in a folder with same", "self._h = self.xpathToInt(node, self.xpH, 1) self._inc = self.xpathToInt(node, self.xpInc, 0) self._x,self._y = self._x-self._inc,", "the section name in the config file! xpCtxt is an XPath context \"\"\"", "setXPathContext(self, xpCtxt): self.xpCtxt = xpCtxt def xpathError(self, node, xpExpr, eExcpt, sMsg=\"\"): \"\"\"report an", "self.xpathToInt(node, self.xpY, 1) self._w = self.xpathToInt(node, self.xpW, 1) self._h = self.xpathToInt(node, self.xpH, 1)", "= iFontSizeY else: iFontSize = min(iFontSizeX, iFontSizeY) dc.SetFont(wx.Font(iFontSize, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey", "\", \"Invalid lambda expression %s\"%xpExpr sStartEmpty, sLambdaExpr, xpExprArg, sEndEmpty = xpExpr.split('|') assert sEndEmpty", "e, \"xpathToStr return %s as default value\"%sDefault) return sDefault def xpathEval(self, node, xpExpr):", "txt, Family=wx.FONTFAMILY_TELETYPE): \"\"\" compute the font size so as to fit the polygon", "s def isActionable(self): return True def draw(self, wxh, node): \"\"\"draw itself using the", "dic class DecoREADTextLine_custom_offset(DecoREADTextLine, READ_custom): \"\"\" Here we show the annotation by offset found", "node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName, initialValue) s = '@%s :=", "\"xpath_w\"), cfg.get(sSurname, \"xpath_h\") self.xpInc = cfg.get(sSurname, \"xpath_incr\") #to increase the BB width and", "yg) def draw(self, wxh, node): \"\"\"draw itself using the wx handle return a", "= self.xpathToStr(node, self.xpFillStyle, \"Solid\") for (_a, x, y, r) in self._laxyr: #draw a", "= str(node) if len(sNode) > iMaxLen: sNode = sNode[:iMaxLen] + \"...\" s +=", "= DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sAttrName = self.xpathToStr(node, self.xpAttrName , None)", "ExtentY \"\"\" (x1, y1), (x2, y2) = self._coordList_to_BB(ltXY) sFit = self.xpathToStr(node, self.xpFit, 'xy',", "# compute for font size of 24 and do proportional dc.SetFont(wx.Font(24, Family, wx.FONTSTYLE_NORMAL,", "node) if self._node != node: self._lxy = self._getCoordList(node) self._node = node #lo =", "sPageTag = self.config.getPageTag() sPageNumberAttr = self.config.getPageNumberAttr() number = None x,y,w,h = None, None,", "return fA, (xg, yg) def draw(self, wxh, node): \"\"\"draw itself using the wx", "fA, (xg, yg) def draw(self, wxh, node): \"\"\"draw itself using the wx handle", "given page\"\"\" pass def endPage(self, node): \"\"\"called before any sequnce of draw for", "also indicate the precise arrival point? if self.xp_xTo and self.xp_yTo and self.xp_hTo and", "= None,None,None,None,None sToPageNum = self.xpathToStr(node, self.xpAttrToPageNumber , None) if sToPageNum: index = int(sToPageNum)", "= self.xpathToInt(node, self.xpInc, 0) self._x,self._y = self._x-self._inc, self._y-self._inc self._w,self._h = self._w+2*self._inc, self._h+2*self._inc self._node", "setEnabled(self, b=True): self.bEnabled = b return b def isActionable(self): return False def setXPathContext(self,", "\"FillColors\").split() #cached values self._node = None self._laxyr = None print \"DecoClusterCircle lsLineColor =", "xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\")", "\"\"\" Here we show the annotation by offset found in the custom attribute", "[(self._x1, -self._y1), (self._x2, -self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoClickableRectangleSetAttr(DecoBBXYWH):", "line and fill colors self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor", "nodes \"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a config file", "in a folder with same name as XML file? (Transkribus style) sUrl =", "self._lxy[0] x_inc = self.xpathToInt(node, self.xpX_Inc, 0, False) y_inc = self.xpathToInt(node, self.xpY_Inc, 0, False)", "is an XPath context \"\"\" self.sSurname = sSurname self.xpMain = cfg.get(sSurname, \"xpath\") #", "for _sPair in sCoords.split(' '): (sx, sy) = _sPair.split(',') ltXY.append((Deco.toInt(sx), Deco.toInt(sy))) except Exception", "(x1, y1), (x2, y2) \"\"\" lX = [_x for _x,_y in ltXY] lY", "return iFontSize, ExtentX, ExtentY \"\"\" (x1, y1), (x2, y2) = self._coordList_to_BB(ltXY) sFit =", "yprev*x fA += iTerm xSum += iTerm * (xprev+x) ySum += iTerm *", "\"xpathToInt return %d as default value\"%iDefault) return iDefault def xpathToStr(self, node, xpExpr, sDefault,", "+= \"\\n\" + \"-\"*60 + \"\\n\" logging.warning(s) def warning(self, sMsg): \"\"\"report an xpath", "= self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"BLACK\") x, y = int(x + w/2.0),", "/ 2 xg, yg = xSum/6/fA, ySum/6/fA if fA <0: return -fA, (xg,", "self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) #double evaluation, and a default", "= cfg.get(sSurname, \"xpath_LineWidth_Selected\") self.xpFillColorSlctd = cfg.get(sSurname, \"xpath_FillColor_Selected\") self.xpFillStyleSlctd = cfg.get(sSurname, \"xpath_FillStyle_Selected\") def __str__(self):", "try: s = s[0].text except AttributeError: s = s[0] return s except Exception,", "node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) return self.xpCtxt.xpathEval(xpExpr) except Exception, e: self.xpathError(node, xpExpr, e, \"xpathEval return None\")", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now get the", "handle return a list of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node)", "node): \"\"\"called before any sequnce of draw for a given page\"\"\" pass def", "__str__(self): s = Deco.__str__(self) s += \"+(x=%s y=%s w=%s h=%s)\" % (self.xpX, self.xpY,", "value if necessary xpX2 = self.xpathToStr(node, self.xpEvalX2, '\"\"') self._x2 = self.xpathToInt(node, xpX2, iLARGENEG,", "if s == Deco._s_prev_xpath_error: # let's not overload the console. return Deco._s_prev_xpath_error =", "\"Removal of @%s\"%sAttrName else: node.set(sAttrName, initialValue) s = '@%s := \"%s\"'%(sAttrName,initialValue) else: if", "sEncoding = s class DecoSeparator: \"\"\" this is not properly a decoration but", "The custom attribute contains data in a CSS style syntax. We parse this", "% str(eExcpt) if sMsg: s += \"\\n--- Info: %s\" % sMsg if s", "[(0,0)] try: ltXY = [] for _sPair in sCoords.split(' '): (sx, sy) =", "defaultdict import glob import logging import random from lxml import etree #import cStringIO", "self._x,self._y = self._x-self._inc, self._y-self._inc self._w,self._h = self._w+2*self._inc, self._h+2*self._inc self._node = node return (self._x,", "1) self._inc = self.xpathToInt(node, self.xpInc, 0) self._x,self._y = self._x-self._inc, self._y-self._inc self._w,self._h = self._w+2*self._inc,", "\"\"\" evaluate the xpath expression return None on error \"\"\" try: # s", "len(txt) except: self.warning(\"absence of text: cannot compute font size along X axis\") iFontSizeX", "self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') obj = wxh.AddScaledTextBox(txt, (x+x_inc, -y-y_inc),", "self.xpFillStyle, \"Solid\") obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) \"\"\"", "cfg is a config file sSurname is the decoration surname and the section", "cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrName = cfg.get(sSurname, \"xpath_AttrName\") self.xpAttrValue = cfg.get(sSurname, \"xpath_AttrValue\") self.dInitialValue = {}", ", Color=sFontColor) lo.append(obj) return lo def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\")", "must be evaluated twice self.xpEvalX2, self.xpEvalY2 = cfg.get(sSurname, \"eval_xpath_x2\"), cfg.get(sSurname, \"eval_xpath_y2\") self.xpDfltX2, self.xpDfltY2", "return s def runXYWHI(self, node): \"\"\"get the X,Y values for a node and", "self.xpFontColor, 'BLACK') sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") sBackgroundColor = self.xpathToStr(node, self.xpBackgroundColor, \"#000000\") #", "KeyError: pass return lo class DecoPolyLine(DecoREAD): \"\"\"A polyline along x1,y1,x2,y2, ...,xn,yn or x1,y1", "1) self._h = self.xpathToInt(node, self.xpH, 1) self._inc = self.xpathToInt(node, self.xpInc, 0) self._x,self._y =", "Example: parseCustomAttr( \"readingOrder {index:4;} structure {type:catch-word;}\" ) --> { 'readingOrder': [{ 'index':'4' }],", "self.dInitialValue = {} self.xpLineColorSlctd = cfg.get(sSurname, \"xpath_LineColor_Selected\") self.xpLineWidthSlctd = cfg.get(sSurname, \"xpath_LineWidth_Selected\") self.xpFillColorSlctd =", "1000: if sMsg != Deco._s_prev_warning: logging.warning(sMsg) Deco._warning_count += 1 Deco._s_prev_warning = sMsg def", "= self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj", "lo class DecoOrder(DecoBBXYWH): \"\"\"Show the order with lines \"\"\" def __init__(self, cfg, sSurname,", "FillStyle=sFillStyle) lo.append(obj) \"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor =", "self._laxyr: #draw a circle sFillColor = self.lsFillColor[Nf % iMaxFC] if self.lsLineColor: sLineColor =", "cfg.get(sSurname, \"eval_xpath_y2\") self.xpDfltX2, self.xpDfltY2 = cfg.get(sSurname, \"xpath_x2_default\"), cfg.get(sSurname, \"xpath_y2_default\") #now get the xpath", "wxh, node) ) return lo class DecoImage(DecoBBXYWH): \"\"\"An image \"\"\" # in case", "'index':'4' }], 'structure':[{'type':'catch-word'}] } \"\"\" dic = defaultdict(list) s = s.strip() lChunk =", "cfg, sSurname, xpCtxt) self.xpCluster = cfg.get(sSurname, \"xpath\") self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpRadius =", "\"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def draw(self,", "\"xpath_LineColor_Selected\") self.xpLineWidthSlctd = cfg.get(sSurname, \"xpath_LineWidth_Selected\") self.xpFillColorSlctd = cfg.get(sSurname, \"xpath_FillColor_Selected\") self.xpFillStyleSlctd = cfg.get(sSurname, \"xpath_FillStyle_Selected\")", "= wxh.AddScaledTextBox(txt, (x, -y+inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo", "xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpCluster = cfg.get(sSurname, \"xpath\") self.xpContent = cfg.get(sSurname, \"xpath_content\")", "if sFit == \"x\": iFontSize = iFontSizeX elif sFit == \"y\": iFontSize =", "shift the text def draw(self, wxh, node): lo = Deco.draw(self, wxh, node) if", "cfg.get(sSurname, \"xpath_hTo\") self.xpAttrToId = cfg.get(sSurname, \"xpath_ToId\") self.config = cfg.jl_hack_cfg #HACK def __str__(self): s", "on it add/remove an attribute the rectangle color is indicative of the presence/absence", "(min(lX), max(lY)), (max(lX), min(lY)) class DecoREADTextLine(DecoREAD): \"\"\"A TextLine as defined by the PageXml", "list of created WX objects \"\"\" lo = [] #add the text itself", "ExtentX, ExtentY \"\"\" (x1, y1), (x2, y2) = self._coordList_to_BB(ltXY) sFit = self.xpathToStr(node, self.xpFit,", "2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) #now get", "on it jump to a node \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self,", "self.xp_yTo = cfg.get(sSurname, \"xpath_yTo\") self.xp_wTo = cfg.get(sSurname, \"xpath_wTo\") self.xp_hTo = cfg.get(sSurname, \"xpath_hTo\") self.xpAttrToId", "max(0, self.xpathToInt(nd, sPageNumberAttr, 1, True) - 1) #maybe we can also indicate the", "except ValueError: logging.error(\"DecoUnicodeChar: ERROR: base=%d code=%s\"%(self.base, sEncodedText)) return \"\" class DecoImageBox(DecoRectangle): \"\"\"An image", "cfg.get(sSurname, \"xpath_h\") self.xpInc = cfg.get(sSurname, \"xpath_incr\") #to increase the BB width and height", "attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now get", "class\"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a configuration object sSurname", "for (_a, x, y, r) in self._laxyr: #draw a circle sFillColor = self.lsFillColor[Nf", "None except ValueError: dc = wx.ScreenDC() # compute for font size of 24", "encoded in Unicode We assume the unicode index is given in a certain", "eval('u\"\\\\u%04x\"' % int(sEncodedText, self.base)) except ValueError: logging.error(\"DecoUnicodeChar: ERROR: base=%d code=%s\"%(self.base, sEncodedText)) return \"\"", "1 Deco._s_prev_warning = sMsg def toInt(cls, s): try: return int(s) except ValueError: return", "dictionary Example: parseCustomAttr( \"readingOrder {index:4;} structure {type:catch-word;}\" ) --> { 'readingOrder': [{ 'index':'4'", "1) sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") for (_a, x, y, r) in self._laxyr:", "self._getCoordList(ndItem) fA, (xg, yg) = self.getArea_and_CenterOfMass(lxy) r = self.xpathToInt(ndItem, self.xpRadius, 1) self._laxyr.append( (fA,", "toInt(cls, s): try: return int(s) except ValueError: return int(round(float(s))) toInt = classmethod(toInt) def", "= self.xpathToStr(node, self.xpEvalX2, '\"\"') self._x2 = self.xpathToInt(node, xpX2, iLARGENEG, False) #do not show", "Nl = random.randrange(iMaxFC) iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\")", "'//*[@id=\"%s\"]'%sToId.strip()) if ln: #find the page number ndTo = nd = ln[0] #while", "the list of wx created objects\"\"\" return [] class DecoBBXYWH(Deco): \"\"\"A decoration with", "\"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xp_xTo = cfg.get(sSurname, \"xpath_xTo\") self.xp_yTo = cfg.get(sSurname, \"xpath_yTo\")", "wx handle return a list of created WX objects\"\"\" # print node.serialize() #", "iLARGENEG) #double evaluation, and a default value if necessary xpX2 = self.xpathToStr(node, self.xpEvalX2,", "the node serialization s = \"-\"*60 s += \"\\n--- XPath ERROR on class", "# for n in node.xpathEval(self.xpX): print n.serialize() lo = DecoREAD.draw(self, wxh, node) if", "the X,Y values for a node and put them in cache\"\"\" if self._node", "= self.xpathToInt(ndTo, self.xp_wTo, None) h = self.xpathToInt(ndTo, self.xp_hTo, None) if x==None or y==None", "ltXY = [] for _sPair in sCoords.split(' '): (sx, sy) = _sPair.split(',') ltXY.append((Deco.toInt(sx),", "wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node,", "wx handle return a list of created WX objects\"\"\" lo = DecoRectangle.draw(self, wxh,", "a list of created WX objects\"\"\" # print node.serialize() # print self.xpX #", "y1), (x2, y2) \"\"\" lX = [_x for _x,_y in ltXY] lY =", "associated decorations, return the list of wx created objects\"\"\" return [] class DecoBBXYWH(Deco):", "cfg.get(sSurname, \"xpath_label\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpBackgroundColor = cfg.get(sSurname, \"xpath_background_color\") def draw(self, wxh,", "= self._coordList_to_BB(ltXY) sFit = self.xpathToStr(node, self.xpFit, 'xy', bShowError=False) try: iFontSize = int(sFit) Ex,", "in sIds.split(): l = self.xpathEval(ndPage, './/*[@id=\"%s\"]'%sId) ndItem = l[0] lxy = self._getCoordList(ndItem) fA,", "self.xpathToInt(node, self.xpDfltX2, iLARGENEG) xpY2 = self.xpathToStr(node, self.xpEvalY2, '\"\"') self._y2 = self.xpathToInt(node, xpY2, iLARGENEG,", "= glob.glob(sFilePath) bKO = True for s in lCandidate: if os.path.exists(s): sFilePath =", "class READ_custom: \"\"\" Everything related to the PageXML custom attribute \"\"\" @classmethod def", "= None print \"DecoClusterCircle lsLineColor = \", self.lsLineColor print \"DecoClusterCircle lsFillColor = \",", "= cfg.get(sSurname, \"xpath_ToPageNumber\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s", "{index:0;} Item-name {offset:0; length:11;} Item-price {offset:12; length:2;}\"> <Coords points=\"985,390 1505,390 1505,440 985,440\"/> <Baseline", "WX objects \"\"\" lo = [] #add the text itself txt = self.getText(wxh,", "== sPrefix: sLocalDir = os.path.dirname(sUrl[len(sPrefix):]) sDir,_ = os.path.splitext(os.path.basename(sUrl)) sCandidate = os.path.abspath(os.path.join(sLocalDir, sDir, sFilePath))", "sLambdaExpr, xpExprArg, sEndEmpty = xpExpr.split('|') assert sEndEmpty == \"\", \"Missing last '|'\" sArg", "= _sPair.split(',') ltXY.append((Deco.toInt(sx), Deco.toInt(sy))) except Exception as e: logging.error(\"ERROR: polyline coords are bad:", "objects\"\"\" lo = DecoRectangle.draw(self, wxh, node) #add the text itself txt = self.xpathToStr(node,", "a list of created WX objects\"\"\" DecoClusterCircle.count = DecoClusterCircle.count + 1 lo =", "return lo class DecoTextBox(DecoRectangle): \"\"\"A text within a bounding box (a rectangle) \"\"\"", "Image: file does not exists: '%s'\"%sFilePath) sFilePath = None if bool(sFilePath): img =", "= cfg.get(sSurname, \"xpath_AttrValue\") self.dInitialValue = {} self.xpLineColorSlctd = cfg.get(sSurname, \"xpath_LineColor_Selected\") self.xpLineWidthSlctd = cfg.get(sSurname,", "r) in self._laxyr: #draw a circle sFillColor = self.lsFillColor[Nf % iMaxFC] if self.lsLineColor:", "\"x:1 ; y:2\") except Exception: raise ValueError(\"Expected a '{' in '%s'\"%chunk) #the dictionary", "-self._y1), (self._x2, -self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoREAD(Deco): \"\"\"", "Exception, e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToInt return %d as default value\"%iDefault)", "such decoration type: '%s'\"%sClass) return c getDecoClass = classmethod(getDecoClass) def getSurname(self): return self.sSurname", "xpath=.//TextLine/Coords xpath_lxy=@points xpath_LineColor=\"RED\" xpath_FillStyle=\"Solid\" <NAME> - March 2016 \"\"\" def __init__(self, cfg, sSurname,", "to fit the polygon and the extent of the 'x' character for this", "return self.xpathToStr(node, self.xpContent, \"\") class READ_custom: \"\"\" Everything related to the PageXML custom", "sSurname is the decoration surname and the section name in the config file", "= None self._lxy = None def __str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\"", "it via the menu sImageFolder = None def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self,", "{x:1\" chunk = chunk.strip() if not chunk: continue try: sNames, sValues = chunk.split('{')", "% (self.xpX, self.xpY, self.xpW, self.xpH) return s def runXYWHI(self, node): \"\"\"get the X,Y", "lCandidate: if os.path.exists(s): sFilePath = s bKO = False break if bKO: self.warning(\"WARNING:", "+= DecoBBXYWH.__str__(self) return s def draw(self, wxh, node): \"\"\"draw itself using the wx", "\"\") class READ_custom: \"\"\" Everything related to the PageXML custom attribute \"\"\" @classmethod", "(xprev+x) ySum += iTerm * (yprev+y) xprev, yprev = x, y if fA", "Ex / len(txt) except: self.warning(\"absence of text: cannot compute font size along X", "x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y-h/2.0), Size=iFontSize, Family=wx.ROMAN, Position='cl', Color=sFontColor, PadSize=0,", "cfg.get(sSurname, \"xpath_xTo\") self.xp_yTo = cfg.get(sSurname, \"xpath_yTo\") self.xp_wTo = cfg.get(sSurname, \"xpath_wTo\") self.xp_hTo = cfg.get(sSurname,", "ValueError: dc = wx.ScreenDC() # compute for font size of 24 and do", "x, y = self._lxy[0] x_inc = self.xpathToInt(node, self.xpX_Inc, 0, False) y_inc = self.xpathToInt(node,", "xpath error\"\"\" try: Deco._s_prev_xpath_error except AttributeError: Deco._s_prev_xpath_error = \"\" Deco._prev_xpath_error_count = 0 iMaxLen", "DecoBBXYWH.draw(self, wxh, node) #add the text itself txt = self.getText(wxh, node) iFontSize =", "#need to go thru each item ndPage = node.xpath(\"ancestor::*[local-name()='Page']\")[0] sIds = self.xpathEval(node, self.xpContent)[0]", "created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) #add the text itself txt", "985,440\"/> or <Baseline points=\"985,435 1505,435\"/> \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg,", "None x,y,w,h = None, None, None, None bbHighlight = None sToId = self.xpathToStr(node,", "scalar XPath expressions to get the associated x,y,w,h values from the selected nodes", "\"x\": iFontSize = iFontSizeX elif sFit == \"y\": iFontSize = iFontSizeY else: iFontSize", "comma-separated string, got '%s'\"%sKeyVal) sKey = sKey.strip().lower() if bNoCase else sKey.strip() dicValForName[sKey] =", "= cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.lsLineColor = cfg.get(sSurname, \"LineColors\").split() self.lsFillColor =", "#to increase the BB width and height self._node = None def __str__(self): s", "= node if self._laxyr: iMaxFC = len(self.lsFillColor) iMaxLC = len(self.lsLineColor) if False: Nf", "= None if bool(sFilePath): img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) try: if h > 0:", "xpath_LineColor=\"RED\" xpath_FillStyle=\"Solid\" <NAME> - March 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self,", "= self.xpathToInt(node, self.xpLineWidth, 1) sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") for (_a, x, y,", "= sNode[:iMaxLen] + \"...\" s += \"\\n--- XML node = %s\" % sNode", "cfg.get(sSurname, \"xpath_ToId\") self.config = cfg.jl_hack_cfg #HACK def __str__(self): s = \"%s=\"%self.__class__ s +=", "self.xpathEval(ndPage, './/*[@id=\"%s\"]'%sId) ndItem = l[0] lxy = self._getCoordList(ndItem) fA, (xg, yg) = self.getArea_and_CenterOfMass(lxy)", "= cfg.get(sSurname, \"xpath_hTo\") self.xpAttrToId = cfg.get(sSurname, \"xpath_ToId\") self.config = cfg.jl_hack_cfg #HACK def __str__(self):", "a string on the given node The XPath expression should return a scalar", "folder with same name as XML file? (Transkribus style) sUrl = node.getroottree().docinfo.URL.decode('utf-8') #", "= None x,y,w,h = None, None, None, None bbHighlight = None sToId =", "== None or initialValue == sAttrValue: #very special case: when an attr was", "of wx created objects\"\"\" return [] class DecoBBXYWH(Deco): \"\"\"A decoration with a bounding", "return lCoord class DecoTextPolyLine(DecoPolyLine, DecoText): \"\"\"A polyline that closes automatically the shape <NAME>", "eExcpt, sMsg=\"\"): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_xpath_error except AttributeError: Deco._s_prev_xpath_error = \"\"", "ltXY = self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt , Family=wx.FONTFAMILY_TELETYPE) dCustom", "sFit == \"y\": iFontSize = iFontSizeY else: iFontSize = min(iFontSizeX, iFontSizeY) dc.SetFont(wx.Font(iFontSize, Family,", "dc.GetTextExtent(\"x\") try: iFontSizeX = 24 * abs(x2-x1) / Ex / len(txt) except: self.warning(\"absence", "pass class Deco: \"\"\"A general decoration class\"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\"", "xn,yn Example of config: [TextLine] type=DecoPolyLine xpath=.//TextLine/Coords xpath_lxy=@points xpath_LineColor=\"RED\" xpath_FillStyle=\"Solid\" <NAME> - March", "self.xpathToInt(node, self.xpH, 1) self._inc = self.xpathToInt(node, self.xpInc, 0) self._x,self._y = self._x-self._inc, self._y-self._inc self._w,self._h", "self._x1 = self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) #double evaluation, and", "\"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) #draw a line obj = wxh.AddLine( [(self._x1,", "s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName, sAttrValue) s = '@%s := \"%s\"'%(sAttrName,sAttrValue)", "== \"x\": iFontSize = iFontSizeX elif sFit == \"y\": iFontSize = iFontSizeY else:", "each item ndPage = node.xpath(\"ancestor::*[local-name()='Page']\")[0] sIds = self.xpathEval(node, self.xpContent)[0] for sId in sIds.split():", "\"\") class DecoUnicodeChar(DecoText): \"\"\"A character encoded in Unicode We assume the unicode index", "else sKey.strip() dicValForName[sKey] = sVal.strip() lName = sNames.split(',') for name in lName: name", "try: Deco._s_prev_warning except AttributeError: Deco._s_prev_warning = \"\" Deco._warning_count = 0 # if sMsg", "with a bounding box defined by X,Y for its top-left corner and width/height.", "cfg.get(sSurname, \"enabled\").lower() self.bEnabled = sEnabled in ['1', 'yes', 'true'] def isSeparator(cls): return False", "the following items: x, y, w, h \"\"\" Deco.__init__(self, cfg, sSurname, xpCtxt) #now", "for name in lName: name = name.strip().lower() if bNoCase else name.strip() dic[name].append(dicValForName) return", "cfg.get(sSurname, \"LineColors\").split() self.lsFillColor = cfg.get(sSurname, \"FillColors\").split() #cached values self._node = None self._laxyr =", "return self.xpMain def isEnabled(self): return self.bEnabled def setEnabled(self, b=True): self.bEnabled = b return", "\"xpath_FillStyle\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def draw(self,", "decoration to be made on certain XML node using WX \"\"\" import types,", "WX objects\"\"\" DecoClusterCircle.count = DecoClusterCircle.count + 1 lo = DecoREAD.draw(self, wxh, node) if", ", LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) else: self.bInit = True iEllipseParam = min(w,h) /", "= s.strip() lChunk = s.split('}') if lChunk: for chunk in lChunk: #things like", "lo class DecoImage(DecoBBXYWH): \"\"\"An image \"\"\" # in case the use wants to", "sEncoding = \"utf-8\" def setEncoding(s): global sEncoding sEncoding = s class DecoSeparator: \"\"\"", "xpCtxt) self.xpCoords = cfg.get(sSurname, \"xpath_lxy\") def _getCoordList(self, node): sCoords = self.xpathToStr(node, self.xpCoords, \"\")", "= min(iFontSizeX, iFontSizeY) dc.SetFont(wx.Font(iFontSize, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") del dc", "import types, os from collections import defaultdict import glob import logging import random", "\"#000000\") sBackgroundColor = self.xpathToStr(node, self.xpBackgroundColor, \"#000000\") # Position and computation of font size", "class DecoClusterCircle(DecoREAD): \"\"\" [Cluster] type=DecoClusterCircle xpath=.//Cluster xpath_content=@content xpath_radius=40 xpath_item_lxy=./pg:Coords/@points xpath_LineWidth=\"1\" xpath_FillStyle=\"Transparent\" LineColors=\"BLUE SIENNA", "= wxh.AddScaledBitmap(img, (x,-y), h) else: obj = wxh.AddScaledBitmap(img, (x,-y), img.GetHeight()) lo.append(obj) except Exception,", "x, y if fA == 0.0: raise ValueError(\"surface == 0.0\") fA = fA", "e: self.warning(\"DecoImageBox ERROR: File %s: %s\"%(sFilePath, str(e))) lo.append( DecoRectangle.draw(self, wxh, node) ) return", "self._coordList_to_BB(ltXY) sFit = self.xpathToStr(node, self.xpFit, 'xy', bShowError=False) try: iFontSize = int(sFit) Ex, Ey", "\"xpathEval return None\") return None def beginPage(self, node): \"\"\"called before any sequnce of", "= \"%s=\"%self.__class__ return s def _getFontSize(self, node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE): \"\"\" compute the", "{index:4;} structure {type:catch-word;}\" ) --> { 'readingOrder': [{ 'index':'4' }], 'structure':[{'type':'catch-word'}] } \"\"\"", "(w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo = [obj] + lo return lo", "a scalar or a one-node nodeset On error, return the default int value", "txt = self.getText(wxh, node) iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor,", "s def getArea_and_CenterOfMass(self, lXY): \"\"\" https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone return A, (Xg, Yg) which are the", "{ 'readingOrder': [{ 'index':'4' }], 'structure':[{'type':'catch-word'}] } \"\"\" dic = defaultdict(list) s =", "\"x:1\" for sKeyVal in lsKeyVal: if not sKeyVal.strip(): continue #empty try: sKey, sVal", "mass of the polygon \"\"\" if len(lXY) < 2: raise ValueError(\"Only one point:", "center of mass of the polygon \"\"\" if len(lXY) < 2: raise ValueError(\"Only", "try: sNames, sValues = chunk.split('{') #things like: (\"a,b\", \"x:1 ; y:2\") except Exception:", "sSurname, xpCtxt) self.xpCluster = cfg.get(sSurname, \"xpath\") self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpRadius = cfg.get(sSurname,", "(w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo.append(obj) return lo class DecoTextBox(DecoRectangle): \"\"\"A text", "to be made on certain XML node using WX \"\"\" import types, os", "return lo class DecoPolyLine(DecoREAD): \"\"\"A polyline along x1,y1,x2,y2, ...,xn,yn or x1,y1 x2,y2 ....", "node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth,", "s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) if xpExpr[0] == \"|\": #must be a lambda assert", "== \"\", \"Missing last '|'\" sArg = self.xpCtxt.xpathEval(xpExprArg)[0] sPythonExpr = \"(%s)(%s)\" % (sLambdaExpr,", "self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: try: img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY)", "sNames, sValues = chunk.split('{') #things like: (\"a,b\", \"x:1 ; y:2\") except Exception: raise", "= ln[0] #while nd and nd.name != \"PAGE\": nd = nd.parent while nd", "page \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now get", "%s\" % sMsg if s == Deco._s_prev_xpath_error: # let's not overload the console.", "y = int(x + w/2.0), int(y + h/2.0) if self.bInit: #draw a line", "config file This section should contain the following items: x, y, w, h", "= cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrToPageNumber = cfg.get(sSurname, \"xpath_ToPageNumber\") def __str__(self): s = \"%s=\"%self.__class__ s", "sVal = sKeyVal.split(':') except Exception: raise ValueError(\"Expected a comma-separated string, got '%s'\"%sKeyVal) sKey", "-fA, (xg, yg) else: return fA, (xg, yg) assert fA >0 and xg", "size of 24 and do proportional dc.SetFont(wx.Font(24, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey =", "expression return None on error \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) return", "\"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpX2, self.xpY2) return s def draw(self,", "is given in a certain base, e.g. 10 or 16 \"\"\" def __init__(self,", "Deco._s_prev_warning and Deco._warning_count < 1000: if sMsg != Deco._s_prev_warning: logging.warning(sMsg) Deco._warning_count += 1", "a certain base, e.g. 10 or 16 \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) # obj = wxh.AddRectangle((x, -y), (20, 20), # LineWidth=iLineWidth, #", "\"xpath_label\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpBackgroundColor = cfg.get(sSurname, \"xpath_background_color\") def draw(self, wxh, node):", "self.xpathToStr(node, self.xpEvalX2, '\"\"') self._x2 = self.xpathToInt(node, xpX2, iLARGENEG, False) #do not show any", "sFit = self.xpathToStr(node, self.xpFit, 'xy', bShowError=False) try: iFontSize = int(sFit) Ex, Ey =", "\"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return s def getArea_and_CenterOfMass(self, lXY): \"\"\" https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone", "self.base)) except ValueError: logging.error(\"DecoUnicodeChar: ERROR: base=%d code=%s\"%(self.base, sEncodedText)) return \"\" class DecoImageBox(DecoRectangle): \"\"\"An", "s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName, initialValue) s = '@%s := \"%s\"'%(sAttrName,initialValue)", "cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth =", "iLARGENEG and self._y2 != iLARGENEG: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node,", "config: [TextLine] type=DecoPolyLine xpath=.//TextLine/Coords xpath_lxy=@points xpath_LineColor=\"RED\" xpath_FillStyle=\"Solid\" <NAME> - March 2016 \"\"\" def", "Ex, Ey = dc.GetTextExtent(\"x\") try: iFontSizeX = 24 * abs(x2-x1) / Ex /", "let us find the rectangle line and fill colors self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\")", "x_inc = self.xpathToInt(node, self.xpX_Inc, 0, False) y_inc = self.xpathToInt(node, self.xpY_Inc, 0, False) txt", "classmethod(isSeparator) def __str__(self): return \"(Surname=%s xpath==%s)\" % (self.sSurname, self.xpMain) def getDecoClass(cls, sClass): \"\"\"given", "getDecoClass(cls, sClass): \"\"\"given a decoration type, return the associated class\"\"\" c = globals()[sClass]", "text itself x, y = self._lxy[0] x_inc = self.xpathToInt(node, self.xpX_Inc, 0, False) y_inc", "self.xpMain = cfg.get(sSurname, \"xpath\") # a main XPath that select nodes to be", "# x, y = ltXY[0] (x, _y1), (_x2, y) = self._coordList_to_BB(ltXY) obj =", "classmethod(toInt) def xpathToInt(self, node, xpExpr, iDefault=0, bShowError=True): \"\"\"The given XPath expression should return", "if bShowError: self.xpathError(node, xpExpr, e, \"xpathToStr return %s as default value\"%sDefault) return sDefault", "an xpath error\"\"\" try: Deco._s_prev_xpath_error except AttributeError: Deco._s_prev_xpath_error = \"\" Deco._prev_xpath_error_count = 0", "\"xpath_y\") self.xpW, self.xpH = cfg.get(sSurname, \"xpath_w\"), cfg.get(sSurname, \"xpath_h\") self.xpInc = cfg.get(sSurname, \"xpath_incr\") #to", "+= 1 if Deco._prev_xpath_error_count > 10: return try: sNode = etree.tostring(node) except: sNode", "the xpath expression return None on error \"\"\" try: # s = node.xpathEval(xpExpr)", "h \"\"\" Deco.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions that let", "\"xpath_font_color\") self.xpFit = cfg.get(sSurname, \"xpath_fit_text_size\").lower() def __str__(self): s = \"%s=\"%self.__class__ return s def", "an attr was set, then saved, re-clicking on it wil remove it. del", "y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpEvalX2, self.xpEvalY2) return s def draw(self, wxh,", "(_a, x, y, r) in self._laxyr: #draw a circle sFillColor = self.lsFillColor[Nf %", "\"\"\"A text within a bounding box (a rectangle) \"\"\" def __init__(self, cfg, sSurname,", "= \", self.lsFillColor def __str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords)", "self.xpEvalX2, '\"\"') self._x2 = self.xpathToInt(node, xpX2, iLARGENEG, False) #do not show any error", "DecoClickableRectangleSetAttr(DecoBBXYWH): \"\"\"A rectangle clicking on it add/remove an attribute the rectangle color is", "xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions that let us", "8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x,", "= classmethod(getDecoClass) def getSurname(self): return self.sSurname def getMainXPath(self): return self.xpMain def isEnabled(self): return", "type, return the associated class\"\"\" c = globals()[sClass] if type(c) != types.ClassType: raise", "s in lCandidate: if os.path.exists(s): sFilePath = s bKO = False break if", "a dictionary of list of dictionary Example: parseCustomAttr( \"readingOrder {index:4;} structure {type:catch-word;}\" )", "\"\"\"A general decoration class\"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a", "return None\") return None def beginPage(self, node): \"\"\"called before any sequnce of draw", "= self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y+inc), Size=iFontSize,", "-h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo = [obj] + lo return lo def", "on it jump to a page \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self,", "not properly a decoration but rather a separator of decoration in the toolbar", "%d as default value\"%iDefault) return iDefault def xpathToStr(self, node, xpExpr, sDefault, bShowError=True): \"\"\"The", "coordinates. like: <Coords points=\"985,390 1505,390 1505,440 985,440\"/> or <Baseline points=\"985,435 1505,435\"/> \"\"\" def", "= self._getCoordList(ndItem) fA, (xg, yg) = self.getArea_and_CenterOfMass(lxy) r = self.xpathToInt(ndItem, self.xpRadius, 1) self._laxyr.append(", "of mass of the polygon \"\"\" if len(lXY) < 2: raise ValueError(\"Only one", "\"\"\"A TextLine as defined by the PageXml format of the READ project <TextLine", "= \"utf-8\" def setEncoding(s): global sEncoding sEncoding = s class DecoSeparator: \"\"\" this", "on error \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) return self.xpCtxt.xpathEval(xpExpr) except Exception,", "values for a node and put them in cache\"\"\" if self._node != node:", "self.warning(\"DecoImageBox ERROR: File %s: %s\"%(sFilePath, str(e))) lo.append( DecoRectangle.draw(self, wxh, node) ) return lo", "itself txt = self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') # Position and", "sAttrValue: #very special case: when an attr was set, then saved, re-clicking on", "of @%s\"%sAttrName else: node.set(sAttrName, initialValue) s = '@%s := \"%s\"'%(sAttrName,initialValue) else: if not", "sKey.strip().lower() if bNoCase else sKey.strip() dicValForName[sKey] = sVal.strip() lName = sNames.split(',') for name", "0, False) y_inc = self.xpathToInt(node, self.xpY_Inc, 0, False) txt = self.xpathToStr(node, self.xpContent, \"\")", "y, r) in self._laxyr: #draw a circle sFillColor = self.lsFillColor[Nf % iMaxFC] if", "self.xpBackgroundColor, \"#000000\") # Position and computation of font size ltXY = self._getCoordList(node) iFontSize,", "be decorated in this way self.xpCtxt = xpCtxt #this context may include the", "node: self._lxy = self._getCoordList(node) self._node = node #lo = DecoClosedPolyLine.draw(self, wxh, node) #add", "self.getArea_and_CenterOfMass(lxy) r = self.xpathToInt(ndItem, self.xpRadius, 1) self._laxyr.append( (fA, xg, yg, r) ) self._node", "node.get(\"id\") is None: self.warning(\"No coordinates: node = %s\" % etree.tostring(node)) else: self.warning(\"No coordinates:", "lo class DecoLink(Deco): \"\"\"A link from x1,y1 to x2,y2 \"\"\" def __init__(self, cfg,", "w/2.0), int(y + h/2.0) if self.bInit: #draw a line iLineWidth = self.xpathToInt(node, self.xpLineWidth,", "self.xpathToInt(nd, sPageNumberAttr, 1, True) - 1) #maybe we can also indicate the precise", "\"xpath_FillColor_Selected\") self.xpFillStyleSlctd = cfg.get(sSurname, \"xpath_FillStyle_Selected\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self)", "Exception, e: self.warning(\"DecoImageBox ERROR: File %s: %s\"%(sFilePath, str(e))) lo.append( DecoRectangle.draw(self, wxh, node) )", "iFontSizeY else: iFontSize = min(iFontSizeX, iFontSizeY) dc.SetFont(wx.Font(iFontSize, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey =", "is indicative of the presence/absence of the attribute \"\"\" def __init__(self, cfg, sSurname,", "x,y,w,h values from the selected nodes \"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\"", "self.xpY = cfg.get(sSurname, \"xpath_x\"), cfg.get(sSurname, \"xpath_y\") self.xpW, self.xpH = cfg.get(sSurname, \"xpath_w\"), cfg.get(sSurname, \"xpath_h\")", "%s\" % node.get(\"id\")) return [(0,0)] try: ltXY = [] for _sPair in sCoords.split('", "LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) # obj = wxh.AddRectangle((x, -y), (20, 20), # LineWidth=iLineWidth,", "node) #add the image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\")", "file does not exists: '%s'\"%sFilePath) sFilePath = None if bool(sFilePath): img = wx.Image(sFilePath,", "\"xpath_ToPageNumber\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def isActionable(self):", "string on the given node The XPath expression should return a scalar or", "of draw for a given page\"\"\" pass def endPage(self, node): \"\"\"called before any", "sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) #draw a line", "Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class DecoClusterCircle(DecoREAD): \"\"\" [Cluster] type=DecoClusterCircle xpath=.//Cluster", "self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) self._x2 = self.xpathToInt(node, self.xpX2, iLARGENEG)", "WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node,", "self.xpathToStr(node, self.xpFillColor, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") obj = wxh.AddRectangle((x, -y), (w,", "(x,-y), img.GetHeight()) lo.append(obj) except Exception, e: self.warning(\"DecoImage ERROR: File %s: %s\"%(sFilePath, str(e))) return", "return (self._x, self._y, self._w, self._h, self._inc) class DecoRectangle(DecoBBXYWH): \"\"\"A rectangle \"\"\" def __init__(self,", "LineColor=sLineColor , BackgroundColor=sBackgroundColor) lo.append(obj) except KeyError: pass except KeyError: pass return lo class", "The XPath expression should return a scalar or a one-node nodeset On error,", "def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a configuration object sSurname is", "specify it via the menu sImageFolder = None def __init__(self, cfg, sSurname, xpCtxt):", "index is given in a certain base, e.g. 10 or 16 \"\"\" def", "wxh, node): sEncodedText = self.xpathToStr(node, self.xpContent, \"\") try: return eval('u\"\\\\u%04x\"' % int(sEncodedText, self.base))", "%s: %s\"%(sFilePath, str(e))) return lo class DecoOrder(DecoBBXYWH): \"\"\"Show the order with lines \"\"\"", "lsFillColor = \", self.lsFillColor def __str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" %", "except ValueError: return int(round(float(s))) toInt = classmethod(toInt) def xpathToInt(self, node, xpExpr, iDefault=0, bShowError=True):", "self.xpFillStyle, \"Solid\") obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo.append(obj)", "self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") self.xpX2, self.xpY2 = cfg.get(sSurname, \"xpath_x2\"), cfg.get(sSurname, \"xpath_y2\")", "node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) if xpExpr[0] == \"|\": #must be a lambda assert xpExpr[:8] ==", "decoration in the toolbar \"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is", "classmethod(getDecoClass) def getSurname(self): return self.sSurname def getMainXPath(self): return self.xpMain def isEnabled(self): return self.bEnabled", "lo class DecoLine(Deco): \"\"\"A line from x1,y1 to x2,y2 \"\"\" def __init__(self, cfg,", "an int on the given node. The XPath expression should return a scalar", "= \"%s=\"%self.__class__ s += \"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpX2, self.xpY2)", "configuration object sSurname is the surname of the decoration and the section name", "return s def beginPage(self, node): \"\"\"called before any sequnce of draw for a", "LineColor=sLineColor, # FillColor=sFillColor, # FillStyle=sFillStyle) lo.append(obj) \"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc", "-y), (20, 20), # LineWidth=iLineWidth, # LineColor=sLineColor, # FillColor=sFillColor, # FillStyle=sFillStyle) lo.append(obj) \"\"\"", "self.xpX, 1) self._y = self.xpathToInt(node, self.xpY, 1) self._w = self.xpathToInt(node, self.xpW, 1) self._h", "bShowError: self.xpathError(node, xpExpr, e, \"xpathToStr return %s as default value\"%sDefault) return sDefault def", "#lo = DecoClosedPolyLine.draw(self, wxh, node) #add the text itself x, y = self._lxy[0]", "\"\"\"called before any sequnce of draw for a given page\"\"\" self.bInit = False", "any error if self._y2 == iLARGENEG: self._y2 = self.xpathToInt(node, self.xpDfltY2, iLARGENEG) self._node =", "sEndEmpty = xpExpr.split('|') assert sEndEmpty == \"\", \"Missing last '|'\" sArg = self.xpCtxt.xpathEval(xpExprArg)[0]", "xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) def _getCoordList(self, node): lCoord = DecoPolyLine._getCoordList(self, node) if", "#maybe the image is in a folder with same name as XML file?", "the config file! xpCtxt is an XPath context \"\"\" self.sSurname = sSurname self.xpMain", "rectangle \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now get", "\"\"\" return the page number of the destination or None on error \"\"\"", "if sFilePath: if self.sImageFolder: sCandidate = os.path.join(self.sImageFolder, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate", "wxh, node) #add the text itself x, y = self._lxy[0] x_inc = self.xpathToInt(node,", "setXPathContext(self, xpCtxt): pass class Deco: \"\"\"A general decoration class\"\"\" def __init__(self, cfg, sSurname,", "logging.warning(sMsg) Deco._warning_count += 1 Deco._s_prev_warning = sMsg def toInt(cls, s): try: return int(s)", "x1,y1 to x2,y2 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt)", "fA <0: return -fA, (xg, yg) else: return fA, (xg, yg) assert fA", "self._y2 = self.xpathToInt(node, self.xpDfltY2, iLARGENEG) self._node = node if self._x1 != iLARGENEG and", "#should be an attribute value return Deco.toInt(s) except Exception, e: if bShowError: self.xpathError(node,", "the rectangle line and fill colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname,", "self._x2 = self.xpathToInt(node, xpX2, iLARGENEG, False) #do not show any error if self._x2", "else: self.bInit = True iEllipseParam = min(w,h) / 2 wxh.AddEllipse((x, -y), (iEllipseParam, -iEllipseParam),", "iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") for (_a, x,", "lxy = self._getCoordList(ndItem) fA, (xg, yg) = self.getArea_and_CenterOfMass(lxy) r = self.xpathToInt(ndItem, self.xpRadius, 1)", "* abs(x2-x1) / Ex / len(txt) except: self.warning(\"absence of text: cannot compute font", "\"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") self.xpX2, self.xpY2 = cfg.get(sSurname, \"xpath_x2\"), cfg.get(sSurname, \"xpath_y2\") #now get the", "# FillStyle=sFillStyle) lo.append(obj) \"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor", "= cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s", "#draw a circle sFillColor = self.lsFillColor[Nf % iMaxFC] if self.lsLineColor: sLineColor = self.lsLineColor[Nl", "None self._laxyr = None print \"DecoClusterCircle lsLineColor = \", self.lsLineColor print \"DecoClusterCircle lsFillColor", "= self.xpathToInt(node, xpY2, iLARGENEG, False) #do not show any error if self._y2 ==", "the section name in the config file This section should contain the following", "ltXY = self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE) # x,", "y) = self._coordList_to_BB(ltXY) obj = wxh.AddScaledText(txt, (x, -y+iFontSize/6), Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='tl'", "except Exception: raise ValueError(\"Expected a '{' in '%s'\"%chunk) #the dictionary for that name", "= cfg.get(sSurname, \"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s", ", Color=sFontColor , LineColor=sLineColor , BackgroundColor=sBackgroundColor) lo.append(obj) except KeyError: pass except KeyError: pass", "the default int value \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) if xpExpr[0]", "%s\"%xpExpr sStartEmpty, sLambdaExpr, xpExprArg, sEndEmpty = xpExpr.split('|') assert sEndEmpty == \"\", \"Missing last", "if self._x1 != iLARGENEG and self._y1 != iLARGENEG and self._x2 != iLARGENEG and", "style) sUrl = node.getroottree().docinfo.URL.decode('utf-8') # py2 ... for sPrefix in [\"file://\", \"file:/\"]: if", "% (self.sSurname, self.xpMain) def getDecoClass(cls, sClass): \"\"\"given a decoration type, return the associated", "= None self._laxyr = None print \"DecoClusterCircle lsLineColor = \", self.lsLineColor print \"DecoClusterCircle", "PadSize=0, LineColor=None) lo.append(obj) return lo class DecoClusterCircle(DecoREAD): \"\"\" [Cluster] type=DecoClusterCircle xpath=.//Cluster xpath_content=@content xpath_radius=40", "a folder with same name as XML file? (Transkribus style) sUrl = node.getroottree().docinfo.URL.decode('utf-8')", "xpath=.//Cluster xpath_content=@content xpath_radius=40 xpath_item_lxy=./pg:Coords/@points xpath_LineWidth=\"1\" xpath_FillStyle=\"Transparent\" LineColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" FillColors=\"BLUE", "iLARGENEG) self._x2 = self.xpathToInt(node, self.xpX2, iLARGENEG) self._y2 = self.xpathToInt(node, self.xpY2, iLARGENEG) self._node =", "wx handle return a list of created WX objects\"\"\" DecoClusterCircle.count = DecoClusterCircle.count +", "def isEnabled(self): return self.bEnabled def setEnabled(self, b=True): self.bEnabled = b return b def", "xg, yg = xSum/6/fA, ySum/6/fA if fA <0: return -fA, (xg, yg) else:", "font size so as to fit the polygon and the extent of the", "zip(self._lxy, self._lxy[1:]): #draw a line obj = wxh.AddLine( [(x1, -y1), (x2, -y2)] ,", "#add the text itself txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize,", "self.xpFontSize = cfg.get(sSurname, \"xpath_font_size\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__", "for sKeyVal in lsKeyVal: if not sKeyVal.strip(): continue #empty try: sKey, sVal =", "self.xpathToInt(node, self.xpY1, iLARGENEG) #double evaluation, and a default value if necessary xpX2 =", "DecoREADTextLine(DecoREAD): \"\"\"A TextLine as defined by the PageXml format of the READ project", "lo = Deco.draw(self, wxh, node) if self._node != node: self._lxy = self._getCoordList(node) self._node", "= cfg.get(sSurname, \"xpath_FillStyle\") self.xp_xTo = cfg.get(sSurname, \"xpath_xTo\") self.xp_yTo = cfg.get(sSurname, \"xpath_yTo\") self.xp_wTo =", "#add the text itself txt = self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK')", "node #lo = DecoClosedPolyLine.draw(self, wxh, node) #add the text itself x, y =", "= cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") def __str__(self):", "== 0.0\") fA = fA / 2 xg, yg = xSum/6/fA, ySum/6/fA if", "LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) \"\"\" return lo class DecoLink(Deco): \"\"\"A link from x1,y1 to", "= etree.tostring(node) except: sNode = str(node) if len(sNode) > iMaxLen: sNode = sNode[:iMaxLen]", "iLARGENEG = -9999 lo = Deco.draw(self, wxh, node) if self._node != node: self._x1", "a decoration but rather a separator of decoration in the toolbar \"\"\" def", "node) if self._node != node: self._laxyr = [] #need to go thru each", "1) sFillColor = self.xpathToStr(node, self.xpFillColorSlctd, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyleSlctd, \"Solid\") else: sLineColor", "sLocalDir = os.path.dirname(sUrl[len(sPrefix):]) sDir,_ = os.path.splitext(os.path.basename(sUrl)) sCandidate = os.path.abspath(os.path.join(sLocalDir, sDir, sFilePath)) if os.path.exists(sCandidate):", "lo class DecoREAD(Deco): \"\"\" READ PageXml has a special way to encode coordinates.", "= self.xpathToInt(node, self.xpY1, iLARGENEG) #double evaluation, and a default value if necessary xpX2", "while nd and nd.name != sPageTag: nd = nd.parent try: #number = max(0,", "n.serialize() lo = DecoREAD.draw(self, wxh, node) if self._node != node: self._lxy = self._getCoordList(node)", "= chunk.split('{') #things like: (\"a,b\", \"x:1 ; y:2\") except Exception: raise ValueError(\"Expected a", "self._getFontSize(node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE) # x, y = ltXY[0] (x, _y1), (_x2, y)", "+= \"\\n--- Python Exception=%s\" % str(eExcpt) if sMsg: s += \"\\n--- Info: %s\"", "= cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrName = cfg.get(sSurname, \"xpath_AttrName\") self.xpAttrValue =", "%s\"%self.__class__ s += \"\\n--- xpath=%s\" % xpExpr s += \"\\n--- Python Exception=%s\" %", "repr(sArg)) s = eval(sPythonExpr) else: s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try:", "file is in a subfolder ? # e.g. \"S_Aicha_an_der_Donau_004-03_0005.jpg\" is in folder \"S_Aicha_an_der_Donau_004-03\"", "\"xpath_incr\") #to increase the BB width and height self._node = None def __str__(self):", "cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpCluster = cfg.get(sSurname, \"xpath\") self.xpContent =", "are the area and the coordinates (float) of the center of mass of", "== Deco._s_prev_xpath_error: # let's not overload the console. return Deco._s_prev_xpath_error = s Deco._prev_xpath_error_count", "sId in sIds.split(): l = self.xpathEval(ndPage, './/*[@id=\"%s\"]'%sId) ndItem = l[0] lxy = self._getCoordList(ndItem)", "#now get the xpath expressions that let uis find x,y,w,h from a selected", "config file sSurname is the decoration surname and the section name in the", "= cfg.jl_hack_cfg #HACK def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s", "y = -y0+iFontSize/6 obj = wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength] , (x, y) , Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE", "DecoSeparator: \"\"\" this is not properly a decoration but rather a separator of", "initialValue = self.dInitialValue[node] except KeyError: initialValue = node.prop(sAttrName) #first time self.dInitialValue[node] = initialValue", "# to truncate the node serialization s = \"-\"*60 s += \"\\n--- XPath", "if type(c) != types.ClassType: raise Exception(\"No such decoration type: '%s'\"%sClass) return c getDecoClass", "self.xpHRef, \"\") if sFilePath: try: img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) obj = wxh.AddScaledBitmap(img, (x,-y),", "ltXY.append((Deco.toInt(sx), Deco.toInt(sy))) except Exception as e: logging.error(\"ERROR: polyline coords are bad: '%s' ->", "sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\")", "self._x1 != iLARGENEG and self._y1 != iLARGENEG and self._x2 != iLARGENEG and self._y2", "def isActionable(self): return True def draw(self, wxh, node): \"\"\"draw itself using the wx", "sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") self.xpFit = cfg.get(sSurname,", "= cfg.get(sSurname, \"FillColors\").split() #cached values self._node = None self._laxyr = None print \"DecoClusterCircle", "return the page number of the destination or None on error \"\"\" sPageTag", "sMsg != Deco._s_prev_warning and Deco._warning_count < 1000: if sMsg != Deco._s_prev_warning: logging.warning(sMsg) Deco._warning_count", "before any sequnce of draw for a given page\"\"\" pass def draw(self, wxh,", "= self.getText(wxh, node) iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK')", "10 or 16 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoText.__init__(self, cfg, sSurname, xpCtxt)", "(Transkribus style) sUrl = node.getroottree().docinfo.URL.decode('utf-8') # py2 ... for sPrefix in [\"file://\", \"file:/\"]:", "objects \"\"\" lo = [] #add the text itself txt = self.getText(wxh, node)", "\"\"\" self.sSurname = sSurname def __str__(self): return \"--------\" def isSeparator(self): return True def", "page\"\"\" pass def endPage(self, node): \"\"\"called before any sequnce of draw for a", "following items: x, y, w, h \"\"\" Deco.__init__(self, cfg, sSurname, xpCtxt) #now get", "e.g. \"S_Aicha_an_der_Donau_004-03_0005.jpg\" is in folder \"S_Aicha_an_der_Donau_004-03\" try: sDir = sFilePath[:sFilePath.rindex(\"_\")] sCandidate = os.path.join(self.sImageFolder,", "cfg.get(sSurname, \"xpath_FillColor_Selected\") self.xpFillStyleSlctd = cfg.get(sSurname, \"xpath_FillStyle_Selected\") def __str__(self): s = \"%s=\"%self.__class__ s +=", "xpCtxt): pass class Deco: \"\"\"A general decoration class\"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "config file! xpCtxt is an XPath context \"\"\" self.sSurname = sSurname self.xpMain =", "lambda expression %s\"%xpExpr sStartEmpty, sLambdaExpr, xpExprArg, sEndEmpty = xpExpr.split('|') assert sEndEmpty == \"\",", "its top-left corner and width/height. xpX, xpY, xpW, xpH are scalar XPath expressions", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname,", "sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate except ValueError: pass if not os.path.exists(sFilePath): #maybe", "xpath expressions that let us find the rectangle line and fill colors self.xpLineWidth", "ORANGE RED GREEN\" FillColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" enabled=1 \"\"\" count =", "of the presence/absence of the attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self,", "2 wxh.AddEllipse((x, -y), (iEllipseParam, -iEllipseParam), LineColor=sLineColor, LineWidth=5, FillStyle=\"Transparent\") self.prevX, self.prevY = x, y", ", BackgroundColor=sBackgroundColor) lo.append(obj) except KeyError: pass except KeyError: pass return lo class DecoPolyLine(DecoREAD):", "lChunk: for chunk in lChunk: #things like \"a {x:1\" chunk = chunk.strip() if", "= cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrName = cfg.get(sSurname, \"xpath_AttrName\") self.xpAttrValue = cfg.get(sSurname, \"xpath_AttrValue\") self.dInitialValue =", "cfg.get(sSurname, \"xpath_FillStyle_Selected\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def", "self.xp_yTo, None) w = self.xpathToInt(ndTo, self.xp_wTo, None) h = self.xpathToInt(ndTo, self.xp_hTo, None) if", "= self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillColor", "node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") sBackgroundColor =", "= wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) \"\"\" return lo class", "1) for (x1, y1), (x2, y2) in zip(self._lxy, self._lxy[1:]): #draw a line obj", "n in node.xpathEval(self.xpX): print n.serialize() lo = DecoREAD.draw(self, wxh, node) if self._node !=", "\"\") if sFilePath: try: img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) obj = wxh.AddScaledBitmap(img, (x,-y), h)", "lXY: iTerm = xprev*y - yprev*x fA += iTerm xSum += iTerm *", "sSurname def __str__(self): return \"--------\" def isSeparator(self): return True def setXPathContext(self, xpCtxt): pass", "error, return the default int value \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node)", "iDefault def xpathToStr(self, node, xpExpr, sDefault, bShowError=True): \"\"\"The given XPath expression should return", "def beginPage(self, node): \"\"\"called before any sequnce of draw for a given page\"\"\"", "s += \"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpX2, self.xpY2) return s", "custom attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREADTextLine.__init__(self, cfg, sSurname, xpCtxt) self.xpLabel", "number of the destination or None on error \"\"\" index,x,y,w,h = None,None,None,None,None sToPageNum", "the menu sImageFolder = None def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname,", "return %d as default value\"%iDefault) return iDefault def xpathToStr(self, node, xpExpr, sDefault, bShowError=True):", "it. del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName, initialValue) s =", "before any sequnce of draw for a given page\"\"\" pass def endPage(self, node):", "ValueError(\"Only one point: polygon area is undefined.\") fA = 0.0 xSum, ySum =", "compute the font size so as to fit the polygon and the extent", "return fA, (xg, yg) assert fA >0 and xg >0 and yg >0,", "#while nd and nd.name != \"PAGE\": nd = nd.parent while nd and nd.name", "yg = xSum/6/fA, ySum/6/fA if fA <0: return -fA, (xg, yg) else: return", "Deco.draw(self, wxh, node) if self._node != node: self._x1 = self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1", "sSurname, xpCtxt) self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") def __str__(self): s", "True def draw(self, wxh, node): \"\"\"draw itself using the wx handle return a", "YELLOW ORANGE RED GREEN\" enabled=1 \"\"\" count = 0 def __init__(self, cfg, sSurname,", "[obj] + lo return lo def act(self, obj, node): \"\"\" return the page", "sKey.strip() dicValForName[sKey] = sVal.strip() lName = sNames.split(',') for name in lName: name =", "clicking on it jump to a node \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "__init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) def _getCoordList(self, node): lCoord =", "\"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrName = cfg.get(sSurname, \"xpath_AttrName\")", "class DecoOrder(DecoBBXYWH): \"\"\"Show the order with lines \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo = [obj]", "self.xpathToStr(node, self.xpAttrToPageNumber , None) if sToPageNum: index = int(sToPageNum) - 1 return index,x,y,w,h", "x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: try: img =", "= name.strip().lower() if bNoCase else name.strip() dic[name].append(dicValForName) return dic class DecoREADTextLine_custom_offset(DecoREADTextLine, READ_custom): \"\"\"", "py2 ... for sPrefix in [\"file://\", \"file:/\"]: if sUrl[0:len(sPrefix)] == sPrefix: sLocalDir =", "line iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) obj = wxh.AddLine( [(self.prevX, -self.prevY), (x, -y)]", "self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrToPageNumber = cfg.get(sSurname, \"xpath_ToPageNumber\") def", "self.xpContent, \"\") class DecoUnicodeChar(DecoText): \"\"\"A character encoded in Unicode We assume the unicode", "= self._getCoordList(node) self._node = node if self._lxy: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth", "DecoText(DecoBBXYWH): \"\"\"A text \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt)", "objects\"\"\" # print node.serialize() # print self.xpX # for n in node.xpathEval(self.xpX): print", "xpCtxt): DecoText.__init__(self, cfg, sSurname, xpCtxt) self.base = int(cfg.get(sSurname, \"code_base\")) def getText(self, wxh, node):", "!= iLARGENEG and self._y2 != iLARGENEG: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth =", "is None: self.warning(\"No coordinates: node = %s\" % etree.tostring(node)) else: self.warning(\"No coordinates: node", "general decoration class\"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a configuration", "twice self.xpEvalX2, self.xpEvalY2 = cfg.get(sSurname, \"eval_xpath_x2\"), cfg.get(sSurname, \"eval_xpath_y2\") self.xpDfltX2, self.xpDfltY2 = cfg.get(sSurname, \"xpath_x2_default\"),", "node.set(sAttrName, sAttrValue) s = '@%s := \"%s\"'%(sAttrName,sAttrValue) return s class DecoClickableRectangleJump(DecoBBXYWH): \"\"\"A rectangle", "Color=sFontColor) lo.append(obj) return lo def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class", "% ( self.xpCoords, sCoords)) raise e return ltXY def _coordList_to_BB(self, ltXY): \"\"\" return", "Toggle the attribute value \"\"\" s = \"do nothing\" sAttrName = self.xpathToStr(node, self.xpAttrName", "= self.lsLineColor[Nl % iMaxLC] else: sLineColor = sFillColor obj = wxh.AddCircle((x, -y), r,", "def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def draw(self, wxh,", "Deco._warning_count < 1000: if sMsg != Deco._s_prev_warning: logging.warning(sMsg) Deco._warning_count += 1 Deco._s_prev_warning =", "bNoCase=True): \"\"\" The custom attribute contains data in a CSS style syntax. We", "s class DecoClickableRectangleJump(DecoBBXYWH): \"\"\"A rectangle clicking on it jump to a node \"\"\"", "except AttributeError: Deco._s_prev_xpath_error = \"\" Deco._prev_xpath_error_count = 0 iMaxLen = 200 # to", "self.xpDfltY2, iLARGENEG) self._node = node if self._x1 != iLARGENEG and self._y1 != iLARGENEG", "xpath_item_lxy=./pg:Coords/@points xpath_LineWidth=\"1\" xpath_FillStyle=\"Transparent\" LineColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" FillColors=\"BLUE SIENNA YELLOW ORANGE", "= \"(%s)(%s)\" % (sLambdaExpr, repr(sArg)) s = eval(sPythonExpr) else: s = self.xpCtxt.xpathEval(xpExpr) if", "from the selected nodes \"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is", "for _x,_y in ltXY] return (min(lX), max(lY)), (max(lX), min(lY)) class DecoREADTextLine(DecoREAD): \"\"\"A TextLine", "\"\"\" if len(lXY) < 2: raise ValueError(\"Only one point: polygon area is undefined.\")", "lo.append( DecoRectangle.draw(self, wxh, node) ) return lo class DecoImage(DecoBBXYWH): \"\"\"An image \"\"\" #", "y:2\") except Exception: raise ValueError(\"Expected a '{' in '%s'\"%chunk) #the dictionary for that", "None def __str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return s", "self.xpH, 1) self._inc = self.xpathToInt(node, self.xpInc, 0) self._x,self._y = self._x-self._inc, self._y-self._inc self._w,self._h =", "__init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions", "of created WX objects \"\"\" lo = [] #add the text itself txt", "a line iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) obj = wxh.AddLine( [(self.prevX, -self.prevY), (x,", "evaluation, and a default value if necessary xpX2 = self.xpathToStr(node, self.xpEvalX2, '\"\"') self._x2", "page\"\"\" pass def draw(self, wxh, node): \"\"\"draw the associated decorations, return the list", "self.bEnabled = b return b def isActionable(self): return False def setXPathContext(self, xpCtxt): self.xpCtxt", "of decoration in the toolbar \"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg", "coordinates: node id = %s\" % node.get(\"id\")) return [(0,0)] try: ltXY = []", "? # e.g. \"S_Aicha_an_der_Donau_004-03_0005.jpg\" is in folder \"S_Aicha_an_der_Donau_004-03\" try: sDir = sFilePath[:sFilePath.rindex(\"_\")] sCandidate", ", LineColor=sLineColor) lo.append(obj) else: self.bInit = True iEllipseParam = min(w,h) / 2 wxh.AddEllipse((x,", "__str__(self): s = \"%s=\"%self.__class__ s += \"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1,", "Family=wx.FONTFAMILY_TELETYPE , Position='bl' , Color=sFontColor , LineColor=sLineColor , BackgroundColor=sBackgroundColor) lo.append(obj) except KeyError: pass", "that select nodes to be decorated in this way self.xpCtxt = xpCtxt #this", "self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return", "self.xpathToInt(ndTo, self.xp_xTo, None) y = self.xpathToInt(ndTo, self.xp_yTo, None) w = self.xpathToInt(ndTo, self.xp_wTo, None)", "# e.g. \"S_Aicha_an_der_Donau_004-03_0005.jpg\" is in folder \"S_Aicha_an_der_Donau_004-03\" try: sDir = sFilePath[:sFilePath.rindex(\"_\")] sCandidate =", "in a CSS style syntax. We parse this syntax here and return a", "= wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo.append(obj) return lo class", "= dict() lsKeyVal = sValues.split(';') #things like \"x:1\" for sKeyVal in lsKeyVal: if", "LineColor=None) lo.append(obj) return lo class DecoClusterCircle(DecoREAD): \"\"\" [Cluster] type=DecoClusterCircle xpath=.//Cluster xpath_content=@content xpath_radius=40 xpath_item_lxy=./pg:Coords/@points", "sCandidate = os.path.abspath(os.path.join(sLocalDir, sDir, sFilePath)) if os.path.exists(sCandidate): sFilePath = sCandidate print(sFilePath) break if", "line and fill colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self._node", "sDir, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate except ValueError: pass if not os.path.exists(sFilePath):", "def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\")", "the config file This section should contain the following items: x, y, w,", "yprev = x, y if fA == 0.0: raise ValueError(\"surface == 0.0\") fA", ", LineColor=sLineColor) lo.append(obj) return lo class DecoClickableRectangleSetAttr(DecoBBXYWH): \"\"\"A rectangle clicking on it add/remove", "a node and put them in cache\"\"\" if self._node != node: self._x =", "self.xpX_Inc, 0, False) y_inc = self.xpathToInt(node, self.xpY_Inc, 0, False) txt = self.xpathToStr(node, self.xpContent,", "saved, re-clicking on it wil remove it. del node.attrib[sAttrName] s = \"Removal of", "self._getCoordList(node) self._node = node if self._lxy: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth =", "= cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") #the following expression must be evaluated twice self.xpEvalX2,", "the given node The XPath expression should return a scalar or a one-node", "for (x1, y1), (x2, y2) in zip(self._lxy, self._lxy[1:]): #draw a line obj =", "should return an int on the given node. The XPath expression should return", "and the section name in the config file This section should contain the", "in sCoords.split(' '): (sx, sy) = _sPair.split(',') ltXY.append((Deco.toInt(sx), Deco.toInt(sy))) except Exception as e:", "self.xpFontColor, 'BLACK') obj = wxh.AddScaledTextBox(txt, (x+x_inc, -y-y_inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None)", "Nf = random.randrange(iMaxFC) Nl = random.randrange(iMaxFC) iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillStyle =", "if node.get(sAttrName) == sAttrValue: #back to previous value if initialValue == None or", "= self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: if self.sImageFolder: sCandidate = os.path.join(self.sImageFolder, sFilePath) if", "them in cache\"\"\" if self._node != node: self._x = self.xpathToInt(node, self.xpX, 1) self._y", "'%s'\"%sFilePath) sFilePath = None if bool(sFilePath): img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) try: if h", "y1), (x2, y2) in zip(self._lxy, self._lxy[1:]): #draw a line obj = wxh.AddLine( [(x1,", "self.xpathToInt(ndTo, self.xp_yTo, None) w = self.xpathToInt(ndTo, self.xp_wTo, None) h = self.xpathToInt(ndTo, self.xp_hTo, None)", "\"%s=\"%self.__class__ return s def _getFontSize(self, node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE): \"\"\" compute the font", "xpExpr[:8] == \"|lambda \", \"Invalid lambda expression %s\"%xpExpr sStartEmpty, sLambdaExpr, xpExprArg, sEndEmpty =", "attribute \"\"\" @classmethod def parseCustomAttr(cls, s, bNoCase=True): \"\"\" The custom attribute contains data", "sPageTag: nd = nd.parent try: #number = max(0, int(nd.prop(\"number\")) - 1) number =", "this way self.xpCtxt = xpCtxt #this context may include the declaration of some", "Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class DecoText(DecoBBXYWH): \"\"\"A text \"\"\"", "= self.parseCustomAttr(node.get(\"custom\"), bNoCase=True) try: x0, y0 = ltXY[0] _ldLabel = dCustom[self.xpathToStr(node, self.xpLabel, \"\").lower()]", "\"xpath_LineWidth\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.lsLineColor = cfg.get(sSurname, \"LineColors\").split() self.lsFillColor = cfg.get(sSurname, \"FillColors\").split()", "= self.xpathToStr(node, self.xpAttrValue, None) if sAttrName and sAttrValue != None: if node.prop(sAttrName) ==", "self.config = cfg.jl_hack_cfg #HACK def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return", "= self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) #draw a line obj", "glob.glob(sFilePath) bKO = True for s in lCandidate: if os.path.exists(s): sFilePath = s", "self.sSurname = sSurname def __str__(self): return \"--------\" def isSeparator(self): return True def setXPathContext(self,", "= cfg.get(sSurname, \"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return s", "os.path.join(self.sImageFolder, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate else: # maybe the file is", "self._x2 = self.xpathToInt(node, self.xpX2, iLARGENEG) self._y2 = self.xpathToInt(node, self.xpY2, iLARGENEG) self._node = node", "> 0: obj = wxh.AddScaledBitmap(img, (x,-y), h) else: obj = wxh.AddScaledBitmap(img, (x,-y), img.GetHeight())", "iLARGENEG) self._node = node if self._x1 != iLARGENEG and self._y1 != iLARGENEG and", "= self.xpathToStr(node, self.xpLineColor, \"BLACK\") x, y = int(x + w/2.0), int(y + h/2.0)", "dictionary for that name dicValForName = dict() lsKeyVal = sValues.split(';') #things like \"x:1\"", "\"+(x=%s y=%s w=%s h=%s)\" % (self.xpX, self.xpY, self.xpW, self.xpH) return s def runXYWHI(self,", "\"utf-8\" def setEncoding(s): global sEncoding sEncoding = s class DecoSeparator: \"\"\" this is", "else: # maybe the file is in a subfolder ? # e.g. \"S_Aicha_an_der_Donau_004-03_0005.jpg\"", "= self._getCoordList(node) self._node = node #lo = DecoClosedPolyLine.draw(self, wxh, node) #add the text", "cfg.get(sSurname, \"xpath_font_size\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__ s +=", "ndTo = nd = ln[0] #while nd and nd.name != \"PAGE\": nd =", "DecoREAD.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions that let us find", "= self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) #double evaluation, and a", "continue #empty try: sKey, sVal = sKeyVal.split(':') except Exception: raise ValueError(\"Expected a comma-separated", "y return lo class DecoLine(Deco): \"\"\"A line from x1,y1 to x2,y2 \"\"\" def", "the wx handle return a list of created WX objects\"\"\" lo = DecoBBXYWH.draw(self,", "self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") self.xpFit = cfg.get(sSurname, \"xpath_fit_text_size\").lower() def __str__(self): s = \"%s=\"%self.__class__", "expression should return a scalar or a one-node nodeset On error, return the", "ORANGE RED GREEN\" enabled=1 \"\"\" count = 0 def __init__(self, cfg, sSurname, xpCtxt):", "1) self._laxyr.append( (fA, xg, yg, r) ) self._node = node if self._laxyr: iMaxFC", "cfg.get(sSurname, \"xpath_LineWidth_Selected\") self.xpFillColorSlctd = cfg.get(sSurname, \"xpath_FillColor_Selected\") self.xpFillStyleSlctd = cfg.get(sSurname, \"xpath_FillStyle_Selected\") def __str__(self): s", "KeyError: initialValue = node.prop(sAttrName) #first time self.dInitialValue[node] = initialValue if node.get(sAttrName) == sAttrValue:", "error \"\"\" sPageTag = self.config.getPageTag() sPageNumberAttr = self.config.getPageNumberAttr() number = None x,y,w,h =", "-> '%s'\" % ( self.xpCoords, sCoords)) raise e return ltXY def _coordList_to_BB(self, ltXY):", "'BLACK') obj = wxh.AddScaledTextBox(txt, (x+x_inc, -y-y_inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj)", "!= None: if node.prop(sAttrName) == sAttrValue: sLineColor = self.xpathToStr(node, self.xpLineColorSlctd, \"#000000\") iLineWidth =", "# obj = wxh.AddRectangle((x, -y), (20, 20), # LineWidth=iLineWidth, # LineColor=sLineColor, # FillColor=sFillColor,", "expression should return a string on the given node The XPath expression should", "# print self.xpX # for n in node.xpathEval(self.xpX): print n.serialize() lo = DecoREAD.draw(self,", "'%s'\" % ( self.xpCoords, sCoords)) raise e return ltXY def _coordList_to_BB(self, ltXY): \"\"\"", "sEnabled = cfg.get(sSurname, \"enabled\").lower() self.bEnabled = sEnabled in ['1', 'yes', 'true'] def isSeparator(cls):", "coordinates: node = %s\" % etree.tostring(node)) else: self.warning(\"No coordinates: node id = %s\"", "= self.xpathToStr(node, self.xpLineColorSlctd, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidthSlctd, 1) sFillColor = self.xpathToStr(node, self.xpFillColorSlctd,", "str(node) if len(sNode) > iMaxLen: sNode = sNode[:iMaxLen] + \"...\" s += \"\\n---", "txt = self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') sLineColor = self.xpathToStr(node, self.xpLineColor,", "initialValue = node.prop(sAttrName) #first time self.dInitialValue[node] = initialValue if node.get(sAttrName) == sAttrValue: #back", "Ey = dc.GetTextExtent(\"x\") try: iFontSizeX = 24 * abs(x2-x1) / Ex / len(txt)", "in zip(self._lxy, self._lxy[1:]): #draw a line obj = wxh.AddLine( [(x1, -y1), (x2, -y2)]", "if self._node != node: self._x1 = self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1,", "self.base = int(cfg.get(sSurname, \"code_base\")) def getText(self, wxh, node): sEncodedText = self.xpathToStr(node, self.xpContent, \"\")", "node serialization s = \"-\"*60 s += \"\\n--- XPath ERROR on class %s\"%self.__class__", "lo def act(self, obj, node): \"\"\" return the page number of the destination", "\"\" Deco._warning_count = 0 # if sMsg != Deco._s_prev_warning and Deco._warning_count < 1000:", "yg))) return fA, (xg, yg) def draw(self, wxh, node): \"\"\"draw itself using the", "cfg.get(sSurname, \"xpath_background_color\") def draw(self, wxh, node): \"\"\" draw itself using the wx handle", "return s def isActionable(self): return True def draw(self, wxh, node): \"\"\"draw itself using", "if sFilePath: try: img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) obj = wxh.AddScaledBitmap(img, (x,-y), h) lo.append(obj)", "self.xpathToStr(node, self.xpFillStyleSlctd, \"Solid\") else: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth,", "iOffset y = -y0+iFontSize/6 obj = wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength] , (x, y) , Size=iFontSize ,", "decoration surname and the section name in the config file This section should", "isSeparator(self): return True def setXPathContext(self, xpCtxt): pass class Deco: \"\"\"A general decoration class\"\"\"", "FillColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" enabled=1 \"\"\" count = 0 def __init__(self,", "sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__ s +=", "os.path.exists(sCandidate): sFilePath = sCandidate else: # maybe the file is in a subfolder", "a node \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now", "self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return", "def act(self, obj, node): \"\"\" return the page number of the destination or", "itself using the wx handle return a list of created WX objects\"\"\" #", "DecoImageBox(DecoRectangle): \"\"\"An image with a box around it \"\"\" def __init__(self, cfg, sSurname,", "sBackgroundColor = self.xpathToStr(node, self.xpBackgroundColor, \"#000000\") # Position and computation of font size ltXY", "if False: Nf = DecoClusterCircle.count Nl = Nf else: Nf = random.randrange(iMaxFC) Nl", "= lXY[-1] for x, y in lXY: iTerm = xprev*y - yprev*x fA", "xpathEval(self, node, xpExpr): \"\"\" evaluate the xpath expression return None on error \"\"\"", "same name as XML file? (Transkribus style) sUrl = node.getroottree().docinfo.URL.decode('utf-8') # py2 ...", "%s\"%(sFilePath, str(e))) return lo class DecoOrder(DecoBBXYWH): \"\"\"Show the order with lines \"\"\" def", "error if self._x2 == iLARGENEG: self._x2 = self.xpathToInt(node, self.xpDfltX2, iLARGENEG) xpY2 = self.xpathToStr(node,", "self.xpCoords, sCoords)) raise e return ltXY def _coordList_to_BB(self, ltXY): \"\"\" return (x1, y1),", "self.xpathError(node, xpExpr, e, \"xpathEval return None\") return None def beginPage(self, node): \"\"\"called before", "or <Baseline points=\"985,435 1505,435\"/> \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname,", "global sEncoding sEncoding = s class DecoSeparator: \"\"\" this is not properly a", "wxh.AddScaledTextBox(txt, (x+x_inc, -y-y_inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class", "= self.xpathToStr(node, self.xpFillStyleSlctd, \"Solid\") else: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node,", "= cfg.get(sSurname, \"enabled\").lower() self.bEnabled = sEnabled in ['1', 'yes', 'true'] def isSeparator(cls): return", "in lCandidate: if os.path.exists(s): sFilePath = s bKO = False break if bKO:", ", Family=wx.FONTFAMILY_TELETYPE , Position='bl' , Color=sFontColor , LineColor=sLineColor , BackgroundColor=sBackgroundColor) lo.append(obj) except KeyError:", "on the given node. The XPath expression should return a scalar or a", "xpathToInt(self, node, xpExpr, iDefault=0, bShowError=True): \"\"\"The given XPath expression should return an int", "True) - 1) #maybe we can also indicate the precise arrival point? if", "s += DecoBBXYWH.__str__(self) return s def isActionable(self): return True def draw(self, wxh, node):", "return lo class DecoImage(DecoBBXYWH): \"\"\"An image \"\"\" # in case the use wants", "logging.warning(s) def warning(self, sMsg): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_warning except AttributeError: Deco._s_prev_warning", "iLARGENEG) self._y2 = self.xpathToInt(node, self.xpY2, iLARGENEG) self._node = node if self._x1 != iLARGENEG", "the custom attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREADTextLine.__init__(self, cfg, sSurname, xpCtxt)", "sSurname, xpCtxt) self.xpCoords = cfg.get(sSurname, \"xpath_lxy\") def _getCoordList(self, node): sCoords = self.xpathToStr(node, self.xpCoords,", "sSurname, xpCtxt) #now get the xpath expressions that let us find the rectangle", "with a box around it \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg,", "(x, _y1), (_x2, y) = self._coordList_to_BB(ltXY) obj = wxh.AddScaledText(txt, (x, -y+iFontSize/6), Size=iFontSize ,", "+= \"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpX2, self.xpY2) return s def", "node) iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc =", "DecoRectangle.draw(self, wxh, node) ) return lo class DecoImage(DecoBBXYWH): \"\"\"An image \"\"\" # in", "DecoPolyLine._getCoordList(self, node) if lCoord: lCoord.append(lCoord[0]) return lCoord class DecoTextPolyLine(DecoPolyLine, DecoText): \"\"\"A polyline that", "\"do nothing\" sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue = self.xpathToStr(node, self.xpAttrValue, None)", "(self.xpX1, self.xpY1, self.xpX2, self.xpY2) return s def draw(self, wxh, node): \"\"\"draw itself using", "= int(_dLabel[\"offset\"]) iLength = int(_dLabel[\"length\"]) x = x0 + Ex * iOffset y", "\"\\n--- XML node = %s\" % sNode s += \"\\n\" + \"-\"*60 +", "bShowError=True): \"\"\"The given XPath expression should return a string on the given node", "cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions that", "\"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\")", "self.warning(\"No coordinates: node = %s\" % etree.tostring(node)) else: self.warning(\"No coordinates: node id =", "\"LineColors\").split() self.lsFillColor = cfg.get(sSurname, \"FillColors\").split() #cached values self._node = None self._laxyr = None", "s[0] return s except Exception, e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToStr return", "def setXPathContext(self, xpCtxt): pass class Deco: \"\"\"A general decoration class\"\"\" def __init__(self, cfg,", "== types.ListType: try: s = s[0].text except AttributeError: s = s[0] return s", "not show any error if self._y2 == iLARGENEG: self._y2 = self.xpathToInt(node, self.xpDfltY2, iLARGENEG)", "% node.get(\"id\")) return [(0,0)] try: ltXY = [] for _sPair in sCoords.split(' '):", "logging import random from lxml import etree #import cStringIO import wx sEncoding =", "page\"\"\" self.bInit = False def draw(self, wxh, node): \"\"\"draw itself using the wx", "= s class DecoSeparator: \"\"\" this is not properly a decoration but rather", "X,Y values for a node and put them in cache\"\"\" if self._node !=", "s += \"\\n\" + \"-\"*60 + \"\\n\" logging.warning(s) def warning(self, sMsg): \"\"\"report an", "box defined by X,Y for its top-left corner and width/height. xpX, xpY, xpW,", "<Baseline points=\"985,435 1505,435\"/> \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt)", "= cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") def __str__(self): s = \"%s=\"%self.__class__ s", "iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) obj = wxh.AddLine( [(self.prevX, -self.prevY), (x, -y)] ,", "return \"\" class DecoImageBox(DecoRectangle): \"\"\"An image with a box around it \"\"\" def", "sImageFolder = None def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef", "for x, y in lXY: iTerm = xprev*y - yprev*x fA += iTerm", "= self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) for (x1, y1), (x2,", "-h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo.append(obj) return lo class DecoTextBox(DecoRectangle): \"\"\"A text within", "xprev, yprev = lXY[-1] for x, y in lXY: iTerm = xprev*y -", "sSurname, xpCtxt) self.xpLabel = cfg.get(sSurname, \"xpath_label\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpBackgroundColor = cfg.get(sSurname,", "if os.path.exists(s): sFilePath = s bKO = False break if bKO: self.warning(\"WARNING: deco", "image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: if", "-y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo.append(obj) return lo class DecoTextBox(DecoRectangle): \"\"\"A", "ERROR: base=%d code=%s\"%(self.base, sEncodedText)) return \"\" class DecoImageBox(DecoRectangle): \"\"\"An image with a box", "self.xp_hTo, None) if x==None or y==None or w==None or h==None: x,y,w,h = None,", "given XPath expression should return a string on the given node The XPath", "via the menu sImageFolder = None def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg,", "truncate the node serialization s = \"-\"*60 s += \"\\n--- XPath ERROR on", "def xpathEval(self, node, xpExpr): \"\"\" evaluate the xpath expression return None on error", "in node.xpathEval(self.xpX): print n.serialize() lo = DecoREAD.draw(self, wxh, node) if self._node != node:", "int value \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) s = self.xpCtxt.xpathEval(xpExpr) if", "self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") #cached values self._node = None self._lxy = None def", "10: return try: sNode = etree.tostring(node) except: sNode = str(node) if len(sNode) >", "(fA, xg, yg, r) ) self._node = node if self._laxyr: iMaxFC = len(self.lsFillColor)", "(yprev+y) xprev, yprev = x, y if fA == 0.0: raise ValueError(\"surface ==", "- September 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt)", "return s def _getFontSize(self, node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE): \"\"\" compute the font size", "#do not show any error if self._x2 == iLARGENEG: self._x2 = self.xpathToInt(node, self.xpDfltX2,", "of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor", "= s[0] return s except Exception, e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToStr", "return a list of created WX objects\"\"\" DecoClusterCircle.count = DecoClusterCircle.count + 1 lo", "time self.dInitialValue[node] = initialValue if node.get(sAttrName) == sAttrValue: #back to previous value if", "xpY, xpW, xpH are scalar XPath expressions to get the associated x,y,w,h values", "sFilePath = None if bool(sFilePath): img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) try: if h >", "and a default value if necessary xpX2 = self.xpathToStr(node, self.xpEvalX2, '\"\"') self._x2 =", "iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt , Family=wx.FONTFAMILY_TELETYPE) dCustom = self.parseCustomAttr(node.get(\"custom\"), bNoCase=True)", "return Deco.toInt(s) except Exception, e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToInt return %d", "node: self._x1 = self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) #double evaluation,", "the polygon \"\"\" if len(lXY) < 2: raise ValueError(\"Only one point: polygon area", "!= None: try: initialValue = self.dInitialValue[node] except KeyError: initialValue = node.prop(sAttrName) #first time", "or x1,y1 x2,y2 .... xn,yn Example of config: [TextLine] type=DecoPolyLine xpath=.//TextLine/Coords xpath_lxy=@points xpath_LineColor=\"RED\"", "DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) def _getCoordList(self, node): lCoord = DecoPolyLine._getCoordList(self, node) if lCoord:", "xprev*y - yprev*x fA += iTerm xSum += iTerm * (xprev+x) ySum +=", "xpCtxt) self.xpLabel = cfg.get(sSurname, \"xpath_label\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpBackgroundColor = cfg.get(sSurname, \"xpath_background_color\")", "= cfg.get(sSurname, \"xpath_FillStyle\") self.lsLineColor = cfg.get(sSurname, \"LineColors\").split() self.lsFillColor = cfg.get(sSurname, \"FillColors\").split() #cached values", "we have some pattern?? lCandidate = glob.glob(sFilePath) bKO = True for s in", "wxh.AddEllipse((x, -y), (iEllipseParam, -iEllipseParam), LineColor=sLineColor, LineWidth=5, FillStyle=\"Transparent\") self.prevX, self.prevY = x, y return", "size along X axis\") iFontSizeX = 8 iFontSizeY = 24 * abs(y2-y1) /", "sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize = cfg.get(sSurname, \"xpath_font_size\") self.xpFontColor = cfg.get(sSurname,", "None: self.warning(\"No coordinates: node = %s\" % etree.tostring(node)) else: self.warning(\"No coordinates: node id", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname,", "ValueError: pass if not os.path.exists(sFilePath): #maybe the image is in a folder with", "xpX2 = self.xpathToStr(node, self.xpEvalX2, '\"\"') self._x2 = self.xpathToInt(node, xpX2, iLARGENEG, False) #do not", "selected nodes \"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a config", "if self._node != node: self._x = self.xpathToInt(node, self.xpX, 1) self._y = self.xpathToInt(node, self.xpY,", "if initialValue == None or initialValue == sAttrValue: #very special case: when an", "def draw(self, wxh, node): \"\"\" draw itself using the wx handle return a", "def __str__(self): return \"(Surname=%s xpath==%s)\" % (self.sSurname, self.xpMain) def getDecoClass(cls, sClass): \"\"\"given a", "console. return Deco._s_prev_xpath_error = s Deco._prev_xpath_error_count += 1 if Deco._prev_xpath_error_count > 10: return", "s = s.strip() lChunk = s.split('}') if lChunk: for chunk in lChunk: #things", "c getDecoClass = classmethod(getDecoClass) def getSurname(self): return self.sSurname def getMainXPath(self): return self.xpMain def", "try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) return self.xpCtxt.xpathEval(xpExpr) except Exception, e: self.xpathError(node, xpExpr,", "let uis find x,y,w,h from a selected node self.xpX, self.xpY = cfg.get(sSurname, \"xpath_x\"),", "lsKeyVal = sValues.split(';') #things like \"x:1\" for sKeyVal in lsKeyVal: if not sKeyVal.strip():", "type=DecoClusterCircle xpath=.//Cluster xpath_content=@content xpath_radius=40 xpath_item_lxy=./pg:Coords/@points xpath_LineWidth=\"1\" xpath_FillStyle=\"Transparent\" LineColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\"", "self.dInitialValue[node] = initialValue if node.get(sAttrName) == sAttrValue: #back to previous value if initialValue", "= cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self._node = None def __str__(self): s", "+= DecoRectangle.__str__(self) return s def draw(self, wxh, node): \"\"\"draw itself using the wx", "1) obj = wxh.AddLine( [(self.prevX, -self.prevY), (x, -y)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj)", "closes automatically the shape <NAME> - September 2016 \"\"\" def __init__(self, cfg, sSurname,", "XML file? (Transkribus style) sUrl = node.getroottree().docinfo.URL.decode('utf-8') # py2 ... for sPrefix in", "fA == 0.0: raise ValueError(\"surface == 0.0\") fA = fA / 2 xg,", "return lo class DecoREAD(Deco): \"\"\" READ PageXml has a special way to encode", "self.xpY_Inc = cfg.get(sSurname, \"xpath_y_incr\") #to shift the text def draw(self, wxh, node): lo", "return None def beginPage(self, node): \"\"\"called before any sequnce of draw for a", "_getCoordList(self, node): lCoord = DecoPolyLine._getCoordList(self, node) if lCoord: lCoord.append(lCoord[0]) return lCoord class DecoTextPolyLine(DecoPolyLine,", "bShowError: self.xpathError(node, xpExpr, e, \"xpathToInt return %d as default value\"%iDefault) return iDefault def", "top-left corner and width/height. xpX, xpY, xpW, xpH are scalar XPath expressions to", "WX objects\"\"\" lo = [] #add the image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath", "evaluated twice self.xpEvalX2, self.xpEvalY2 = cfg.get(sSurname, \"eval_xpath_x2\"), cfg.get(sSurname, \"eval_xpath_y2\") self.xpDfltX2, self.xpDfltY2 = cfg.get(sSurname,", "= 8 iFontSizeY = 24 * abs(y2-y1) / Ey if sFit == \"x\":", "(x1, y1), (x2, y2) in zip(self._lxy, self._lxy[1:]): #draw a line obj = wxh.AddLine(", "lo = [obj] + lo return lo def act(self, obj, node): \"\"\" Toggle", "the console. return Deco._s_prev_xpath_error = s Deco._prev_xpath_error_count += 1 if Deco._prev_xpath_error_count > 10:", "name.strip().lower() if bNoCase else name.strip() dic[name].append(dicValForName) return dic class DecoREADTextLine_custom_offset(DecoREADTextLine, READ_custom): \"\"\" Here", "None) h = self.xpathToInt(ndTo, self.xp_hTo, None) if x==None or y==None or w==None or", "= s bKO = False break if bKO: self.warning(\"WARNING: deco Image: file does", "% (self.xpCoords) return s def getArea_and_CenterOfMass(self, lXY): \"\"\" https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone return A, (Xg, Yg)", "+= \"+(x=%s y=%s w=%s h=%s)\" % (self.xpX, self.xpY, self.xpW, self.xpH) return s def", "iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillColor = self.xpathToStr(node, self.xpFillColor, \"#000000\") sFillStyle = self.xpathToStr(node,", "on class %s\"%self.__class__ s += \"\\n--- xpath=%s\" % xpExpr s += \"\\n--- Python", "wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength] , (x, y) , Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='bl' , Color=sFontColor ,", "sEnabled in ['1', 'yes', 'true'] def isSeparator(cls): return False isSeparator = classmethod(isSeparator) def", "a special way to encode coordinates. like: <Coords points=\"985,390 1505,390 1505,440 985,440\"/> or", "be a lambda assert xpExpr[:8] == \"|lambda \", \"Invalid lambda expression %s\"%xpExpr sStartEmpty,", "and computation of font size ltXY = self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node,", "-y+iFontSize/6), Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='tl' , Color=sFontColor) lo.append(obj) return lo def getText(self,", "['1', 'yes', 'true'] def isSeparator(cls): return False isSeparator = classmethod(isSeparator) def __str__(self): return", "print n.serialize() iLARGENEG = -9999 lo = Deco.draw(self, wxh, node) if self._node !=", "do proportional dc.SetFont(wx.Font(24, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") try: iFontSizeX =", "= cfg.get(sSurname, \"xpath\") self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpRadius = cfg.get(sSurname, \"xpath_radius\") self.xpLineWidth =", "sVal.strip() lName = sNames.split(',') for name in lName: name = name.strip().lower() if bNoCase", "__init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) DecoText .__init__(self, cfg, sSurname, xpCtxt)", "subfolder ? # e.g. \"S_Aicha_an_der_Donau_004-03_0005.jpg\" is in folder \"S_Aicha_an_der_Donau_004-03\" try: sDir = sFilePath[:sFilePath.rindex(\"_\")]", "node = %s\" % etree.tostring(node)) else: self.warning(\"No coordinates: node id = %s\" %", "node): sEncodedText = self.xpathToStr(node, self.xpContent, \"\") try: return eval('u\"\\\\u%04x\"' % int(sEncodedText, self.base)) except", "!= node: self._lxy = self._getCoordList(node) self._node = node if self._lxy: sLineColor = self.xpathToStr(node,", "return lo class DecoClusterCircle(DecoREAD): \"\"\" [Cluster] type=DecoClusterCircle xpath=.//Cluster xpath_content=@content xpath_radius=40 xpath_item_lxy=./pg:Coords/@points xpath_LineWidth=\"1\" xpath_FillStyle=\"Transparent\"", "self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrName = cfg.get(sSurname, \"xpath_AttrName\") self.xpAttrValue", "nd = nd.parent try: #number = max(0, int(nd.prop(\"number\")) - 1) number = max(0,", "xpCtxt): self.xpCtxt = xpCtxt def xpathError(self, node, xpExpr, eExcpt, sMsg=\"\"): \"\"\"report an xpath", ", LineColor=sLineColor) lo.append(obj) return lo class DecoClosedPolyLine(DecoPolyLine): \"\"\"A polyline that closes automatically the", "nd and nd.name != \"PAGE\": nd = nd.parent while nd and nd.name !=", "(x,-y), h) lo.append(obj) except Exception, e: self.warning(\"DecoImageBox ERROR: File %s: %s\"%(sFilePath, str(e))) lo.append(", "file This section should contain the following items: x, y, w, h \"\"\"", "self.xpCoords = cfg.get(sSurname, \"xpath_lxy\") def _getCoordList(self, node): sCoords = self.xpathToStr(node, self.xpCoords, \"\") if", "False isSeparator = classmethod(isSeparator) def __str__(self): return \"(Surname=%s xpath==%s)\" % (self.sSurname, self.xpMain) def", "% (sLambdaExpr, repr(sArg)) s = eval(sPythonExpr) else: s = self.xpCtxt.xpathEval(xpExpr) if type(s) ==", "None def __str__(self): s = \"%s=\"%self.__class__ s += \"+(x1=%s y1=%s x2=%s y2=%s)\" %", "+= \"\\n--- XPath ERROR on class %s\"%self.__class__ s += \"\\n--- xpath=%s\" % xpExpr", "sAttrValue: #back to previous value if initialValue == None or initialValue == sAttrValue:", "Deco._s_prev_xpath_error = \"\" Deco._prev_xpath_error_count = 0 iMaxLen = 200 # to truncate the", "as to fit the polygon and the extent of the 'x' character for", "of dictionary Example: parseCustomAttr( \"readingOrder {index:4;} structure {type:catch-word;}\" ) --> { 'readingOrder': [{", "{type:catch-word;}\" ) --> { 'readingOrder': [{ 'index':'4' }], 'structure':[{'type':'catch-word'}] } \"\"\" dic =", "= xpCtxt def xpathError(self, node, xpExpr, eExcpt, sMsg=\"\"): \"\"\"report an xpath error\"\"\" try:", "1) number = max(0, self.xpathToInt(nd, sPageNumberAttr, 1, True) - 1) #maybe we can", "c = globals()[sClass] if type(c) != types.ClassType: raise Exception(\"No such decoration type: '%s'\"%sClass)", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname,", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpLineColor = cfg.get(sSurname,", "sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y+inc),", "ltXY] return (min(lX), max(lY)), (max(lX), min(lY)) class DecoREADTextLine(DecoREAD): \"\"\"A TextLine as defined by", "show the annotation by offset found in the custom attribute \"\"\" def __init__(self,", "wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") del dc return iFontSize, Ex, Ey def draw(self,", "cfg.get(sSurname, \"xpath\") self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpRadius = cfg.get(sSurname, \"xpath_radius\") self.xpLineWidth = cfg.get(sSurname,", "(fA, (xg, yg))) return fA, (xg, yg) def draw(self, wxh, node): \"\"\"draw itself", "sFillColor = self.xpathToStr(node, self.xpFillColor, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") obj = wxh.AddRectangle((x,", "self.xpAttrName = cfg.get(sSurname, \"xpath_AttrName\") self.xpAttrValue = cfg.get(sSurname, \"xpath_AttrValue\") self.dInitialValue = {} self.xpLineColorSlctd =", "#this context may include the declaration of some namespace sEnabled = cfg.get(sSurname, \"enabled\").lower()", "sNames.split(',') for name in lName: name = name.strip().lower() if bNoCase else name.strip() dic[name].append(dicValForName)", "the destination or None on error \"\"\" index,x,y,w,h = None,None,None,None,None sToPageNum = self.xpathToStr(node,", "None) if sAttrName and sAttrValue != None: try: initialValue = self.dInitialValue[node] except KeyError:", "ERROR on class %s\"%self.__class__ s += \"\\n--- xpath=%s\" % xpExpr s += \"\\n---", "cfg.get(sSurname, \"xpath_x2\"), cfg.get(sSurname, \"xpath_y2\") #now get the xpath expressions that let us find", "chunk in lChunk: #things like \"a {x:1\" chunk = chunk.strip() if not chunk:", "200 # to truncate the node serialization s = \"-\"*60 s += \"\\n---", "DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") self.xpFit", "<NAME> - September 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname,", "a given page\"\"\" pass def draw(self, wxh, node): \"\"\"draw the associated decorations, return", "Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class DecoText(DecoBBXYWH): \"\"\"A text", "in ltXY] lY = [_y for _x,_y in ltXY] return (min(lX), max(lY)), (max(lX),", "on error \"\"\" index,x,y,w,h = None,None,None,None,None sToPageNum = self.xpathToStr(node, self.xpAttrToPageNumber , None) if", "sEndEmpty == \"\", \"Missing last '|'\" sArg = self.xpCtxt.xpathEval(xpExprArg)[0] sPythonExpr = \"(%s)(%s)\" %", "def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\")", "% (self.xpX1, self.xpY1, self.xpX2, self.xpY2) return s def draw(self, wxh, node): \"\"\"draw itself", "\"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def beginPage(self, node): \"\"\"called before any sequnce", "x,y,w,h = None, None, None, None bbHighlight = None sToId = self.xpathToStr(node, self.xpAttrToId", "string, got '%s'\"%sKeyVal) sKey = sKey.strip().lower() if bNoCase else sKey.strip() dicValForName[sKey] = sVal.strip()", "def __str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return s def", "\"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def isActionable(self): return True def draw(self, wxh,", "= node #lo = DecoClosedPolyLine.draw(self, wxh, node) #add the text itself x, y", "\"xpath_xTo\") self.xp_yTo = cfg.get(sSurname, \"xpath_yTo\") self.xp_wTo = cfg.get(sSurname, \"xpath_wTo\") self.xp_hTo = cfg.get(sSurname, \"xpath_hTo\")", "a main XPath that select nodes to be decorated in this way self.xpCtxt", "node.prop(sAttrName) #first time self.dInitialValue[node] = initialValue if node.get(sAttrName) == sAttrValue: #back to previous", "or y==None or w==None or h==None: x,y,w,h = None, None, None, None except:", "class\"\"\" c = globals()[sClass] if type(c) != types.ClassType: raise Exception(\"No such decoration type:", "= [] #add the image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef,", "'xy', bShowError=False) try: iFontSize = int(sFit) Ex, Ey = None, None except ValueError:", "found in the custom attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREADTextLine.__init__(self, cfg,", "\"\"\" sPageTag = self.config.getPageTag() sPageNumberAttr = self.config.getPageNumberAttr() number = None x,y,w,h = None,", "self.xpX # for n in node.xpathEval(self.xpX): print n.serialize() iLARGENEG = -9999 lo =", "self.xpathToInt(node, self.xpLineWidth, 1) sFillColor = self.xpathToStr(node, self.xpFillColor, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\")", "self.xpAttrValue = cfg.get(sSurname, \"xpath_AttrValue\") self.dInitialValue = {} self.xpLineColorSlctd = cfg.get(sSurname, \"xpath_LineColor_Selected\") self.xpLineWidthSlctd =", "from collections import defaultdict import glob import logging import random from lxml import", "Exception, e: self.warning(\"DecoImage ERROR: File %s: %s\"%(sFilePath, str(e))) return lo class DecoOrder(DecoBBXYWH): \"\"\"Show", "cfg, sSurname, xpCtxt) self.xpX_Inc = cfg.get(sSurname, \"xpath_x_incr\") #to shift the text self.xpY_Inc =", "sCandidate except ValueError: pass if not os.path.exists(sFilePath): #maybe the image is in a", "= self.xpathToStr(node, self.xpFontColor, 'BLACK') obj = wxh.AddScaledTextBox(txt, (x+x_inc, -y-y_inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor,", "was set, then saved, re-clicking on it wil remove it. del node.attrib[sAttrName] s", "self.xpathToStr(node, self.xpLineColor, \"BLACK\") x, y = int(x + w/2.0), int(y + h/2.0) if", "\"\"\"Show the order with lines \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg,", "node): \"\"\"draw itself using the wx handle return a list of created WX", "given in a certain base, e.g. 10 or 16 \"\"\" def __init__(self, cfg,", "self.xpW, self.xpH = cfg.get(sSurname, \"xpath_w\"), cfg.get(sSurname, \"xpath_h\") self.xpInc = cfg.get(sSurname, \"xpath_incr\") #to increase", "lo = [obj] + lo return lo def act(self, obj, node): \"\"\" return", "XPath expression should return an int on the given node. The XPath expression", "else: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillColor =", "def __str__(self): s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return s def draw(self, wxh,", "DecoUnicodeChar(DecoText): \"\"\"A character encoded in Unicode We assume the unicode index is given", "None, None, None bbHighlight = None sToId = self.xpathToStr(node, self.xpAttrToId , None) if", "self.xpY_Inc, 0, False) txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8)", "cfg.get(sSurname, \"xpath_x\"), cfg.get(sSurname, \"xpath_y\") self.xpW, self.xpH = cfg.get(sSurname, \"xpath_w\"), cfg.get(sSurname, \"xpath_h\") self.xpInc =", "DecoREAD(Deco): \"\"\" READ PageXml has a special way to encode coordinates. like: <Coords", "types, os from collections import defaultdict import glob import logging import random from", "h = self.xpathToInt(ndTo, self.xp_hTo, None) if x==None or y==None or w==None or h==None:", "os.path.join(self.sImageFolder, sDir, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate except ValueError: pass if not", "node) if self._node != node: self._lxy = self._getCoordList(node) self._node = node if self._lxy:", "class DecoImage(DecoBBXYWH): \"\"\"An image \"\"\" # in case the use wants to specify", "index,x,y,w,h = None,None,None,None,None sToPageNum = self.xpathToStr(node, self.xpAttrToPageNumber , None) if sToPageNum: index =", "return -fA, (xg, yg) else: return fA, (xg, yg) assert fA >0 and", "to be decorated in this way self.xpCtxt = xpCtxt #this context may include", "s += \"\\n--- Info: %s\" % sMsg if s == Deco._s_prev_xpath_error: # let's", "min(w,h) / 2 wxh.AddEllipse((x, -y), (iEllipseParam, -iEllipseParam), LineColor=sLineColor, LineWidth=5, FillStyle=\"Transparent\") self.prevX, self.prevY =", "wxh, node) if self._node != node: self._lxy = self._getCoordList(node) self._node = node #lo", "lo = DecoRectangle.draw(self, wxh, node) #add the text itself txt = self.xpathToStr(node, self.xpContent,", "LineColor=None) lo.append(obj) return lo class DecoText(DecoBBXYWH): \"\"\"A text \"\"\" def __init__(self, cfg, sSurname,", "wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") try: iFontSizeX = 24 * abs(x2-x1) /", "sDir = sFilePath[:sFilePath.rindex(\"_\")] sCandidate = os.path.join(self.sImageFolder, sDir, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate", "= Nf else: Nf = random.randrange(iMaxFC) Nl = random.randrange(iMaxFC) iLineWidth = self.xpathToInt(node, self.xpLineWidth,", "= wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) obj = wxh.AddScaledBitmap(img, (x,-y), h) lo.append(obj) except Exception, e: self.warning(\"DecoImageBox", "# maybe we have some pattern?? lCandidate = glob.glob(sFilePath) bKO = True for", "not show any error if self._x2 == iLARGENEG: self._x2 = self.xpathToInt(node, self.xpDfltX2, iLARGENEG)", "nd.name != sPageTag: nd = nd.parent try: #number = max(0, int(nd.prop(\"number\")) - 1)", "else: iFontSize = min(iFontSizeX, iFontSizeY) dc.SetFont(wx.Font(iFontSize, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\")", "-self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoClickableRectangleSetAttr(DecoBBXYWH): \"\"\"A rectangle clicking", "= self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: try: img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) obj =", "wxh.AddRectangle((x, -y), (20, 20), # LineWidth=iLineWidth, # LineColor=sLineColor, # FillColor=sFillColor, # FillStyle=sFillStyle) lo.append(obj)", "AttributeError: s = s[0] return s except Exception, e: if bShowError: self.xpathError(node, xpExpr,", "#things like: (\"a,b\", \"x:1 ; y:2\") except Exception: raise ValueError(\"Expected a '{' in", "file? (Transkribus style) sUrl = node.getroottree().docinfo.URL.decode('utf-8') # py2 ... for sPrefix in [\"file://\",", "ltXY, txt, Family=wx.FONTFAMILY_TELETYPE): \"\"\" compute the font size so as to fit the", "self.xpCtxt.xpathEval(xpExpr) except Exception, e: self.xpathError(node, xpExpr, e, \"xpathEval return None\") return None def", "Ex, Ey def draw(self, wxh, node): \"\"\"draw itself using the wx handle return", "BackgroundColor=sBackgroundColor) lo.append(obj) except KeyError: pass except KeyError: pass return lo class DecoPolyLine(DecoREAD): \"\"\"A", "% (self.xpCoords) return s def draw(self, wxh, node): \"\"\"draw itself using the wx", "def __str__(self): return \"--------\" def isSeparator(self): return True def setXPathContext(self, xpCtxt): pass class", "self.xpX # for n in node.xpathEval(self.xpX): print n.serialize() lo = DecoREAD.draw(self, wxh, node)", "cfg.get(sSurname, \"xpath_LineColor\") self._node = None def __str__(self): s = \"%s=\"%self.__class__ s += \"+(x1=%s", "the 'x' character for this font size return iFontSize, ExtentX, ExtentY \"\"\" (x1,", "= DecoREAD.draw(self, wxh, node) if self._node != node: self._lxy = self._getCoordList(node) self._node =", "of the attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt)", "sDefault def xpathEval(self, node, xpExpr): \"\"\" evaluate the xpath expression return None on", "cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") #cached values self._node = None self._lxy =", "+ Ex * iOffset y = -y0+iFontSize/6 obj = wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength] , (x, y)", "Ex, Ey = self._getFontSize(node, ltXY, txt , Family=wx.FONTFAMILY_TELETYPE) dCustom = self.parseCustomAttr(node.get(\"custom\"), bNoCase=True) try:", "[] class DecoBBXYWH(Deco): \"\"\"A decoration with a bounding box defined by X,Y for", "the wx handle return a list of created WX objects\"\"\" # print node.serialize()", "\"eval_xpath_y2\") self.xpDfltX2, self.xpDfltY2 = cfg.get(sSurname, \"xpath_x2_default\"), cfg.get(sSurname, \"xpath_y2_default\") #now get the xpath expressions", "(xg, yg) = self.getArea_and_CenterOfMass(lxy) r = self.xpathToInt(ndItem, self.xpRadius, 1) self._laxyr.append( (fA, xg, yg,", "\"xpath_FillStyle\") self.xpAttrName = cfg.get(sSurname, \"xpath_AttrName\") self.xpAttrValue = cfg.get(sSurname, \"xpath_AttrValue\") self.dInitialValue = {} self.xpLineColorSlctd", "handle return a list of created WX objects\"\"\" lo = [] #add the", "y = self._lxy[0] x_inc = self.xpathToInt(node, self.xpX_Inc, 0, False) y_inc = self.xpathToInt(node, self.xpY_Inc,", "coords are bad: '%s' -> '%s'\" % ( self.xpCoords, sCoords)) raise e return", "here and return a dictionary of list of dictionary Example: parseCustomAttr( \"readingOrder {index:4;}", "\"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") def __str__(self): s =", "cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self):", "sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') # Position and computation of font size ltXY", "XPath context \"\"\" self.sSurname = sSurname def __str__(self): return \"--------\" def isSeparator(self): return", "Exception: raise ValueError(\"Expected a '{' in '%s'\"%chunk) #the dictionary for that name dicValForName", "nd and nd.name != sPageTag: nd = nd.parent try: #number = max(0, int(nd.prop(\"number\"))", "sPrefix in [\"file://\", \"file:/\"]: if sUrl[0:len(sPrefix)] == sPrefix: sLocalDir = os.path.dirname(sUrl[len(sPrefix):]) sDir,_ =", "lX = [_x for _x,_y in ltXY] lY = [_y for _x,_y in", "= wxh.AddRectangle((x, -y), (20, 20), # LineWidth=iLineWidth, # LineColor=sLineColor, # FillColor=sFillColor, # FillStyle=sFillStyle)", "lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sAttrName = self.xpathToStr(node, self.xpAttrName ,", "= self.config.getPageTag() sPageNumberAttr = self.config.getPageNumberAttr() number = None x,y,w,h = None, None, None,", "xpath=%s\" % xpExpr s += \"\\n--- Python Exception=%s\" % str(eExcpt) if sMsg: s", "special way to encode coordinates. like: <Coords points=\"985,390 1505,390 1505,440 985,440\"/> or <Baseline", "is in a subfolder ? # e.g. \"S_Aicha_an_der_Donau_004-03_0005.jpg\" is in folder \"S_Aicha_an_der_Donau_004-03\" try:", "<filename>TranskribusDU/visu/deco.py<gh_stars>10-100 \"\"\" A class that reflect a decoration to be made on certain", "ltXY[0] _ldLabel = dCustom[self.xpathToStr(node, self.xpLabel, \"\").lower()] for _dLabel in _ldLabel: try: iOffset =", "__init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def", "a given page\"\"\" pass def endPage(self, node): \"\"\"called before any sequnce of draw", "</TextEquiv> </TextLine> \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpContent", "x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y+inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0,", "None sToId = self.xpathToStr(node, self.xpAttrToId , None) if sToId: ln = self.xpathEval(node.doc.getroot(), '//*[@id=\"%s\"]'%sToId.strip())", "self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) for (x1, y1), (x2, y2) in", "in self._laxyr: #draw a circle sFillColor = self.lsFillColor[Nf % iMaxFC] if self.lsLineColor: sLineColor", "= self._coordList_to_BB(ltXY) obj = wxh.AddScaledText(txt, (x, -y+iFontSize/6), Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='tl' ,", "section name in the config file! xpCtxt is an XPath context \"\"\" self.sSurname", "isSeparator = classmethod(isSeparator) def __str__(self): return \"(Surname=%s xpath==%s)\" % (self.sSurname, self.xpMain) def getDecoClass(cls,", "y2) \"\"\" lX = [_x for _x,_y in ltXY] lY = [_y for", "\"\"\" return lo class DecoLink(Deco): \"\"\"A link from x1,y1 to x2,y2 \"\"\" def", "= wxh.AddScaledBitmap(img, (x,-y), h) lo.append(obj) except Exception, e: self.warning(\"DecoImageBox ERROR: File %s: %s\"%(sFilePath,", "xpCtxt is an XPath context \"\"\" self.sSurname = sSurname self.xpMain = cfg.get(sSurname, \"xpath\")", "s[0] #should be an attribute value return Deco.toInt(s) except Exception, e: if bShowError:", "def setEncoding(s): global sEncoding sEncoding = s class DecoSeparator: \"\"\" this is not", "s = Deco.__str__(self) s += \"+(x=%s y=%s w=%s h=%s)\" % (self.xpX, self.xpY, self.xpW,", "this syntax here and return a dictionary of list of dictionary Example: parseCustomAttr(", "self._y2 = self.xpathToInt(node, xpY2, iLARGENEG, False) #do not show any error if self._y2", "node) x,y,w,h,inc = self.runXYWHI(node) sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue = self.xpathToStr(node,", "xpCtxt #this context may include the declaration of some namespace sEnabled = cfg.get(sSurname,", "node.xpathEval(self.xpX): print n.serialize() iLARGENEG = -9999 lo = Deco.draw(self, wxh, node) if self._node", "__str__(self): s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return s def draw(self, wxh, node):", "Family=wx.FONTFAMILY_TELETYPE) dCustom = self.parseCustomAttr(node.get(\"custom\"), bNoCase=True) try: x0, y0 = ltXY[0] _ldLabel = dCustom[self.xpathToStr(node,", "cfg.get(sSurname, \"xpath_content\") self.xpRadius = cfg.get(sSurname, \"xpath_radius\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillStyle = cfg.get(sSurname,", "(max(lX), min(lY)) class DecoREADTextLine(DecoREAD): \"\"\"A TextLine as defined by the PageXml format of", "= cfg.get(sSurname, \"xpath_LineColor\") self.xpBackgroundColor = cfg.get(sSurname, \"xpath_background_color\") def draw(self, wxh, node): \"\"\" draw", "= self.xpathToStr(node, self.xpFillColor, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") obj = wxh.AddRectangle((x, -y),", "* iOffset y = -y0+iFontSize/6 obj = wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength] , (x, y) , Size=iFontSize", "pass except KeyError: pass return lo class DecoPolyLine(DecoREAD): \"\"\"A polyline along x1,y1,x2,y2, ...,xn,yn", "folder \"S_Aicha_an_der_Donau_004-03\" try: sDir = sFilePath[:sFilePath.rindex(\"_\")] sCandidate = os.path.join(self.sImageFolder, sDir, sFilePath) if os.path.exists(sCandidate):", "text self.xpY_Inc = cfg.get(sSurname, \"xpath_y_incr\") #to shift the text def draw(self, wxh, node):", "except Exception as e: logging.error(\"ERROR: polyline coords are bad: '%s' -> '%s'\" %", "= len(self.lsFillColor) iMaxLC = len(self.lsLineColor) if False: Nf = DecoClusterCircle.count Nl = Nf", "s): try: return int(s) except ValueError: return int(round(float(s))) toInt = classmethod(toInt) def xpathToInt(self,", "e.g. 10 or 16 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoText.__init__(self, cfg, sSurname,", "font size ltXY = self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt ,", "self.xpathToInt(ndItem, self.xpRadius, 1) self._laxyr.append( (fA, xg, yg, r) ) self._node = node if", "None def __str__(self): s = Deco.__str__(self) s += \"+(x=%s y=%s w=%s h=%s)\" %", "# print node.serialize() # print self.xpX # for n in node.xpathEval(self.xpX): print n.serialize()", "as default value\"%sDefault) return sDefault def xpathEval(self, node, xpExpr): \"\"\" evaluate the xpath", "= None def __str__(self): s = Deco.__str__(self) s += \"+(x=%s y=%s w=%s h=%s)\"", "PageXml has a special way to encode coordinates. like: <Coords points=\"985,390 1505,390 1505,440", "self.xpY1, self.xpEvalX2, self.xpEvalY2) return s def draw(self, wxh, node): \"\"\"draw itself using the", "= self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\")", "= wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) try: if h > 0: obj = wxh.AddScaledBitmap(img, (x,-y), h)", "lo def act(self, obj, node): \"\"\" Toggle the attribute value \"\"\" s =", "sIds.split(): l = self.xpathEval(ndPage, './/*[@id=\"%s\"]'%sId) ndItem = l[0] lxy = self._getCoordList(ndItem) fA, (xg,", "self.xpHRef, \"\") if sFilePath: if self.sImageFolder: sCandidate = os.path.join(self.sImageFolder, sFilePath) if os.path.exists(sCandidate): sFilePath", "handle return a list of created WX objects\"\"\" lo = DecoRectangle.draw(self, wxh, node)", "cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self):", ") self._node = node if self._laxyr: iMaxFC = len(self.lsFillColor) iMaxLC = len(self.lsLineColor) if", "= self._getFontSize(node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE) # x, y = ltXY[0] (x, _y1), (_x2,", "'@%s := \"%s\"'%(sAttrName,sAttrValue) return s class DecoClickableRectangleJump(DecoBBXYWH): \"\"\"A rectangle clicking on it jump", "node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE): \"\"\" compute the font size so as to fit", "sAttrValue != None: if node.prop(sAttrName) == sAttrValue: sLineColor = self.xpathToStr(node, self.xpLineColorSlctd, \"#000000\") iLineWidth", "self.xpAttrToId , None) if sToId: ln = self.xpathEval(node.doc.getroot(), '//*[@id=\"%s\"]'%sToId.strip()) if ln: #find the", "= self.xpathToStr(node, self.xpFit, 'xy', bShowError=False) try: iFontSize = int(sFit) Ex, Ey = None,", "sSurname, xpCtxt) self.base = int(cfg.get(sSurname, \"code_base\")) def getText(self, wxh, node): sEncodedText = self.xpathToStr(node,", "cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontColor =", "in the toolbar \"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a", "node The XPath expression should return a scalar or a one-node nodeset On", "us find the rectangle line and fill colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor", "s += DecoBBXYWH.__str__(self) return s def beginPage(self, node): \"\"\"called before any sequnce of", "except Exception, e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToStr return %s as default", "in [\"file://\", \"file:/\"]: if sUrl[0:len(sPrefix)] == sPrefix: sLocalDir = os.path.dirname(sUrl[len(sPrefix):]) sDir,_ = os.path.splitext(os.path.basename(sUrl))", "self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y+inc), Size=iFontSize, Family=wx.ROMAN,", "os.path.splitext(os.path.basename(sUrl)) sCandidate = os.path.abspath(os.path.join(sLocalDir, sDir, sFilePath)) if os.path.exists(sCandidate): sFilePath = sCandidate print(sFilePath) break", "style syntax. We parse this syntax here and return a dictionary of list", "\"\"\" draw itself using the wx handle return a list of created WX", "of text: cannot compute font size along X axis\") iFontSizeX = 8 iFontSizeY", "\"--------\" def isSeparator(self): return True def setXPathContext(self, xpCtxt): pass class Deco: \"\"\"A general", "obj, node): \"\"\" Toggle the attribute value \"\"\" s = \"do nothing\" sAttrName", "!= node: self._laxyr = [] #need to go thru each item ndPage =", "[] #add the image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\")", "self._x2 == iLARGENEG: self._x2 = self.xpathToInt(node, self.xpDfltX2, iLARGENEG) xpY2 = self.xpathToStr(node, self.xpEvalY2, '\"\"')", "sToPageNum = self.xpathToStr(node, self.xpAttrToPageNumber , None) if sToPageNum: index = int(sToPageNum) - 1", "PageXML custom attribute \"\"\" @classmethod def parseCustomAttr(cls, s, bNoCase=True): \"\"\" The custom attribute", ", None) if sToId: ln = self.xpathEval(node.doc.getroot(), '//*[@id=\"%s\"]'%sToId.strip()) if ln: #find the page", "else: if not sAttrValue: del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName,", "self.xpathEval(node, self.xpContent)[0] for sId in sIds.split(): l = self.xpathEval(ndPage, './/*[@id=\"%s\"]'%sId) ndItem = l[0]", "cfg.get(sSurname, \"xpath_lxy\") def _getCoordList(self, node): sCoords = self.xpathToStr(node, self.xpCoords, \"\") if not sCoords:", "= max(0, int(nd.prop(\"number\")) - 1) number = max(0, self.xpathToInt(nd, sPageNumberAttr, 1, True) -", "self._lxy = None def __str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords)", "wxh, node): \"\"\"draw itself using the wx handle return a list of created", "int(s) except ValueError: return int(round(float(s))) toInt = classmethod(toInt) def xpathToInt(self, node, xpExpr, iDefault=0,", "lines \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpLineColor =", "DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions that let us find", "else: Nf = random.randrange(iMaxFC) Nl = random.randrange(iMaxFC) iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillStyle", "\"xpath_x\"), cfg.get(sSurname, \"xpath_y\") self.xpW, self.xpH = cfg.get(sSurname, \"xpath_w\"), cfg.get(sSurname, \"xpath_h\") self.xpInc = cfg.get(sSurname,", "self._lxy[1:]): #draw a line obj = wxh.AddLine( [(x1, -y1), (x2, -y2)] , LineWidth=iLineWidth", "colors self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\")", "raise ValueError(\"Expected a '{' in '%s'\"%chunk) #the dictionary for that name dicValForName =", "= sCandidate print(sFilePath) break if not os.path.exists(sFilePath): # maybe we have some pattern??", "= cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xp_xTo = cfg.get(sSurname, \"xpath_xTo\") self.xp_yTo =", "sEncodedText)) return \"\" class DecoImageBox(DecoRectangle): \"\"\"An image with a box around it \"\"\"", "\"\"\" [Cluster] type=DecoClusterCircle xpath=.//Cluster xpath_content=@content xpath_radius=40 xpath_item_lxy=./pg:Coords/@points xpath_LineWidth=\"1\" xpath_FillStyle=\"Transparent\" LineColors=\"BLUE SIENNA YELLOW ORANGE", "sAttrValue = self.xpathToStr(node, self.xpAttrValue, None) if sAttrName and sAttrValue != None: if node.prop(sAttrName)", "\"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyleSlctd, \"Solid\") else: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth", "\"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc =", "b def isActionable(self): return False def setXPathContext(self, xpCtxt): self.xpCtxt = xpCtxt def xpathError(self,", "lsLineColor = \", self.lsLineColor print \"DecoClusterCircle lsFillColor = \", self.lsFillColor def __str__(self): s", "% sMsg if s == Deco._s_prev_xpath_error: # let's not overload the console. return", "like \"a {x:1\" chunk = chunk.strip() if not chunk: continue try: sNames, sValues", "<Baseline points=\"985,435 1505,435\"/> <TextEquiv> <Unicode>Salgadinhos 12</Unicode> </TextEquiv> </TextLine> \"\"\" def __init__(self, cfg, sSurname,", "s def _getFontSize(self, node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE): \"\"\" compute the font size so", "lo class DecoClickableRectangleSetAttr(DecoBBXYWH): \"\"\"A rectangle clicking on it add/remove an attribute the rectangle", "= self.xpathToInt(node, self.xpLineWidth, 1) for (x1, y1), (x2, y2) in zip(self._lxy, self._lxy[1:]): #draw", "txt, Family=wx.FONTFAMILY_TELETYPE) # x, y = ltXY[0] (x, _y1), (_x2, y) = self._coordList_to_BB(ltXY)", "or initialValue == sAttrValue: #very special case: when an attr was set, then", "section should contain the following items: x, y, w, h \"\"\" Deco.__init__(self, cfg,", "DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue", "20), # LineWidth=iLineWidth, # LineColor=sLineColor, # FillColor=sFillColor, # FillStyle=sFillStyle) lo.append(obj) \"\"\" lo =", "= self.xpathEval(ndPage, './/*[@id=\"%s\"]'%sId) ndItem = l[0] lxy = self._getCoordList(ndItem) fA, (xg, yg) =", "number ndTo = nd = ln[0] #while nd and nd.name != \"PAGE\": nd", "= '@%s := \"%s\"'%(sAttrName,sAttrValue) return s class DecoClickableRectangleJump(DecoBBXYWH): \"\"\"A rectangle clicking on it", "DecoLine(Deco): \"\"\"A line from x1,y1 to x2,y2 \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "given page\"\"\" pass def draw(self, wxh, node): \"\"\"draw the associated decorations, return the", "s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def draw(self, wxh, node): \"\"\"draw", "be made on certain XML node using WX \"\"\" import types, os from", "_coordList_to_BB(self, ltXY): \"\"\" return (x1, y1), (x2, y2) \"\"\" lX = [_x for", "sSurname, xpCtxt): \"\"\" cfg is a config file sSurname is the decoration surname", "def setEnabled(self, b=True): self.bEnabled = b return b def isActionable(self): return False def", "except: sNode = str(node) if len(sNode) > iMaxLen: sNode = sNode[:iMaxLen] + \"...\"", "except Exception, e: self.warning(\"DecoImageBox ERROR: File %s: %s\"%(sFilePath, str(e))) lo.append( DecoRectangle.draw(self, wxh, node)", "DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__", "\"\"\"get the X,Y values for a node and put them in cache\"\"\" if", "#now get the xpath expressions that let us find the rectangle line and", ".... xn,yn Example of config: [TextLine] type=DecoPolyLine xpath=.//TextLine/Coords xpath_lxy=@points xpath_LineColor=\"RED\" xpath_FillStyle=\"Solid\" <NAME> -", "return self.sSurname def getMainXPath(self): return self.xpMain def isEnabled(self): return self.bEnabled def setEnabled(self, b=True):", "[] #add the text itself txt = self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor,", "sMsg): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_warning except AttributeError: Deco._s_prev_warning = \"\" Deco._warning_count", "and xg >0 and yg >0, \"%s\\t%s\"%(lXY (fA, (xg, yg))) return fA, (xg,", "lo.append(obj) return lo class DecoClosedPolyLine(DecoPolyLine): \"\"\"A polyline that closes automatically the shape <NAME>", "lCoord: lCoord.append(lCoord[0]) return lCoord class DecoTextPolyLine(DecoPolyLine, DecoText): \"\"\"A polyline that closes automatically the", "False) y_inc = self.xpathToInt(node, self.xpY_Inc, 0, False) txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize", "return [(0,0)] try: ltXY = [] for _sPair in sCoords.split(' '): (sx, sy)", "node: self._x1 = self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) self._x2 =", "\"Solid\") obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo.append(obj) return", "cfg.get(sSurname, \"xpath_FillStyle\") self.lsLineColor = cfg.get(sSurname, \"LineColors\").split() self.lsFillColor = cfg.get(sSurname, \"FillColors\").split() #cached values self._node", "surname and the section name in the config file This section should contain", "= os.path.splitext(os.path.basename(sUrl)) sCandidate = os.path.abspath(os.path.join(sLocalDir, sDir, sFilePath)) if os.path.exists(sCandidate): sFilePath = sCandidate print(sFilePath)", "\"+(coords=%s)\" % (self.xpCoords) return s def getArea_and_CenterOfMass(self, lXY): \"\"\" https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone return A, (Xg,", "FillColor=sFillColor, FillStyle=sFillStyle) \"\"\" return lo class DecoLink(Deco): \"\"\"A link from x1,y1 to x2,y2", "created WX objects\"\"\" lo = DecoRectangle.draw(self, wxh, node) #add the text itself txt", "serialization s = \"-\"*60 s += \"\\n--- XPath ERROR on class %s\"%self.__class__ s", "xpath_radius=40 xpath_item_lxy=./pg:Coords/@points xpath_LineWidth=\"1\" xpath_FillStyle=\"Transparent\" LineColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" FillColors=\"BLUE SIENNA YELLOW", "return self.bEnabled def setEnabled(self, b=True): self.bEnabled = b return b def isActionable(self): return", "created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor =", "the rectangle color is indicative of the presence/absence of the attribute \"\"\" def", "!= \"PAGE\": nd = nd.parent while nd and nd.name != sPageTag: nd =", "and the extent of the 'x' character for this font size return iFontSize,", "except AttributeError: Deco._s_prev_warning = \"\" Deco._warning_count = 0 # if sMsg != Deco._s_prev_warning", "self.xpathToInt(node, self.xpDfltY2, iLARGENEG) self._node = node if self._x1 != iLARGENEG and self._y1 !=", "is a configuration object sSurname is the surname of the decoration and the", "node) ) return lo class DecoImage(DecoBBXYWH): \"\"\"An image \"\"\" # in case the", "= self.runXYWHI(node) sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue = self.xpathToStr(node, self.xpAttrValue, None)", "YELLOW ORANGE RED GREEN\" FillColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" enabled=1 \"\"\" count", "#import cStringIO import wx sEncoding = \"utf-8\" def setEncoding(s): global sEncoding sEncoding =", "'|'\" sArg = self.xpCtxt.xpathEval(xpExprArg)[0] sPythonExpr = \"(%s)(%s)\" % (sLambdaExpr, repr(sArg)) s = eval(sPythonExpr)", "\"\"\"draw itself using the wx handle return a list of created WX objects\"\"\"", "else: node.set(sAttrName, initialValue) s = '@%s := \"%s\"'%(sAttrName,initialValue) else: if not sAttrValue: del", "sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize = cfg.get(sSurname,", "associated class\"\"\" c = globals()[sClass] if type(c) != types.ClassType: raise Exception(\"No such decoration", "-self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoREAD(Deco): \"\"\" READ PageXml", "%s\" % etree.tostring(node)) else: self.warning(\"No coordinates: node id = %s\" % node.get(\"id\")) return", "which are the area and the coordinates (float) of the center of mass", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) #now get the", "= s[0].text except AttributeError: s = s[0] return s except Exception, e: if", "self.xpathToStr(node, self.xpFillStyle, \"Solid\") for (_a, x, y, r) in self._laxyr: #draw a circle", "the text itself txt = self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') #", "__str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def beginPage(self, node): \"\"\"called", "(self._x2, -self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoClickableRectangleSetAttr(DecoBBXYWH): \"\"\"A rectangle", "== \"|lambda \", \"Invalid lambda expression %s\"%xpExpr sStartEmpty, sLambdaExpr, xpExprArg, sEndEmpty = xpExpr.split('|')", "= self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor,", "self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try: s = s[0].text except AttributeError: s =", "\"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return s def draw(self, wxh, node): \"\"\"draw itself using", "necessary xpX2 = self.xpathToStr(node, self.xpEvalX2, '\"\"') self._x2 = self.xpathToInt(node, xpX2, iLARGENEG, False) #do", "one-node nodeset On error, return the default int value \"\"\" try: # s", "if h > 0: obj = wxh.AddScaledBitmap(img, (x,-y), h) else: obj = wxh.AddScaledBitmap(img,", "class DecoClosedPolyLine(DecoPolyLine): \"\"\"A polyline that closes automatically the shape <NAME> - September 2016", "\"a {x:1\" chunk = chunk.strip() if not chunk: continue try: sNames, sValues =", "expression must be evaluated twice self.xpEvalX2, self.xpEvalY2 = cfg.get(sSurname, \"eval_xpath_x2\"), cfg.get(sSurname, \"eval_xpath_y2\") self.xpDfltX2,", "self.xpEvalX2, self.xpEvalY2 = cfg.get(sSurname, \"eval_xpath_x2\"), cfg.get(sSurname, \"eval_xpath_y2\") self.xpDfltX2, self.xpDfltY2 = cfg.get(sSurname, \"xpath_x2_default\"), cfg.get(sSurname,", "and self._y1 != iLARGENEG and self._x2 != iLARGENEG and self._y2 != iLARGENEG: sLineColor", "if self.sImageFolder: sCandidate = os.path.join(self.sImageFolder, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate else: #", "= cfg.get(sSurname, \"xpath_FillColor_Selected\") self.xpFillStyleSlctd = cfg.get(sSurname, \"xpath_FillStyle_Selected\") def __str__(self): s = \"%s=\"%self.__class__ s", "None, None, None, None bbHighlight = None sToId = self.xpathToStr(node, self.xpAttrToId , None)", "self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt , Family=wx.FONTFAMILY_TELETYPE) dCustom = self.parseCustomAttr(node.get(\"custom\"),", "DecoClickableRectangleJumpToPage(DecoBBXYWH): \"\"\"A rectangle clicking on it jump to a page \"\"\" def __init__(self,", "self.xpathToStr(node, self.xpContent, \"\") try: return eval('u\"\\\\u%04x\"' % int(sEncodedText, self.base)) except ValueError: logging.error(\"DecoUnicodeChar: ERROR:", "items: x, y, w, h \"\"\" Deco.__init__(self, cfg, sSurname, xpCtxt) #now get the", "iFontSizeX = 24 * abs(x2-x1) / Ex / len(txt) except: self.warning(\"absence of text:", "self.xpFillStyleSlctd, \"Solid\") else: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1)", "value \"\"\" s = \"do nothing\" sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue", "def isActionable(self): return False def setXPathContext(self, xpCtxt): self.xpCtxt = xpCtxt def xpathError(self, node,", "24 * abs(y2-y1) / Ey if sFit == \"x\": iFontSize = iFontSizeX elif", "and height self._node = None def __str__(self): s = Deco.__str__(self) s += \"+(x=%s", "AttributeError: s = s[0] #should be an attribute value return Deco.toInt(s) except Exception,", "= -y0+iFontSize/6 obj = wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength] , (x, y) , Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE ,", "b=True): self.bEnabled = b return b def isActionable(self): return False def setXPathContext(self, xpCtxt):", "self.xpathToInt(node, self.xpX_Inc, 0, False) y_inc = self.xpathToInt(node, self.xpY_Inc, 0, False) txt = self.xpathToStr(node,", "LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoClosedPolyLine(DecoPolyLine): \"\"\"A polyline that closes automatically", "-y), r, LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) # obj = wxh.AddRectangle((x, -y), (20, 20),", "order with lines \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt)", "...,xn,yn or x1,y1 x2,y2 .... xn,yn Example of config: [TextLine] type=DecoPolyLine xpath=.//TextLine/Coords xpath_lxy=@points", "cfg.jl_hack_cfg #HACK def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def", "'): (sx, sy) = _sPair.split(',') ltXY.append((Deco.toInt(sx), Deco.toInt(sy))) except Exception as e: logging.error(\"ERROR: polyline", "xpExpr, e, \"xpathToInt return %d as default value\"%iDefault) return iDefault def xpathToStr(self, node,", "self.xpLineColor, \"BLACK\") x, y = int(x + w/2.0), int(y + h/2.0) if self.bInit:", "return s def getArea_and_CenterOfMass(self, lXY): \"\"\" https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone return A, (Xg, Yg) which are", "\"xpath_LineColor\") self._node = None def __str__(self): s = \"%s=\"%self.__class__ s += \"+(x1=%s y1=%s", "= random.randrange(iMaxFC) iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") for", "#cached values self._node = None self._laxyr = None print \"DecoClusterCircle lsLineColor = \",", "= defaultdict(list) s = s.strip() lChunk = s.split('}') if lChunk: for chunk in", "jump to a page \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname,", "lo = Deco.draw(self, wxh, node) if self._node != node: self._x1 = self.xpathToInt(node, self.xpX1,", "del dc return iFontSize, Ex, Ey def draw(self, wxh, node): \"\"\"draw itself using", "\"xpath_ToId\") self.config = cfg.jl_hack_cfg #HACK def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self)", "iTerm * (xprev+x) ySum += iTerm * (yprev+y) xprev, yprev = x, y", "int(sEncodedText, self.base)) except ValueError: logging.error(\"DecoUnicodeChar: ERROR: base=%d code=%s\"%(self.base, sEncodedText)) return \"\" class DecoImageBox(DecoRectangle):", "wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class DecoUnicodeChar(DecoText): \"\"\"A character encoded in Unicode", "continue try: sNames, sValues = chunk.split('{') #things like: (\"a,b\", \"x:1 ; y:2\") except", "0.0: raise ValueError(\"surface == 0.0\") fA = fA / 2 xg, yg =", "= xSum/6/fA, ySum/6/fA if fA <0: return -fA, (xg, yg) else: return fA,", "self._x = self.xpathToInt(node, self.xpX, 1) self._y = self.xpathToInt(node, self.xpY, 1) self._w = self.xpathToInt(node,", "sLineColor = sFillColor obj = wxh.AddCircle((x, -y), r, LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) #", "default value if necessary xpX2 = self.xpathToStr(node, self.xpEvalX2, '\"\"') self._x2 = self.xpathToInt(node, xpX2,", "nd = nd.parent while nd and nd.name != sPageTag: nd = nd.parent try:", "[{ 'index':'4' }], 'structure':[{'type':'catch-word'}] } \"\"\" dic = defaultdict(list) s = s.strip() lChunk", "\"\"\" lX = [_x for _x,_y in ltXY] lY = [_y for _x,_y", "self.xpEvalX2, self.xpEvalY2) return s def draw(self, wxh, node): \"\"\"draw itself using the wx", "attribute value return Deco.toInt(s) except Exception, e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToInt", "self.xpFontColor, 'BLACK') # Position and computation of font size ltXY = self._getCoordList(node) iFontSize,", "obj = wxh.AddRectangle((x, -y), (20, 20), # LineWidth=iLineWidth, # LineColor=sLineColor, # FillColor=sFillColor, #", "1) #maybe we can also indicate the precise arrival point? if self.xp_xTo and", "Info: %s\" % sMsg if s == Deco._s_prev_xpath_error: # let's not overload the", "= node.xpath(\"ancestor::*[local-name()='Page']\")[0] sIds = self.xpathEval(node, self.xpContent)[0] for sId in sIds.split(): l = self.xpathEval(ndPage,", "structure {type:catch-word;}\" ) --> { 'readingOrder': [{ 'index':'4' }], 'structure':[{'type':'catch-word'}] } \"\"\" dic", "def __init__(self, cfg, sSurname, xpCtxt): DecoREADTextLine.__init__(self, cfg, sSurname, xpCtxt) self.xpLabel = cfg.get(sSurname, \"xpath_label\")", "= self.xpathToStr(node, self.xpBackgroundColor, \"#000000\") # Position and computation of font size ltXY =", "sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") obj = wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor,", "of draw for a given page\"\"\" self.bInit = False def draw(self, wxh, node):", "etree.tostring(node) except: sNode = str(node) if len(sNode) > iMaxLen: sNode = sNode[:iMaxLen] +", "\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor,", "= cfg.get(sSurname, \"xpath_x\"), cfg.get(sSurname, \"xpath_y\") self.xpW, self.xpH = cfg.get(sSurname, \"xpath_w\"), cfg.get(sSurname, \"xpath_h\") self.xpInc", "return lo def act(self, obj, node): \"\"\" return the page number of the", "node.xpathEval(self.xpX): print n.serialize() lo = DecoREAD.draw(self, wxh, node) if self._node != node: self._lxy", "lCoord.append(lCoord[0]) return lCoord class DecoTextPolyLine(DecoPolyLine, DecoText): \"\"\"A polyline that closes automatically the shape", "== types.ListType: try: s = s[0].text except AttributeError: s = s[0] #should be", "self._node = None def __str__(self): s = \"%s=\"%self.__class__ s += \"+(x1=%s y1=%s x2=%s", "pass return lo class DecoPolyLine(DecoREAD): \"\"\"A polyline along x1,y1,x2,y2, ...,xn,yn or x1,y1 x2,y2", "s def draw(self, wxh, node): \"\"\"draw itself using the wx handle return a", "len(lXY) < 2: raise ValueError(\"Only one point: polygon area is undefined.\") fA =", "(self._x, self._y, self._w, self._h, self._inc) class DecoRectangle(DecoBBXYWH): \"\"\"A rectangle \"\"\" def __init__(self, cfg,", "_sPair in sCoords.split(' '): (sx, sy) = _sPair.split(',') ltXY.append((Deco.toInt(sx), Deco.toInt(sy))) except Exception as", "size ltXY = self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE) #", "\"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') obj =", "l = self.xpathEval(ndPage, './/*[@id=\"%s\"]'%sId) ndItem = l[0] lxy = self._getCoordList(ndItem) fA, (xg, yg)", "sFillColor = self.xpathToStr(node, self.xpFillColorSlctd, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyleSlctd, \"Solid\") else: sLineColor =", "sMsg: s += \"\\n--- Info: %s\" % sMsg if s == Deco._s_prev_xpath_error: #", "= self.xpathToStr(node, self.xpFontColor, 'BLACK') sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") sBackgroundColor = self.xpathToStr(node, self.xpBackgroundColor,", "itself x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: try: img", "link from x1,y1 to x2,y2 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg,", "a decoration to be made on certain XML node using WX \"\"\" import", "= cfg.get(sSurname, \"xpath_label\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpBackgroundColor = cfg.get(sSurname, \"xpath_background_color\") def draw(self,", "self.lsFillColor def __str__(self): s = \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return s", "and self._x2 != iLARGENEG and self._y2 != iLARGENEG: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\")", "decoration with a bounding box defined by X,Y for its top-left corner and", "X,Y for its top-left corner and width/height. xpX, xpY, xpW, xpH are scalar", "use wants to specify it via the menu sImageFolder = None def __init__(self,", "given page\"\"\" self.bInit = False def draw(self, wxh, node): \"\"\"draw itself using the", "is a config file sSurname is the decoration surname and the section name", "None def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname,", "None except: pass return number,x,y,w,h class DecoClickableRectangleJumpToPage(DecoBBXYWH): \"\"\"A rectangle clicking on it jump", "of draw for a given page\"\"\" pass def draw(self, wxh, node): \"\"\"draw the", "self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize = cfg.get(sSurname, \"xpath_font_size\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") def", "a comma-separated string, got '%s'\"%sKeyVal) sKey = sKey.strip().lower() if bNoCase else sKey.strip() dicValForName[sKey]", "= cfg.get(sSurname, \"xpath_background_color\") def draw(self, wxh, node): \"\"\" draw itself using the wx", "def setXPathContext(self, xpCtxt): self.xpCtxt = xpCtxt def xpathError(self, node, xpExpr, eExcpt, sMsg=\"\"): \"\"\"report", "the wx handle return a list of created WX objects\"\"\" DecoClusterCircle.count = DecoClusterCircle.count", "self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillColor = self.xpathToStr(node, self.xpFillColor, \"#000000\") sFillStyle", "= cfg.get(sSurname, \"xpath_wTo\") self.xp_hTo = cfg.get(sSurname, \"xpath_hTo\") self.xpAttrToId = cfg.get(sSurname, \"xpath_ToId\") self.config =", "sAttrName and sAttrValue != None: try: initialValue = self.dInitialValue[node] except KeyError: initialValue =", "the PageXML custom attribute \"\"\" @classmethod def parseCustomAttr(cls, s, bNoCase=True): \"\"\" The custom", "= DecoPolyLine._getCoordList(self, node) if lCoord: lCoord.append(lCoord[0]) return lCoord class DecoTextPolyLine(DecoPolyLine, DecoText): \"\"\"A polyline", "self.prevX, self.prevY = x, y return lo class DecoLine(Deco): \"\"\"A line from x1,y1", "and nd.name != sPageTag: nd = nd.parent try: #number = max(0, int(nd.prop(\"number\")) -", "return a list of created WX objects\"\"\" # print node.serialize() # print self.xpX", "DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize = cfg.get(sSurname, \"xpath_font_size\") self.xpFontColor", "= cfg.get(sSurname, \"xpath_LineColor\") #cached values self._node = None self._lxy = None def __str__(self):", "y2=%s)\" % (self.xpX1, self.xpY1, self.xpEvalX2, self.xpEvalY2) return s def draw(self, wxh, node): \"\"\"draw", "__init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a config file sSurname is the", "obj = wxh.AddScaledBitmap(img, (x,-y), h) else: obj = wxh.AddScaledBitmap(img, (x,-y), img.GetHeight()) lo.append(obj) except", "compute for font size of 24 and do proportional dc.SetFont(wx.Font(24, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))", "{offset:12; length:2;}\"> <Coords points=\"985,390 1505,390 1505,440 985,440\"/> <Baseline points=\"985,435 1505,435\"/> <TextEquiv> <Unicode>Salgadinhos 12</Unicode>", "return the default int value \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) s", "colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self._node = None def", "return a scalar or a one-node nodeset On error, return the default int", "and fill colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") #cached values", "Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class DecoClusterCircle(DecoREAD): \"\"\" [Cluster] type=DecoClusterCircle xpath=.//Cluster xpath_content=@content", "bKO = False break if bKO: self.warning(\"WARNING: deco Image: file does not exists:", "DecoOrder(DecoBBXYWH): \"\"\"Show the order with lines \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self,", "iLength = int(_dLabel[\"length\"]) x = x0 + Ex * iOffset y = -y0+iFontSize/6", "lo.append(obj) return lo class DecoText(DecoBBXYWH): \"\"\"A text \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "LineColor=None) lo.append(obj) return lo def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class", "= cfg.get(sSurname, \"xpath_fit_text_size\").lower() def __str__(self): s = \"%s=\"%self.__class__ return s def _getFontSize(self, node,", "encode coordinates. like: <Coords points=\"985,390 1505,390 1505,440 985,440\"/> or <Baseline points=\"985,435 1505,435\"/> \"\"\"", "iFontSizeX = 8 iFontSizeY = 24 * abs(y2-y1) / Ey if sFit ==", "self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrToPageNumber", "xpX, xpY, xpW, xpH are scalar XPath expressions to get the associated x,y,w,h", "break if bKO: self.warning(\"WARNING: deco Image: file does not exists: '%s'\"%sFilePath) sFilePath =", "ValueError(\"Expected a '{' in '%s'\"%chunk) #the dictionary for that name dicValForName = dict()", "are bad: '%s' -> '%s'\" % ( self.xpCoords, sCoords)) raise e return ltXY", "except AttributeError: s = s[0] #should be an attribute value return Deco.toInt(s) except", "\"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillColor = self.xpathToStr(node, self.xpFillColor, \"#000000\") sFillStyle =", "\"S_Aicha_an_der_Donau_004-03\" try: sDir = sFilePath[:sFilePath.rindex(\"_\")] sCandidate = os.path.join(self.sImageFolder, sDir, sFilePath) if os.path.exists(sCandidate): sFilePath", "= sNames.split(',') for name in lName: name = name.strip().lower() if bNoCase else name.strip()", "ltXY def _coordList_to_BB(self, ltXY): \"\"\" return (x1, y1), (x2, y2) \"\"\" lX =", "a selected node self.xpX, self.xpY = cfg.get(sSurname, \"xpath_x\"), cfg.get(sSurname, \"xpath_y\") self.xpW, self.xpH =", "created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) #add the image itself x,y,w,h,inc", "fA, (xg, yg) assert fA >0 and xg >0 and yg >0, \"%s\\t%s\"%(lXY", "__init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontColor", "if bNoCase else sKey.strip() dicValForName[sKey] = sVal.strip() lName = sNames.split(',') for name in", "fA >0 and xg >0 and yg >0, \"%s\\t%s\"%(lXY (fA, (xg, yg))) return", "class DecoLink(Deco): \"\"\"A link from x1,y1 to x2,y2 \"\"\" def __init__(self, cfg, sSurname,", "then saved, re-clicking on it wil remove it. del node.attrib[sAttrName] s = \"Removal", "xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions that let us", "e: self.warning(\"DecoImage ERROR: File %s: %s\"%(sFilePath, str(e))) return lo class DecoOrder(DecoBBXYWH): \"\"\"Show the", "min(iFontSizeX, iFontSizeY) dc.SetFont(wx.Font(iFontSize, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey = dc.GetTextExtent(\"x\") del dc return", "except: self.warning(\"absence of text: cannot compute font size along X axis\") iFontSizeX =", "= cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") def __str__(self): s = \"%s=\"%self.__class__ s", "return an int on the given node. The XPath expression should return a", "in case the use wants to specify it via the menu sImageFolder =", "def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath", "return a list of created WX objects\"\"\" lo = DecoRectangle.draw(self, wxh, node) #add", "DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname, \"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__", "int(round(float(s))) toInt = classmethod(toInt) def xpathToInt(self, node, xpExpr, iDefault=0, bShowError=True): \"\"\"The given XPath", "s = s[0] #should be an attribute value return Deco.toInt(s) except Exception, e:", "xpCtxt is an XPath context \"\"\" self.sSurname = sSurname def __str__(self): return \"--------\"", "Deco._s_prev_warning = sMsg def toInt(cls, s): try: return int(s) except ValueError: return int(round(float(s)))", "self.xpathToInt(node, self.xpY2, iLARGENEG) self._node = node if self._x1 != iLARGENEG and self._y1 !=", "\"\") if sFilePath: if self.sImageFolder: sCandidate = os.path.join(self.sImageFolder, sFilePath) if os.path.exists(sCandidate): sFilePath =", "#to shift the text def draw(self, wxh, node): lo = Deco.draw(self, wxh, node)", "-y-y_inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class DecoClusterCircle(DecoREAD): \"\"\"", "x0, y0 = ltXY[0] _ldLabel = dCustom[self.xpathToStr(node, self.xpLabel, \"\").lower()] for _dLabel in _ldLabel:", "Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo def getText(self, wxh, node): return self.xpathToStr(node, self.xpContent,", "created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sAttrName =", "= cfg.get(sSurname, \"xpath\") # a main XPath that select nodes to be decorated", "+ lo return lo def act(self, obj, node): \"\"\" return the page number", "= cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrToPageNumber =", "context may include the declaration of some namespace sEnabled = cfg.get(sSurname, \"enabled\").lower() self.bEnabled", "DecoText .__init__(self, cfg, sSurname, xpCtxt) self.xpX_Inc = cfg.get(sSurname, \"xpath_x_incr\") #to shift the text", "self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) #draw a line obj = wxh.AddLine(", "any sequnce of draw for a given page\"\"\" pass def draw(self, wxh, node):", "in lsKeyVal: if not sKeyVal.strip(): continue #empty try: sKey, sVal = sKeyVal.split(':') except", "s = \"%s=\"%self.__class__ s += \"+(x1=%s y1=%s x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpX2,", "y in lXY: iTerm = xprev*y - yprev*x fA += iTerm xSum +=", "pass def endPage(self, node): \"\"\"called before any sequnce of draw for a given", "of the polygon \"\"\" if len(lXY) < 2: raise ValueError(\"Only one point: polygon", "x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpX2, self.xpY2) return s def draw(self, wxh, node):", "s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) return self.xpCtxt.xpathEval(xpExpr) except Exception, e: self.xpathError(node, xpExpr, e, \"xpathEval", "with lines \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpLineColor", "# in case the use wants to specify it via the menu sImageFolder", "like: <Coords points=\"985,390 1505,390 1505,440 985,440\"/> or <Baseline points=\"985,435 1505,435\"/> \"\"\" def __init__(self,", "self.xpFillColor, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyle, \"Solid\") obj = wxh.AddRectangle((x, -y), (w, -h),", "sKey = sKey.strip().lower() if bNoCase else sKey.strip() dicValForName[sKey] = sVal.strip() lName = sNames.split(',')", "%s: %s\"%(sFilePath, str(e))) lo.append( DecoRectangle.draw(self, wxh, node) ) return lo class DecoImage(DecoBBXYWH): \"\"\"An", "Ex, Ey = None, None except ValueError: dc = wx.ScreenDC() # compute for", "y2) = self._coordList_to_BB(ltXY) sFit = self.xpathToStr(node, self.xpFit, 'xy', bShowError=False) try: iFontSize = int(sFit)", "lo = [] #add the image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node,", "to go thru each item ndPage = node.xpath(\"ancestor::*[local-name()='Page']\")[0] sIds = self.xpathEval(node, self.xpContent)[0] for", "if type(s) == types.ListType: try: s = s[0].text except AttributeError: s = s[0]", "if lChunk: for chunk in lChunk: #things like \"a {x:1\" chunk = chunk.strip()", "xpath_FillStyle=\"Solid\" <NAME> - March 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg,", "a configuration object sSurname is the surname of the decoration and the section", "self._getFontSize(node, ltXY, txt , Family=wx.FONTFAMILY_TELETYPE) dCustom = self.parseCustomAttr(node.get(\"custom\"), bNoCase=True) try: x0, y0 =", "sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontSize = cfg.get(sSurname,", "clicking on it add/remove an attribute the rectangle color is indicative of the", "print \"DecoClusterCircle lsFillColor = \", self.lsFillColor def __str__(self): s = \"%s=\"%self.__class__ s +=", "= self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y-h/2.0), Size=iFontSize, Family=wx.ROMAN, Position='cl', Color=sFontColor, PadSize=0, LineColor=None)", "in the config file This section should contain the following items: x, y,", "bShowError=False) try: iFontSize = int(sFit) Ex, Ey = None, None except ValueError: dc", "ySum/6/fA if fA <0: return -fA, (xg, yg) else: return fA, (xg, yg)", "of the decoration and the section name in the config file! xpCtxt is", "if len(sNode) > iMaxLen: sNode = sNode[:iMaxLen] + \"...\" s += \"\\n--- XML", "clicking on it jump to a page \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "1 if Deco._prev_xpath_error_count > 10: return try: sNode = etree.tostring(node) except: sNode =", "e, \"xpathEval return None\") return None def beginPage(self, node): \"\"\"called before any sequnce", "def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a config file sSurname is", "include the declaration of some namespace sEnabled = cfg.get(sSurname, \"enabled\").lower() self.bEnabled = sEnabled", "us find the rectangle line and fill colors self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth", "\"file:/\"]: if sUrl[0:len(sPrefix)] == sPrefix: sLocalDir = os.path.dirname(sUrl[len(sPrefix):]) sDir,_ = os.path.splitext(os.path.basename(sUrl)) sCandidate =", "dc.GetTextExtent(\"x\") del dc return iFontSize, Ex, Ey def draw(self, wxh, node): \"\"\"draw itself", "/ Ex / len(txt) except: self.warning(\"absence of text: cannot compute font size along", "fA = 0.0 xSum, ySum = 0, 0 xprev, yprev = lXY[-1] for", "return [] class DecoBBXYWH(Deco): \"\"\"A decoration with a bounding box defined by X,Y", "# for n in node.xpathEval(self.xpX): print n.serialize() iLARGENEG = -9999 lo = Deco.draw(self,", "node.set(sAttrName, initialValue) s = '@%s := \"%s\"'%(sAttrName,initialValue) else: if not sAttrValue: del node.attrib[sAttrName]", "Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class DecoText(DecoBBXYWH): \"\"\"A text \"\"\" def", "one point: polygon area is undefined.\") fA = 0.0 xSum, ySum = 0,", "xSum += iTerm * (xprev+x) ySum += iTerm * (yprev+y) xprev, yprev =", "s += DecoBBXYWH.__str__(self) return s def draw(self, wxh, node): \"\"\"draw itself using the", "in this way self.xpCtxt = xpCtxt #this context may include the declaration of", "as default value\"%iDefault) return iDefault def xpathToStr(self, node, xpExpr, sDefault, bShowError=True): \"\"\"The given", "the wx handle return a list of created WX objects\"\"\" lo = []", "self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self._node = None def __str__(self): s = \"%s=\"%self.__class__ s", "lo.append(obj) return lo class DecoREAD(Deco): \"\"\" READ PageXml has a special way to", "self.warning(\"WARNING: deco Image: file does not exists: '%s'\"%sFilePath) sFilePath = None if bool(sFilePath):", "handle return a list of created WX objects \"\"\" lo = [] #add", "(x, -y+inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo class DecoText(DecoBBXYWH):", "case: when an attr was set, then saved, re-clicking on it wil remove", "we show the annotation by offset found in the custom attribute \"\"\" def", "project <TextLine id=\"line_1551946877389_284\" custom=\"readingOrder {index:0;} Item-name {offset:0; length:11;} Item-price {offset:12; length:2;}\"> <Coords points=\"985,390", "= sSurname def __str__(self): return \"--------\" def isSeparator(self): return True def setXPathContext(self, xpCtxt):", "type: '%s'\"%sClass) return c getDecoClass = classmethod(getDecoClass) def getSurname(self): return self.sSurname def getMainXPath(self):", "ySum += iTerm * (yprev+y) xprev, yprev = x, y if fA ==", "iFontSize = iFontSizeY else: iFontSize = min(iFontSizeX, iFontSizeY) dc.SetFont(wx.Font(iFontSize, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex,", "= %s\" % node.get(\"id\")) return [(0,0)] try: ltXY = [] for _sPair in", "DecoBBXYWH.__str__(self) return s def beginPage(self, node): \"\"\"called before any sequnce of draw for", "return a list of created WX objects\"\"\" lo = [] #add the text", "xpX2, iLARGENEG, False) #do not show any error if self._x2 == iLARGENEG: self._x2", "class DecoPolyLine(DecoREAD): \"\"\"A polyline along x1,y1,x2,y2, ...,xn,yn or x1,y1 x2,y2 .... xn,yn Example", "sMsg def toInt(cls, s): try: return int(s) except ValueError: return int(round(float(s))) toInt =", "return a list of created WX objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) #add", "for n in node.xpathEval(self.xpX): print n.serialize() lo = DecoREAD.draw(self, wxh, node) if self._node", "= \"%s=\"%self.__class__ s += \"+(coords=%s)\" % (self.xpCoords) return s def getArea_and_CenterOfMass(self, lXY): \"\"\"", "circle sFillColor = self.lsFillColor[Nf % iMaxFC] if self.lsLineColor: sLineColor = self.lsLineColor[Nl % iMaxLC]", "file sSurname is the decoration surname and the section name in the config", "xpath expression return None on error \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node)", "cfg, sSurname, xpCtxt): \"\"\" cfg is a config file sSurname is the decoration", "return try: sNode = etree.tostring(node) except: sNode = str(node) if len(sNode) > iMaxLen:", "computation of font size ltXY = self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY,", "LineColor=sLineColor) lo.append(obj) return lo class DecoClosedPolyLine(DecoPolyLine): \"\"\"A polyline that closes automatically the shape", "class DecoLine(Deco): \"\"\"A line from x1,y1 to x2,y2 \"\"\" def __init__(self, cfg, sSurname,", "polygon area is undefined.\") fA = 0.0 xSum, ySum = 0, 0 xprev,", "= self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt , Family=wx.FONTFAMILY_TELETYPE) dCustom =", "try: sKey, sVal = sKeyVal.split(':') except Exception: raise ValueError(\"Expected a comma-separated string, got", "objects\"\"\" lo = DecoBBXYWH.draw(self, wxh, node) x,y,w,h,inc = self.runXYWHI(node) sLineColor = self.xpathToStr(node, self.xpLineColor,", "x2=%s y2=%s)\" % (self.xpX1, self.xpY1, self.xpEvalX2, self.xpEvalY2) return s def draw(self, wxh, node):", "= cfg.get(sSurname, \"xpath_FillStyle_Selected\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s", "value\"%sDefault) return sDefault def xpathEval(self, node, xpExpr): \"\"\" evaluate the xpath expression return", "= cfg.get(sSurname, \"xpath_x2\"), cfg.get(sSurname, \"xpath_y2\") #now get the xpath expressions that let us", "line and fill colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") #cached", "lo = DecoBBXYWH.draw(self, wxh, node) #add the text itself txt = self.getText(wxh, node)", "sSurname, xpCtxt): DecoText.__init__(self, cfg, sSurname, xpCtxt) self.base = int(cfg.get(sSurname, \"code_base\")) def getText(self, wxh,", "if self._node != node: self._lxy = self._getCoordList(node) self._node = node if self._lxy: sLineColor", "= cfg.get(sSurname, \"xpath_x_incr\") #to shift the text self.xpY_Inc = cfg.get(sSurname, \"xpath_y_incr\") #to shift", "has a special way to encode coordinates. like: <Coords points=\"985,390 1505,390 1505,440 985,440\"/>", "self.xpathToInt(ndTo, self.xp_wTo, None) h = self.xpathToInt(ndTo, self.xp_hTo, None) if x==None or y==None or", "destination or None on error \"\"\" index,x,y,w,h = None,None,None,None,None sToPageNum = self.xpathToStr(node, self.xpAttrToPageNumber", "= sVal.strip() lName = sNames.split(',') for name in lName: name = name.strip().lower() if", "self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self._node = None def __str__(self):", "return sDefault def xpathEval(self, node, xpExpr): \"\"\" evaluate the xpath expression return None", "\"%s\"'%(sAttrName,sAttrValue) return s class DecoClickableRectangleJump(DecoBBXYWH): \"\"\"A rectangle clicking on it jump to a", "\"\"\" this is not properly a decoration but rather a separator of decoration", "in ltXY] return (min(lX), max(lY)), (max(lX), min(lY)) class DecoREADTextLine(DecoREAD): \"\"\"A TextLine as defined", "\"xpath_x2\"), cfg.get(sSurname, \"xpath_y2\") #now get the xpath expressions that let us find the", "a list of created WX objects\"\"\" lo = [] #add the text itself", "#first time self.dInitialValue[node] = initialValue if node.get(sAttrName) == sAttrValue: #back to previous value", "like: (\"a,b\", \"x:1 ; y:2\") except Exception: raise ValueError(\"Expected a '{' in '%s'\"%chunk)", "self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpRadius = cfg.get(sSurname, \"xpath_radius\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillStyle", "!= node: self._x1 = self.xpathToInt(node, self.xpX1, iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) self._x2", "xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) DecoText .__init__(self, cfg, sSurname, xpCtxt) self.xpX_Inc = cfg.get(sSurname,", "return ltXY def _coordList_to_BB(self, ltXY): \"\"\" return (x1, y1), (x2, y2) \"\"\" lX", "def toInt(cls, s): try: return int(s) except ValueError: return int(round(float(s))) toInt = classmethod(toInt)", "AttributeError: Deco._s_prev_xpath_error = \"\" Deco._prev_xpath_error_count = 0 iMaxLen = 200 # to truncate", "raise ValueError(\"surface == 0.0\") fA = fA / 2 xg, yg = xSum/6/fA,", "wxh, node) #add the image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef,", "wants to specify it via the menu sImageFolder = None def __init__(self, cfg,", "cStringIO import wx sEncoding = \"utf-8\" def setEncoding(s): global sEncoding sEncoding = s", "iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) for (x1, y1), (x2, y2) in zip(self._lxy, self._lxy[1:]):", "self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") #the following expression must be evaluated", "self.getText(wxh, node) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") sBackgroundColor", "sKeyVal.strip(): continue #empty try: sKey, sVal = sKeyVal.split(':') except Exception: raise ValueError(\"Expected a", "int(sFit) Ex, Ey = None, None except ValueError: dc = wx.ScreenDC() # compute", "s += \"\\n--- XPath ERROR on class %s\"%self.__class__ s += \"\\n--- xpath=%s\" %", "draw(self, wxh, node): \"\"\"draw the associated decorations, return the list of wx created", "scalar or a one-node nodeset On error, return the default int value \"\"\"", "line from x1,y1 to x2,y2 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg,", "initialValue == None or initialValue == sAttrValue: #very special case: when an attr", "= self.xpathToStr(node, self.xpAttrName , None) sAttrValue = self.xpathToStr(node, self.xpAttrValue, None) if sAttrName and", "fill colors self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self._node = None", "+= DecoBBXYWH.__str__(self) return s def beginPage(self, node): \"\"\"called before any sequnce of draw", "% xpExpr s += \"\\n--- Python Exception=%s\" % str(eExcpt) if sMsg: s +=", "y) , Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='bl' , Color=sFontColor , LineColor=sLineColor , BackgroundColor=sBackgroundColor)", "Everything related to the PageXML custom attribute \"\"\" @classmethod def parseCustomAttr(cls, s, bNoCase=True):", "for a given page\"\"\" self.bInit = False def draw(self, wxh, node): \"\"\"draw itself", "sSurname, xpCtxt) def _getCoordList(self, node): lCoord = DecoPolyLine._getCoordList(self, node) if lCoord: lCoord.append(lCoord[0]) return", "\"\"\" # in case the use wants to specify it via the menu", "xpathToStr(self, node, xpExpr, sDefault, bShowError=True): \"\"\"The given XPath expression should return a string", "\"\"\"called before any sequnce of draw for a given page\"\"\" pass def endPage(self,", "if not sKeyVal.strip(): continue #empty try: sKey, sVal = sKeyVal.split(':') except Exception: raise", "not os.path.exists(sFilePath): # maybe we have some pattern?? lCandidate = glob.glob(sFilePath) bKO =", "deco Image: file does not exists: '%s'\"%sFilePath) sFilePath = None if bool(sFilePath): img", "sLineColor = self.lsLineColor[Nl % iMaxLC] else: sLineColor = sFillColor obj = wxh.AddCircle((x, -y),", "the presence/absence of the attribute \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg,", "iTerm = xprev*y - yprev*x fA += iTerm xSum += iTerm * (xprev+x)", "name as XML file? (Transkribus style) sUrl = node.getroottree().docinfo.URL.decode('utf-8') # py2 ... for", "a line obj = wxh.AddLine( [(self._x1, -self._y1), (self._x2, -self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor)", "del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else: node.set(sAttrName, sAttrValue) s = '@%s", "contain the following items: x, y, w, h \"\"\" Deco.__init__(self, cfg, sSurname, xpCtxt)", "node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try: s = s[0].text", "DecoLink(Deco): \"\"\"A link from x1,y1 to x2,y2 \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "True iEllipseParam = min(w,h) / 2 wxh.AddEllipse((x, -y), (iEllipseParam, -iEllipseParam), LineColor=sLineColor, LineWidth=5, FillStyle=\"Transparent\")", "(self.xpX, self.xpY, self.xpW, self.xpH) return s def runXYWHI(self, node): \"\"\"get the X,Y values", "img = wx.Image(sFilePath, wx.BITMAP_TYPE_ANY) obj = wxh.AddScaledBitmap(img, (x,-y), h) lo.append(obj) except Exception, e:", "__init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions", "= l[0] lxy = self._getCoordList(ndItem) fA, (xg, yg) = self.getArea_and_CenterOfMass(lxy) r = self.xpathToInt(ndItem,", ", LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoClosedPolyLine(DecoPolyLine): \"\"\"A polyline that closes", "= eval(sPythonExpr) else: s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try: s =", "_x,_y in ltXY] return (min(lX), max(lY)), (max(lX), min(lY)) class DecoREADTextLine(DecoREAD): \"\"\"A TextLine as", "sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: if self.sImageFolder: sCandidate = os.path.join(self.sImageFolder, sFilePath)", "(Xg, Yg) which are the area and the coordinates (float) of the center", "Deco.toInt(sy))) except Exception as e: logging.error(\"ERROR: polyline coords are bad: '%s' -> '%s'\"", "\"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def draw(self, wxh, node): \"\"\"draw itself using", "y2) in zip(self._lxy, self._lxy[1:]): #draw a line obj = wxh.AddLine( [(x1, -y1), (x2,", "xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") self.xpX2,", "self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrToPageNumber = cfg.get(sSurname, \"xpath_ToPageNumber\") def __str__(self): s = \"%s=\"%self.__class__", "self.runXYWHI(node) sAttrName = self.xpathToStr(node, self.xpAttrName , None) sAttrValue = self.xpathToStr(node, self.xpAttrValue, None) if", "XML node using WX \"\"\" import types, os from collections import defaultdict import", "and yg >0, \"%s\\t%s\"%(lXY (fA, (xg, yg))) return fA, (xg, yg) def draw(self,", "that let uis find x,y,w,h from a selected node self.xpX, self.xpY = cfg.get(sSurname,", "+ w/2.0), int(y + h/2.0) if self.bInit: #draw a line iLineWidth = self.xpathToInt(node,", "font size of 24 and do proportional dc.SetFont(wx.Font(24, Family, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) Ex, Ey", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\" cfg is a configuration object sSurname", ".__init__(self, cfg, sSurname, xpCtxt) self.xpX_Inc = cfg.get(sSurname, \"xpath_x_incr\") #to shift the text self.xpY_Inc", "lo.append(obj) return lo class DecoTextBox(DecoRectangle): \"\"\"A text within a bounding box (a rectangle)", "xpExprArg, sEndEmpty = xpExpr.split('|') assert sEndEmpty == \"\", \"Missing last '|'\" sArg =", "cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") def __str__(self): s", "the text itself txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8)", "a list of created WX objects\"\"\" lo = [] #add the image itself", "\"\"\"report an xpath error\"\"\" try: Deco._s_prev_warning except AttributeError: Deco._s_prev_warning = \"\" Deco._warning_count =", "self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") def __str__(self): s = \"%s=\"%self.__class__", "if xpExpr[0] == \"|\": #must be a lambda assert xpExpr[:8] == \"|lambda \",", "self.xpX2, self.xpY2 = cfg.get(sSurname, \"xpath_x2\"), cfg.get(sSurname, \"xpath_y2\") #now get the xpath expressions that", "'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y+inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor,", "0, 0 xprev, yprev = lXY[-1] for x, y in lXY: iTerm =", "obj = wxh.AddScaledTextBox(txt, (x, -y+inc), Size=iFontSize, Family=wx.ROMAN, Position='tl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return", "nd.parent try: #number = max(0, int(nd.prop(\"number\")) - 1) number = max(0, self.xpathToInt(nd, sPageNumberAttr,", "if self.xp_xTo and self.xp_yTo and self.xp_hTo and self.xp_wTo: x = self.xpathToInt(ndTo, self.xp_xTo, None)", "act(self, obj, node): \"\"\" Toggle the attribute value \"\"\" s = \"do nothing\"", "if Deco._prev_xpath_error_count > 10: return try: sNode = etree.tostring(node) except: sNode = str(node)", "self.xp_wTo = cfg.get(sSurname, \"xpath_wTo\") self.xp_hTo = cfg.get(sSurname, \"xpath_hTo\") self.xpAttrToId = cfg.get(sSurname, \"xpath_ToId\") self.config", "= cfg.get(sSurname, \"xpath_LineColor_Selected\") self.xpLineWidthSlctd = cfg.get(sSurname, \"xpath_LineWidth_Selected\") self.xpFillColorSlctd = cfg.get(sSurname, \"xpath_FillColor_Selected\") self.xpFillStyleSlctd =", "1) self._w = self.xpathToInt(node, self.xpW, 1) self._h = self.xpathToInt(node, self.xpH, 1) self._inc =", "self._node = None self._lxy = None def __str__(self): s = \"%s=\"%self.__class__ s +=", "\"\"\"The given XPath expression should return an int on the given node. The", "sSurname, xpCtxt) self.xpX1, self.xpY1 = cfg.get(sSurname, \"xpath_x1\"), cfg.get(sSurname, \"xpath_y1\") self.xpX2, self.xpY2 = cfg.get(sSurname,", "= self._x-self._inc, self._y-self._inc self._w,self._h = self._w+2*self._inc, self._h+2*self._inc self._node = node return (self._x, self._y,", "should return a scalar or a one-node nodeset On error, return the default", "the text self.xpY_Inc = cfg.get(sSurname, \"xpath_y_incr\") #to shift the text def draw(self, wxh,", "= random.randrange(iMaxFC) Nl = random.randrange(iMaxFC) iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillStyle = self.xpathToStr(node,", "= self.runXYWHI(node) sFilePath = self.xpathToStr(node, self.xpHRef, \"\") if sFilePath: if self.sImageFolder: sCandidate =", "= classmethod(isSeparator) def __str__(self): return \"(Surname=%s xpath==%s)\" % (self.sSurname, self.xpMain) def getDecoClass(cls, sClass):", "= os.path.join(self.sImageFolder, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate else: # maybe the file", "contains data in a CSS style syntax. We parse this syntax here and", "(w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) \"\"\" return lo class DecoLink(Deco): \"\"\"A link", "self.xpDfltX2, self.xpDfltY2 = cfg.get(sSurname, \"xpath_x2_default\"), cfg.get(sSurname, \"xpath_y2_default\") #now get the xpath expressions that", "LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo.append(obj) return lo class DecoTextBox(DecoRectangle): \"\"\"A text within a bounding", "from a selected node self.xpX, self.xpY = cfg.get(sSurname, \"xpath_x\"), cfg.get(sSurname, \"xpath_y\") self.xpW, self.xpH", "id = %s\" % node.get(\"id\")) return [(0,0)] try: ltXY = [] for _sPair", ") return lo class DecoImage(DecoBBXYWH): \"\"\"An image \"\"\" # in case the use", "following expression must be evaluated twice self.xpEvalX2, self.xpEvalY2 = cfg.get(sSurname, \"eval_xpath_x2\"), cfg.get(sSurname, \"eval_xpath_y2\")", "node, xpExpr, eExcpt, sMsg=\"\"): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_xpath_error except AttributeError: Deco._s_prev_xpath_error", "lo.append(obj) except KeyError: pass except KeyError: pass return lo class DecoPolyLine(DecoREAD): \"\"\"A polyline", "os.path.abspath(os.path.join(sLocalDir, sDir, sFilePath)) if os.path.exists(sCandidate): sFilePath = sCandidate print(sFilePath) break if not os.path.exists(sFilePath):", "= self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try: s = s[0].text except AttributeError: s", "decorated in this way self.xpCtxt = xpCtxt #this context may include the declaration", "File %s: %s\"%(sFilePath, str(e))) lo.append( DecoRectangle.draw(self, wxh, node) ) return lo class DecoImage(DecoBBXYWH):", "(xg, yg) else: return fA, (xg, yg) assert fA >0 and xg >0", "\"xpath_href\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return s def draw(self,", "e: if bShowError: self.xpathError(node, xpExpr, e, \"xpathToInt return %d as default value\"%iDefault) return", "if bShowError: self.xpathError(node, xpExpr, e, \"xpathToInt return %d as default value\"%iDefault) return iDefault", "or 16 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoText.__init__(self, cfg, sSurname, xpCtxt) self.base", "False) txt = self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor =", ", Family=wx.FONTFAMILY_TELETYPE) dCustom = self.parseCustomAttr(node.get(\"custom\"), bNoCase=True) try: x0, y0 = ltXY[0] _ldLabel =", "class DecoREADTextLine_custom_offset(DecoREADTextLine, READ_custom): \"\"\" Here we show the annotation by offset found in", "wxh, node): \"\"\" draw itself using the wx handle return a list of", "sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions that let", "= \"%s=\"%self.__class__ s += DecoRectangle.__str__(self) return s def draw(self, wxh, node): \"\"\"draw itself", "\"xpath_content\") self.xpFontSize = cfg.get(sSurname, \"xpath_font_size\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s =", "-y-h/2.0), Size=iFontSize, Family=wx.ROMAN, Position='cl', Color=sFontColor, PadSize=0, LineColor=None) lo.append(obj) return lo def getText(self, wxh,", "\"-\"*60 s += \"\\n--- XPath ERROR on class %s\"%self.__class__ s += \"\\n--- xpath=%s\"", "a default value if necessary xpX2 = self.xpathToStr(node, self.xpEvalX2, '\"\"') self._x2 = self.xpathToInt(node,", "@%s\"%sAttrName else: node.set(sAttrName, initialValue) s = '@%s := \"%s\"'%(sAttrName,initialValue) else: if not sAttrValue:", "\"xpathToStr return %s as default value\"%sDefault) return sDefault def xpathEval(self, node, xpExpr): \"\"\"", "self._getCoordList(node) iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE) # x, y =", "iLARGENEG: self._x2 = self.xpathToInt(node, self.xpDfltX2, iLARGENEG) xpY2 = self.xpathToStr(node, self.xpEvalY2, '\"\"') self._y2 =", "this font size return iFontSize, ExtentX, ExtentY \"\"\" (x1, y1), (x2, y2) =", "getMainXPath(self): return self.xpMain def isEnabled(self): return self.bEnabled def setEnabled(self, b=True): self.bEnabled = b", "number of the destination or None on error \"\"\" sPageTag = self.config.getPageTag() sPageNumberAttr", "as defined by the PageXml format of the READ project <TextLine id=\"line_1551946877389_284\" custom=\"readingOrder", "draw(self, wxh, node): \"\"\"draw itself using the wx handle return a list of", "list of created WX objects\"\"\" # print node.serialize() # print self.xpX # for", "fA = fA / 2 xg, yg = xSum/6/fA, ySum/6/fA if fA <0:", "def act(self, obj, node): \"\"\" Toggle the attribute value \"\"\" s = \"do", "the page number ndTo = nd = ln[0] #while nd and nd.name !=", "cfg, sSurname, xpCtxt) def _getCoordList(self, node): lCoord = DecoPolyLine._getCoordList(self, node) if lCoord: lCoord.append(lCoord[0])", "self.xpY2 = cfg.get(sSurname, \"xpath_x2\"), cfg.get(sSurname, \"xpath_y2\") #now get the xpath expressions that let", "= node.getroottree().docinfo.URL.decode('utf-8') # py2 ... for sPrefix in [\"file://\", \"file:/\"]: if sUrl[0:len(sPrefix)] ==", "list of wx created objects\"\"\" return [] class DecoBBXYWH(Deco): \"\"\"A decoration with a", "\"Invalid lambda expression %s\"%xpExpr sStartEmpty, sLambdaExpr, xpExprArg, sEndEmpty = xpExpr.split('|') assert sEndEmpty ==", "+ \"...\" s += \"\\n--- XML node = %s\" % sNode s +=", "... for sPrefix in [\"file://\", \"file:/\"]: if sUrl[0:len(sPrefix)] == sPrefix: sLocalDir = os.path.dirname(sUrl[len(sPrefix):])", "cfg.get(sSurname, \"xpath_y2\") #now get the xpath expressions that let us find the rectangle", "_getCoordList(self, node): sCoords = self.xpathToStr(node, self.xpCoords, \"\") if not sCoords: if node.get(\"id\") is", "Item-price {offset:12; length:2;}\"> <Coords points=\"985,390 1505,390 1505,440 985,440\"/> <Baseline points=\"985,435 1505,435\"/> <TextEquiv> <Unicode>Salgadinhos", "= self._getFontSize(node, ltXY, txt , Family=wx.FONTFAMILY_TELETYPE) dCustom = self.parseCustomAttr(node.get(\"custom\"), bNoCase=True) try: x0, y0", "DecoClusterCircle.count = DecoClusterCircle.count + 1 lo = DecoREAD.draw(self, wxh, node) if self._node !=", "DecoREAD.draw(self, wxh, node) if self._node != node: self._laxyr = [] #need to go", "lo = DecoBBXYWH.draw(self, wxh, node) #add the image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath", "= self.xpathToStr(node, self.xpFillColorSlctd, \"#000000\") sFillStyle = self.xpathToStr(node, self.xpFillStyleSlctd, \"Solid\") else: sLineColor = self.xpathToStr(node,", "= wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo = [obj] +", "set, then saved, re-clicking on it wil remove it. del node.attrib[sAttrName] s =", "DecoPolyLine(DecoREAD): \"\"\"A polyline along x1,y1,x2,y2, ...,xn,yn or x1,y1 x2,y2 .... xn,yn Example of", "sUrl[0:len(sPrefix)] == sPrefix: sLocalDir = os.path.dirname(sUrl[len(sPrefix):]) sDir,_ = os.path.splitext(os.path.basename(sUrl)) sCandidate = os.path.abspath(os.path.join(sLocalDir, sDir,", "self._x2 = self.xpathToInt(node, self.xpDfltX2, iLARGENEG) xpY2 = self.xpathToStr(node, self.xpEvalY2, '\"\"') self._y2 = self.xpathToInt(node,", "self.xp_xTo, None) y = self.xpathToInt(ndTo, self.xp_yTo, None) w = self.xpathToInt(ndTo, self.xp_wTo, None) h", "node using WX \"\"\" import types, os from collections import defaultdict import glob", "self._y1 != iLARGENEG and self._x2 != iLARGENEG and self._y2 != iLARGENEG: sLineColor =", "obj = wxh.AddScaledTextBox(txt[iOffset:iOffset+iLength] , (x, y) , Size=iFontSize , Family=wx.FONTFAMILY_TELETYPE , Position='bl' ,", "= False break if bKO: self.warning(\"WARNING: deco Image: file does not exists: '%s'\"%sFilePath)", "= self.xpathToStr(node, self.xpCoords, \"\") if not sCoords: if node.get(\"id\") is None: self.warning(\"No coordinates:", "def __init__(self, cfg, sSurname, xpCtxt): DecoREAD.__init__(self, cfg, sSurname, xpCtxt) self.xpCluster = cfg.get(sSurname, \"xpath\")", "and self._y2 != iLARGENEG: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth,", "\"\"\" Deco.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath expressions that let uis", "= nd = ln[0] #while nd and nd.name != \"PAGE\": nd = nd.parent", "self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') obj = wxh.AddScaledTextBox(txt, (x+x_inc, -y-y_inc), Size=iFontSize,", "the given node. The XPath expression should return a scalar or a one-node", "\"eval_xpath_x2\"), cfg.get(sSurname, \"eval_xpath_y2\") self.xpDfltX2, self.xpDfltY2 = cfg.get(sSurname, \"xpath_x2_default\"), cfg.get(sSurname, \"xpath_y2_default\") #now get the", "separator of decoration in the toolbar \"\"\" def __init__(self, cfg, sSurname, xpCtxt): \"\"\"", "= self.xpathToStr(node, self.xpContent, \"\") try: return eval('u\"\\\\u%04x\"' % int(sEncodedText, self.base)) except ValueError: logging.error(\"DecoUnicodeChar:", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef = cfg.get(sSurname,", "import logging import random from lxml import etree #import cStringIO import wx sEncoding", "sFilePath[:sFilePath.rindex(\"_\")] sCandidate = os.path.join(self.sImageFolder, sDir, sFilePath) if os.path.exists(sCandidate): sFilePath = sCandidate except ValueError:", "(self.sSurname, self.xpMain) def getDecoClass(cls, sClass): \"\"\"given a decoration type, return the associated class\"\"\"", "etree.tostring(node)) else: self.warning(\"No coordinates: node id = %s\" % node.get(\"id\")) return [(0,0)] try:", "self.xpathToStr(node, self.xpFontColor, 'BLACK') sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") sBackgroundColor = self.xpathToStr(node, self.xpBackgroundColor, \"#000000\")", "os.path.exists(sCandidate): sFilePath = sCandidate print(sFilePath) break if not os.path.exists(sFilePath): # maybe we have", "draw for a given page\"\"\" self.bInit = False def draw(self, wxh, node): \"\"\"draw", "= node if self._lxy: sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth,", "-y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) \"\"\" return lo class DecoLink(Deco): \"\"\"A", "= 24 * abs(x2-x1) / Ex / len(txt) except: self.warning(\"absence of text: cannot", "a lambda assert xpExpr[:8] == \"|lambda \", \"Invalid lambda expression %s\"%xpExpr sStartEmpty, sLambdaExpr,", "[(x1, -y1), (x2, -y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoClosedPolyLine(DecoPolyLine):", "}], 'structure':[{'type':'catch-word'}] } \"\"\" dic = defaultdict(list) s = s.strip() lChunk = s.split('}')", "len(sNode) > iMaxLen: sNode = sNode[:iMaxLen] + \"...\" s += \"\\n--- XML node", "default int value \"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) if xpExpr[0] ==", "self._h, self._inc) class DecoRectangle(DecoBBXYWH): \"\"\"A rectangle \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self,", "self.xpathToStr(node, self.xpContent, \"\") iFontSize = self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK')", "= [] #add the text itself txt = self.getText(wxh, node) sFontColor = self.xpathToStr(node,", "s.strip() lChunk = s.split('}') if lChunk: for chunk in lChunk: #things like \"a", "\"\"\" The custom attribute contains data in a CSS style syntax. We parse", "getText(self, wxh, node): return self.xpathToStr(node, self.xpContent, \"\") class READ_custom: \"\"\" Everything related to", "sy) = _sPair.split(',') ltXY.append((Deco.toInt(sx), Deco.toInt(sy))) except Exception as e: logging.error(\"ERROR: polyline coords are", "cfg.get(sSurname, \"xpath_w\"), cfg.get(sSurname, \"xpath_h\") self.xpInc = cfg.get(sSurname, \"xpath_incr\") #to increase the BB width", "return a string on the given node The XPath expression should return a", "sFit == \"x\": iFontSize = iFontSizeX elif sFit == \"y\": iFontSize = iFontSizeY", "Position and computation of font size ltXY = self._getCoordList(node) iFontSize, Ex, Ey =", "self.xpLineColor, \"#000000\") sBackgroundColor = self.xpathToStr(node, self.xpBackgroundColor, \"#000000\") # Position and computation of font", "= wxh.AddScaledBitmap(img, (x,-y), img.GetHeight()) lo.append(obj) except Exception, e: self.warning(\"DecoImage ERROR: File %s: %s\"%(sFilePath,", "or None on error \"\"\" sPageTag = self.config.getPageTag() sPageNumberAttr = self.config.getPageNumberAttr() number =", "in lChunk: #things like \"a {x:1\" chunk = chunk.strip() if not chunk: continue", "= self.xpathToInt(ndTo, self.xp_xTo, None) y = self.xpathToInt(ndTo, self.xp_yTo, None) w = self.xpathToInt(ndTo, self.xp_wTo,", "X axis\") iFontSizeX = 8 iFontSizeY = 24 * abs(y2-y1) / Ey if", "self.xpathToInt(node, xpY2, iLARGENEG, False) #do not show any error if self._y2 == iLARGENEG:", "self.xp_wTo, None) h = self.xpathToInt(ndTo, self.xp_hTo, None) if x==None or y==None or w==None", "code=%s\"%(self.base, sEncodedText)) return \"\" class DecoImageBox(DecoRectangle): \"\"\"An image with a box around it", "s class DecoSeparator: \"\"\" this is not properly a decoration but rather a", "self.xpY1, iLARGENEG) #double evaluation, and a default value if necessary xpX2 = self.xpathToStr(node,", "def getSurname(self): return self.sSurname def getMainXPath(self): return self.xpMain def isEnabled(self): return self.bEnabled def", "except KeyError: initialValue = node.prop(sAttrName) #first time self.dInitialValue[node] = initialValue if node.get(sAttrName) ==", "created WX objects\"\"\" lo = [] #add the image itself x,y,w,h,inc = self.runXYWHI(node)", "= cfg.get(sSurname, \"xpath_content\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") self.xpFit = cfg.get(sSurname, \"xpath_fit_text_size\").lower() def __str__(self):", "\"\\n--- Info: %s\" % sMsg if s == Deco._s_prev_xpath_error: # let's not overload", "iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) #draw a line obj = wxh.AddLine( [(self._x1, -self._y1),", "wxh, node): lo = Deco.draw(self, wxh, node) if self._node != node: self._lxy =", "parseCustomAttr(cls, s, bNoCase=True): \"\"\" The custom attribute contains data in a CSS style", "PageXml format of the READ project <TextLine id=\"line_1551946877389_284\" custom=\"readingOrder {index:0;} Item-name {offset:0; length:11;}", "= cfg.get(sSurname, \"xpath_AttrName\") self.xpAttrValue = cfg.get(sSurname, \"xpath_AttrValue\") self.dInitialValue = {} self.xpLineColorSlctd = cfg.get(sSurname,", "None, None, None except: pass return number,x,y,w,h class DecoClickableRectangleJumpToPage(DecoBBXYWH): \"\"\"A rectangle clicking on", "cfg, sSurname, xpCtxt) self.xpLabel = cfg.get(sSurname, \"xpath_label\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpBackgroundColor =", "def getArea_and_CenterOfMass(self, lXY): \"\"\" https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone return A, (Xg, Yg) which are the area", "= 0.0 xSum, ySum = 0, 0 xprev, yprev = lXY[-1] for x,", "\"\"\" try: # s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) return self.xpCtxt.xpathEval(xpExpr) except Exception, e: self.xpathError(node,", "int(nd.prop(\"number\")) - 1) number = max(0, self.xpathToInt(nd, sPageNumberAttr, 1, True) - 1) #maybe", "draw itself using the wx handle return a list of created WX objects", "wxh.AddRectangle((x, -y), (w, -h), LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) lo.append(obj) return lo class DecoTextBox(DecoRectangle):", "select nodes to be decorated in this way self.xpCtxt = xpCtxt #this context", "sNode[:iMaxLen] + \"...\" s += \"\\n--- XML node = %s\" % sNode s", "xpCtxt) self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") def __str__(self): s =", "import defaultdict import glob import logging import random from lxml import etree #import", "Deco._prev_xpath_error_count += 1 if Deco._prev_xpath_error_count > 10: return try: sNode = etree.tostring(node) except:", "self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\") self.xpBackgroundColor = cfg.get(sSurname, \"xpath_background_color\") def draw(self, wxh, node): \"\"\"", "%s\"%(sFilePath, str(e))) lo.append( DecoRectangle.draw(self, wxh, node) ) return lo class DecoImage(DecoBBXYWH): \"\"\"An image", "\"\"\" https://fr.wikipedia.org/wiki/Aire_et_centre_de_masse_d'un_polygone return A, (Xg, Yg) which are the area and the coordinates", "sequnce of draw for a given page\"\"\" pass def draw(self, wxh, node): \"\"\"draw", "or h==None: x,y,w,h = None, None, None, None except: pass return number,x,y,w,h class", "x, y, w, h \"\"\" Deco.__init__(self, cfg, sSurname, xpCtxt) #now get the xpath", "_getFontSize(self, node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE): \"\"\" compute the font size so as to", "yg) assert fA >0 and xg >0 and yg >0, \"%s\\t%s\"%(lXY (fA, (xg,", "xpCtxt): DecoREADTextLine.__init__(self, cfg, sSurname, xpCtxt) self.xpLabel = cfg.get(sSurname, \"xpath_label\") self.xpLineColor = cfg.get(sSurname, \"xpath_LineColor\")", "character encoded in Unicode We assume the unicode index is given in a", "the READ project <TextLine id=\"line_1551946877389_284\" custom=\"readingOrder {index:0;} Item-name {offset:0; length:11;} Item-price {offset:12; length:2;}\">", "self.sSurname def getMainXPath(self): return self.xpMain def isEnabled(self): return self.bEnabled def setEnabled(self, b=True): self.bEnabled", "a list of created WX objects \"\"\" lo = [] #add the text", "point: polygon area is undefined.\") fA = 0.0 xSum, ySum = 0, 0", "text: cannot compute font size along X axis\") iFontSizeX = 8 iFontSizeY =", "Exception(\"No such decoration type: '%s'\"%sClass) return c getDecoClass = classmethod(getDecoClass) def getSurname(self): return", "cache\"\"\" if self._node != node: self._x = self.xpathToInt(node, self.xpX, 1) self._y = self.xpathToInt(node,", "def draw(self, wxh, node): lo = Deco.draw(self, wxh, node) if self._node != node:", "DecoClusterCircle(DecoREAD): \"\"\" [Cluster] type=DecoClusterCircle xpath=.//Cluster xpath_content=@content xpath_radius=40 xpath_item_lxy=./pg:Coords/@points xpath_LineWidth=\"1\" xpath_FillStyle=\"Transparent\" LineColors=\"BLUE SIENNA YELLOW", "xpath error\"\"\" try: Deco._s_prev_warning except AttributeError: Deco._s_prev_warning = \"\" Deco._warning_count = 0 #", "-self._y1), (self._x2, -self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoClickableRectangleSetAttr(DecoBBXYWH): \"\"\"A", "cfg.get(sSurname, \"xpath_LineColor\") self.xpLineWidth = cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname,", "defined by the PageXml format of the READ project <TextLine id=\"line_1551946877389_284\" custom=\"readingOrder {index:0;}", "!= node: self._lxy = self._getCoordList(node) self._node = node #lo = DecoClosedPolyLine.draw(self, wxh, node)", "initialValue if node.get(sAttrName) == sAttrValue: #back to previous value if initialValue == None", "= cfg.get(sSurname, \"xpath_x2_default\"), cfg.get(sSurname, \"xpath_y2_default\") #now get the xpath expressions that let us", "- 1) number = max(0, self.xpathToInt(nd, sPageNumberAttr, 1, True) - 1) #maybe we", "iFontSize, Ex, Ey = self._getFontSize(node, ltXY, txt, Family=wx.FONTFAMILY_TELETYPE) # x, y = ltXY[0]", "= self.xpathToInt(node, self.xpFontSize, 8) sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') obj = wxh.AddScaledTextBox(txt, (x+x_inc,", "sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') sLineColor = self.xpathToStr(node, self.xpLineColor, \"#000000\") sBackgroundColor = self.xpathToStr(node,", "\"PAGE\": nd = nd.parent while nd and nd.name != sPageTag: nd = nd.parent", "\"\"\" def __init__(self, cfg, sSurname, xpCtxt): Deco.__init__(self, cfg, sSurname, xpCtxt) self.xpX1, self.xpY1 =", "= self.xpathToStr(node, self.xpLineColor, \"#000000\") iLineWidth = self.xpathToInt(node, self.xpLineWidth, 1) sFillColor = self.xpathToStr(node, self.xpFillColor,", "\"xpath_font_size\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoRectangle.__str__(self)", "os.path.exists(sFilePath): # maybe we have some pattern?? lCandidate = glob.glob(sFilePath) bKO = True", "Family=wx.FONTFAMILY_TELETYPE , Position='tl' , Color=sFontColor) lo.append(obj) return lo def getText(self, wxh, node): return", "# s = node.xpathEval(xpExpr) self.xpCtxt.setContextNode(node) s = self.xpCtxt.xpathEval(xpExpr) if type(s) == types.ListType: try:", "except Exception: raise ValueError(\"Expected a comma-separated string, got '%s'\"%sKeyVal) sKey = sKey.strip().lower() if", "w=%s h=%s)\" % (self.xpX, self.xpY, self.xpW, self.xpH) return s def runXYWHI(self, node): \"\"\"get", "= cfg.get(sSurname, \"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xp_xTo =", ">0, \"%s\\t%s\"%(lXY (fA, (xg, yg))) return fA, (xg, yg) def draw(self, wxh, node):", "in ['1', 'yes', 'true'] def isSeparator(cls): return False isSeparator = classmethod(isSeparator) def __str__(self):", "= None def __init__(self, cfg, sSurname, xpCtxt): DecoBBXYWH.__init__(self, cfg, sSurname, xpCtxt) self.xpHRef =", "sFilePath = sCandidate print(sFilePath) break if not os.path.exists(sFilePath): # maybe we have some", "September 2016 \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoPolyLine.__init__(self, cfg, sSurname, xpCtxt) def", "\"xpath_LineWidth\") self.xpFillColor = cfg.get(sSurname, \"xpath_FillColor\") self.xpFillStyle = cfg.get(sSurname, \"xpath_FillStyle\") self.xpAttrToPageNumber = cfg.get(sSurname, \"xpath_ToPageNumber\")", "sPageNumberAttr, 1, True) - 1) #maybe we can also indicate the precise arrival", "getSurname(self): return self.sSurname def getMainXPath(self): return self.xpMain def isEnabled(self): return self.bEnabled def setEnabled(self,", "self.bEnabled def setEnabled(self, b=True): self.bEnabled = b return b def isActionable(self): return False", "% (self.xpX1, self.xpY1, self.xpEvalX2, self.xpEvalY2) return s def draw(self, wxh, node): \"\"\"draw itself", "GREEN\" FillColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" enabled=1 \"\"\" count = 0 def", "+= iTerm * (yprev+y) xprev, yprev = x, y if fA == 0.0:", "self.xpY1, iLARGENEG) self._x2 = self.xpathToInt(node, self.xpX2, iLARGENEG) self._y2 = self.xpathToInt(node, self.xpY2, iLARGENEG) self._node", "collections import defaultdict import glob import logging import random from lxml import etree", "isSeparator(cls): return False isSeparator = classmethod(isSeparator) def __str__(self): return \"(Surname=%s xpath==%s)\" % (self.sSurname,", "wxh.AddLine( [(self.prevX, -self.prevY), (x, -y)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) else: self.bInit =", "\"xpath_y2_default\") #now get the xpath expressions that let us find the rectangle line", "\"xpath_FillStyle_Selected\") def __str__(self): s = \"%s=\"%self.__class__ s += DecoBBXYWH.__str__(self) return s def isActionable(self):", "(x2, -y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo class DecoClosedPolyLine(DecoPolyLine): \"\"\"A polyline", "self.xpLineWidth, 1) #draw a line obj = wxh.AddLine( [(self._x1, -self._y1), (self._x2, -self._y2)] ,", "rectangle clicking on it add/remove an attribute the rectangle color is indicative of", "LineWidth=iLineWidth, LineColor=sLineColor, FillColor=sFillColor, FillStyle=sFillStyle) \"\"\" return lo class DecoLink(Deco): \"\"\"A link from x1,y1", "if self._y2 == iLARGENEG: self._y2 = self.xpathToInt(node, self.xpDfltY2, iLARGENEG) self._node = node if", "self._y, self._w, self._h, self._inc) class DecoRectangle(DecoBBXYWH): \"\"\"A rectangle \"\"\" def __init__(self, cfg, sSurname,", "self.xpContent, \"\") class READ_custom: \"\"\" Everything related to the PageXML custom attribute \"\"\"", "self._w,self._h = self._w+2*self._inc, self._h+2*self._inc self._node = node return (self._x, self._y, self._w, self._h, self._inc)", "case the use wants to specify it via the menu sImageFolder = None", "on it wil remove it. del node.attrib[sAttrName] s = \"Removal of @%s\"%sAttrName else:", "is the decoration surname and the section name in the config file This", "objects\"\"\" lo = [] #add the image itself x,y,w,h,inc = self.runXYWHI(node) sFilePath =", "iLARGENEG) self._y1 = self.xpathToInt(node, self.xpY1, iLARGENEG) #double evaluation, and a default value if", "type(s) == types.ListType: try: s = s[0].text except AttributeError: s = s[0] return", "like \"x:1\" for sKeyVal in lsKeyVal: if not sKeyVal.strip(): continue #empty try: sKey,", "image with a box around it \"\"\" def __init__(self, cfg, sSurname, xpCtxt): DecoRectangle.__init__(self,", "'{' in '%s'\"%chunk) #the dictionary for that name dicValForName = dict() lsKeyVal =", "None) sAttrValue = self.xpathToStr(node, self.xpAttrValue, None) if sAttrName and sAttrValue != None: if", "to get the associated x,y,w,h values from the selected nodes \"\"\" def __init__(self,", "> 10: return try: sNode = etree.tostring(node) except: sNode = str(node) if len(sNode)", "sFontColor = self.xpathToStr(node, self.xpFontColor, 'BLACK') x,y,w,h,inc = self.runXYWHI(node) obj = wxh.AddScaledTextBox(txt, (x, -y-h/2.0),", "def _getCoordList(self, node): lCoord = DecoPolyLine._getCoordList(self, node) if lCoord: lCoord.append(lCoord[0]) return lCoord class", "xpath_FillStyle=\"Transparent\" LineColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\" FillColors=\"BLUE SIENNA YELLOW ORANGE RED GREEN\"", "iMaxLC = len(self.lsLineColor) if False: Nf = DecoClusterCircle.count Nl = Nf else: Nf", "= 200 # to truncate the node serialization s = \"-\"*60 s +=", "let's not overload the console. return Deco._s_prev_xpath_error = s Deco._prev_xpath_error_count += 1 if", "xpathError(self, node, xpExpr, eExcpt, sMsg=\"\"): \"\"\"report an xpath error\"\"\" try: Deco._s_prev_xpath_error except AttributeError:", "1505,390 1505,440 985,440\"/> or <Baseline points=\"985,435 1505,435\"/> \"\"\" def __init__(self, cfg, sSurname, xpCtxt):", "= s Deco._prev_xpath_error_count += 1 if Deco._prev_xpath_error_count > 10: return try: sNode =", "= wxh.AddLine( [(self._x1, -self._y1), (self._x2, -self._y2)] , LineWidth=iLineWidth , LineColor=sLineColor) lo.append(obj) return lo", "xpCtxt) self.xpContent = cfg.get(sSurname, \"xpath_content\") self.xpFontColor = cfg.get(sSurname, \"xpath_font_color\") self.xpFit = cfg.get(sSurname, \"xpath_fit_text_size\").lower()", "None,None,None,None,None sToPageNum = self.xpathToStr(node, self.xpAttrToPageNumber , None) if sToPageNum: index = int(sToPageNum) -", "xpCtxt) #now get the xpath expressions that let us find the rectangle line" ]
[ "variable is:\", first) print(\"Your second variable is:\", second) print(\"Your third variable is:\", third)", "third) # $ python ex13.py first 2nd 3rd # The script is called:", "python ex13.py first 2nd 3rd # The script is called: ex13.py # Your", "script is called: ex13.py # Your first variable is: first # Your second", "import argv script, first, second, third = argv print(\"The script is called:\", script)", "is: first # Your second variable is: 2nd # Your third variable is:", "# $ python ex13.py first 2nd 3rd # The script is called: ex13.py", "# The script is called: ex13.py # Your first variable is: first #", "variable is: first # Your second variable is: 2nd # Your third variable", "The script is called: ex13.py # Your first variable is: first # Your", "sys import argv script, first, second, third = argv print(\"The script is called:\",", "# Your first variable is: first # Your second variable is: 2nd #", "second variable is:\", second) print(\"Your third variable is:\", third) # $ python ex13.py", "ex13.py # Your first variable is: first # Your second variable is: 2nd", "first 2nd 3rd # The script is called: ex13.py # Your first variable", "variable is:\", third) # $ python ex13.py first 2nd 3rd # The script", "= argv print(\"The script is called:\", script) print(\"Your first variable is:\", first) print(\"Your", "is:\", second) print(\"Your third variable is:\", third) # $ python ex13.py first 2nd", "first # Your second variable is: 2nd # Your third variable is: 3rd", "$ python ex13.py first 2nd 3rd # The script is called: ex13.py #", "<filename>ex/ex7.py from sys import argv script, first, second, third = argv print(\"The script", "Your first variable is: first # Your second variable is: 2nd # Your", "is:\", first) print(\"Your second variable is:\", second) print(\"Your third variable is:\", third) #", "second, third = argv print(\"The script is called:\", script) print(\"Your first variable is:\",", "script is called:\", script) print(\"Your first variable is:\", first) print(\"Your second variable is:\",", "third variable is:\", third) # $ python ex13.py first 2nd 3rd # The", "3rd # The script is called: ex13.py # Your first variable is: first", "first) print(\"Your second variable is:\", second) print(\"Your third variable is:\", third) # $", "print(\"Your second variable is:\", second) print(\"Your third variable is:\", third) # $ python", "second) print(\"Your third variable is:\", third) # $ python ex13.py first 2nd 3rd", "script, first, second, third = argv print(\"The script is called:\", script) print(\"Your first", "2nd 3rd # The script is called: ex13.py # Your first variable is:", "is:\", third) # $ python ex13.py first 2nd 3rd # The script is", "variable is:\", second) print(\"Your third variable is:\", third) # $ python ex13.py first", "first variable is: first # Your second variable is: 2nd # Your third", "called:\", script) print(\"Your first variable is:\", first) print(\"Your second variable is:\", second) print(\"Your", "called: ex13.py # Your first variable is: first # Your second variable is:", "argv script, first, second, third = argv print(\"The script is called:\", script) print(\"Your", "script) print(\"Your first variable is:\", first) print(\"Your second variable is:\", second) print(\"Your third", "first variable is:\", first) print(\"Your second variable is:\", second) print(\"Your third variable is:\",", "ex13.py first 2nd 3rd # The script is called: ex13.py # Your first", "print(\"Your first variable is:\", first) print(\"Your second variable is:\", second) print(\"Your third variable", "third = argv print(\"The script is called:\", script) print(\"Your first variable is:\", first)", "is called: ex13.py # Your first variable is: first # Your second variable", "first, second, third = argv print(\"The script is called:\", script) print(\"Your first variable", "print(\"Your third variable is:\", third) # $ python ex13.py first 2nd 3rd #", "from sys import argv script, first, second, third = argv print(\"The script is", "is called:\", script) print(\"Your first variable is:\", first) print(\"Your second variable is:\", second)", "print(\"The script is called:\", script) print(\"Your first variable is:\", first) print(\"Your second variable", "argv print(\"The script is called:\", script) print(\"Your first variable is:\", first) print(\"Your second" ]
[ "'.' LIVERELOAD = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'livereload.js', ) class LiveReloadHandler(websocket.WebSocketHandler): waiters = set() _last_reload_time", "True } self._last_reload_time = time.time() for waiter in LiveReloadHandler.waiters: try: waiter.write_message(msg) except: logging.error('Error", "!= 'text/html': return ua = self.request.headers.get('User-Agent', 'bot').lower() if 'msie' not in ua: self.write('<script", "= line.replace('{{port}}', str(PORT)) self.write(line) f.close() handlers = [ (r'/livereload', LiveReloadHandler), (r'/livereload.js', LiveReloadJSHandler), (r'(.*)',", "times logging.info('ignore this reload action') return logging.info('Reload %s waiters', len(self.waiters)) msg = {", "enable_pretty_logging() app = Application(handlers=handlers) app.listen(port) print('Serving path %s on 127.0.0.1:%s' % (root, port))", "800).start() class IndexHandler(RequestHandler): def get(self, path='/'): abspath = os.path.join(os.path.abspath(ROOT), path.lstrip('/')) mime_type, encoding =", "= mime_type self.set_header('Content-Type', mime_type) self.read_path(abspath) def inject_livereload(self): if self.mime_type != 'text/html': return ua", "logging.info('Reading Guardfile') execfile('Guardfile') else: logging.info('No Guardfile') Task.add(os.getcwd()) LiveReloadHandler._last_reload_time = time.time() logging.info('Start watching changes')", "self.set_header('Content-Type', 'application/javascript') for line in f: if '{{port}}' in line: line = line.replace('{{port}}',", "not changes: return if time.time() - self._last_reload_time < 3: # if you changed", "if time.time() - self._last_reload_time < 3: # if you changed lot of files", "root='.', autoraise=False): global PORT PORT = port global ROOT if root is None:", "os import logging import time import mimetypes import webbrowser from tornado import ioloop", "refresh too many times logging.info('ignore this reload action') return logging.info('Reload %s waiters', len(self.waiters))", "self.mime_type = mime_type self.set_header('Content-Type', mime_type) self.read_path(abspath) def inject_livereload(self): if self.mime_type != 'text/html': return", "LiveReloadHandler.waiters.remove(waiter) def on_message(self, message): \"\"\"Handshake with livereload.js 1. client send 'hello' 2. server", "if os.path.exists('Guardfile'): logging.info('Reading Guardfile') execfile('Guardfile') else: logging.info('No Guardfile') Task.add(os.getcwd()) LiveReloadHandler._last_reload_time = time.time() logging.info('Start", "files = os.listdir(root) self.write('<ul>') for f in files: path = os.path.join(root, f) self.write('<li>')", "'bot').lower() if 'msie' not in ua: self.write('<script src=\"/livereload.js\"></script>') def read_path(self, abspath): filepath =", "RequestHandler, Application from tornado.util import ObjectDict from tornado.options import enable_pretty_logging from livereload.task import", "self.inject_livereload() self.write(line) return self.send_error(404) return def create_index(self, root): self.inject_livereload() files = os.listdir(root) self.write('<ul>')", "None def allow_draft76(self): return True def on_close(self): if self in LiveReloadHandler.waiters: LiveReloadHandler.waiters.remove(self) def", "protocols = message.protocols protocols.append( 'http://livereload.com/protocols/2.x-remote-control' ) handshake['protocols'] = protocols handshake['serverName'] = 'livereload-tornado' self.send_message(handshake)", "'info' http://help.livereload.com/kb/ecosystem/livereload-protocol \"\"\" message = ObjectDict(escape.json_decode(message)) if message.command == 'hello': handshake = {}", "return def create_index(self, root): self.inject_livereload() files = os.listdir(root) self.write('<ul>') for f in files:", "= os.path.join(os.path.abspath(ROOT), path.lstrip('/')) mime_type, encoding = mimetypes.guess_type(abspath) if not mime_type: mime_type = 'text/html'", "app.listen(port) print('Serving path %s on 127.0.0.1:%s' % (root, port)) if autoraise: webbrowser.open( 'http://127.0.0.1:%s'", "files in one time # it will refresh too many times logging.info('ignore this", "dict): message = escape.json_encode(message) try: self.write_message(message) except: logging.error('Error sending message', exc_info=True) def watch_tasks(self):", "tornado import escape from tornado import websocket from tornado.web import RequestHandler, Application from", "waiter.write_message(msg) except: logging.error('Error sending message', exc_info=True) LiveReloadHandler.waiters.remove(waiter) def on_message(self, message): \"\"\"Handshake with livereload.js", "return if time.time() - self._last_reload_time < 3: # if you changed lot of", "'text/html': return ua = self.request.headers.get('User-Agent', 'bot').lower() if 'msie' not in ua: self.write('<script src=\"/livereload.js\"></script>')", "utf-8 -*- \"\"\"livereload.app Core Server of LiveReload. \"\"\" import os import logging import", "LiveReloadJSHandler(RequestHandler): def get(self): f = open(LIVERELOAD) self.set_header('Content-Type', 'application/javascript') for line in f: if", "LiveReloadHandler.waiters.remove(self) def send_message(self, message): if isinstance(message, dict): message = escape.json_encode(message) try: self.write_message(message) except:", "tornado import websocket from tornado.web import RequestHandler, Application from tornado.util import ObjectDict from", "def on_message(self, message): \"\"\"Handshake with livereload.js 1. client send 'hello' 2. server reply", "'application/javascript') for line in f: if '{{port}}' in line: line = line.replace('{{port}}', str(PORT))", "def watch_tasks(self): changes = Task.watch() if not changes: return if time.time() - self._last_reload_time", "2. server reply 'hello' 3. client send 'info' http://help.livereload.com/kb/ecosystem/livereload-protocol \"\"\" message = ObjectDict(escape.json_decode(message))", ") class LiveReloadHandler(websocket.WebSocketHandler): waiters = set() _last_reload_time = None def allow_draft76(self): return True", "f = open(LIVERELOAD) self.set_header('Content-Type', 'application/javascript') for line in f: if '{{port}}' in line:", "line: line = line.replace('{{port}}', str(PORT)) self.write(line) f.close() handlers = [ (r'/livereload', LiveReloadHandler), (r'/livereload.js',", "action') return logging.info('Reload %s waiters', len(self.waiters)) msg = { 'command': 'reload', 'path': '*',", "def on_close(self): if self in LiveReloadHandler.waiters: LiveReloadHandler.waiters.remove(self) def send_message(self, message): if isinstance(message, dict):", "return elif not os.path.exists(abspath): filepath = abspath + '.html' if os.path.exists(filepath): for line", "livereload.task import Task PORT = 35729 ROOT = '.' LIVERELOAD = os.path.join( os.path.abspath(os.path.dirname(__file__)),", "watch_tasks(self): changes = Task.watch() if not changes: return if time.time() - self._last_reload_time <", "logging.info('Browser Connected: %s' % message.url) LiveReloadHandler.waiters.add(self) if not LiveReloadHandler._last_reload_time: if os.path.exists('Guardfile'): logging.info('Reading Guardfile')", "self.send_message(handshake) if message.command == 'info' and 'url' in message: logging.info('Browser Connected: %s' %", "LiveReloadHandler.waiters: try: waiter.write_message(msg) except: logging.error('Error sending message', exc_info=True) LiveReloadHandler.waiters.remove(waiter) def on_message(self, message): \"\"\"Handshake", "3: # if you changed lot of files in one time # it", "= 'text/html' self.mime_type = mime_type self.set_header('Content-Type', mime_type) self.read_path(abspath) def inject_livereload(self): if self.mime_type !=", "client send 'hello' 2. server reply 'hello' 3. client send 'info' http://help.livereload.com/kb/ecosystem/livereload-protocol \"\"\"", "try: waiter.write_message(msg) except: logging.error('Error sending message', exc_info=True) LiveReloadHandler.waiters.remove(waiter) def on_message(self, message): \"\"\"Handshake with", "message.command == 'hello': handshake = {} handshake['command'] = 'hello' protocols = message.protocols protocols.append(", "mime_type) self.read_path(abspath) def inject_livereload(self): if self.mime_type != 'text/html': return ua = self.request.headers.get('User-Agent', 'bot').lower()", "else: logging.info('No Guardfile') Task.add(os.getcwd()) LiveReloadHandler._last_reload_time = time.time() logging.info('Start watching changes') ioloop.PeriodicCallback(self.watch_tasks, 800).start() class", "from tornado.options import enable_pretty_logging from livereload.task import Task PORT = 35729 ROOT =", "if message.command == 'info' and 'url' in message: logging.info('Browser Connected: %s' % message.url)", "line: self.inject_livereload() self.write(line) return self.send_error(404) return def create_index(self, root): self.inject_livereload() files = os.listdir(root)", "'text/html' self.mime_type = mime_type self.set_header('Content-Type', mime_type) self.read_path(abspath) def inject_livereload(self): if self.mime_type != 'text/html':", "ua: self.write('<script src=\"/livereload.js\"></script>') def read_path(self, abspath): filepath = abspath if abspath.endswith('/'): filepath =", "127.0.0.1:%s' % (root, port)) if autoraise: webbrowser.open( 'http://127.0.0.1:%s' % port, new=2, autoraise=True )", "# -*- coding: utf-8 -*- \"\"\"livereload.app Core Server of LiveReload. \"\"\" import os", "ROOT if root is None: root = '.' ROOT = root logging.getLogger().setLevel(logging.INFO) enable_pretty_logging()", "not mime_type: mime_type = 'text/html' self.mime_type = mime_type self.set_header('Content-Type', mime_type) self.read_path(abspath) def inject_livereload(self):", "import time import mimetypes import webbrowser from tornado import ioloop from tornado import", "msg = { 'command': 'reload', 'path': '*', 'liveCSS': True } self._last_reload_time = time.time()", "'hello' protocols = message.protocols protocols.append( 'http://livereload.com/protocols/2.x-remote-control' ) handshake['protocols'] = protocols handshake['serverName'] = 'livereload-tornado'", "if autoraise: webbrowser.open( 'http://127.0.0.1:%s' % port, new=2, autoraise=True ) ioloop.IOLoop.instance().start() if __name__ ==", "Server of LiveReload. \"\"\" import os import logging import time import mimetypes import", "in f: if '{{port}}' in line: line = line.replace('{{port}}', str(PORT)) self.write(line) f.close() handlers", "livereload.js 1. client send 'hello' 2. server reply 'hello' 3. client send 'info'", "import enable_pretty_logging from livereload.task import Task PORT = 35729 ROOT = '.' LIVERELOAD", "\"\"\"livereload.app Core Server of LiveReload. \"\"\" import os import logging import time import", "'reload', 'path': '*', 'liveCSS': True } self._last_reload_time = time.time() for waiter in LiveReloadHandler.waiters:", "= 'livereload-tornado' self.send_message(handshake) if message.command == 'info' and 'url' in message: logging.info('Browser Connected:", "import websocket from tornado.web import RequestHandler, Application from tornado.util import ObjectDict from tornado.options", "= { 'command': 'reload', 'path': '*', 'liveCSS': True } self._last_reload_time = time.time() for", "in message: logging.info('Browser Connected: %s' % message.url) LiveReloadHandler.waiters.add(self) if not LiveReloadHandler._last_reload_time: if os.path.exists('Guardfile'):", "# it will refresh too many times logging.info('ignore this reload action') return logging.info('Reload", "if not os.path.exists(filepath): self.create_index(abspath) return elif not os.path.exists(abspath): filepath = abspath + '.html'", "] def start(port=35729, root='.', autoraise=False): global PORT PORT = port global ROOT if", "= 35729 ROOT = '.' LIVERELOAD = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'livereload.js', ) class LiveReloadHandler(websocket.WebSocketHandler):", "not in ua: self.write('<script src=\"/livereload.js\"></script>') def read_path(self, abspath): filepath = abspath if abspath.endswith('/'):", "in ua: self.write('<script src=\"/livereload.js\"></script>') def read_path(self, abspath): filepath = abspath if abspath.endswith('/'): filepath", "handlers = [ (r'/livereload', LiveReloadHandler), (r'/livereload.js', LiveReloadJSHandler), (r'(.*)', IndexHandler), ] def start(port=35729, root='.',", "_last_reload_time = None def allow_draft76(self): return True def on_close(self): if self in LiveReloadHandler.waiters:", "exc_info=True) def watch_tasks(self): changes = Task.watch() if not changes: return if time.time() -", "mime_type self.set_header('Content-Type', mime_type) self.read_path(abspath) def inject_livereload(self): if self.mime_type != 'text/html': return ua =", "f: if '{{port}}' in line: line = line.replace('{{port}}', str(PORT)) self.write(line) f.close() handlers =", "line = line.replace('{{port}}', str(PORT)) self.write(line) f.close() handlers = [ (r'/livereload', LiveReloadHandler), (r'/livereload.js', LiveReloadJSHandler),", "'info' and 'url' in message: logging.info('Browser Connected: %s' % message.url) LiveReloadHandler.waiters.add(self) if not", "self.read_path(abspath) def inject_livereload(self): if self.mime_type != 'text/html': return ua = self.request.headers.get('User-Agent', 'bot').lower() if", "start(port=35729, root='.', autoraise=False): global PORT PORT = port global ROOT if root is", "path %s on 127.0.0.1:%s' % (root, port)) if autoraise: webbrowser.open( 'http://127.0.0.1:%s' % port,", "% (f, f)) self.write('</li>') self.write('</ul>') class LiveReloadJSHandler(RequestHandler): def get(self): f = open(LIVERELOAD) self.set_header('Content-Type',", "self.request.headers.get('User-Agent', 'bot').lower() if 'msie' not in ua: self.write('<script src=\"/livereload.js\"></script>') def read_path(self, abspath): filepath", "href=\"%s/\">%s</a>' % (f, f)) else: self.write('<a href=\"%s\">%s</a>' % (f, f)) self.write('</li>') self.write('</ul>') class", "isinstance(message, dict): message = escape.json_encode(message) try: self.write_message(message) except: logging.error('Error sending message', exc_info=True) def", "import ioloop from tornado import escape from tornado import websocket from tornado.web import", "'hello' 3. client send 'info' http://help.livereload.com/kb/ecosystem/livereload-protocol \"\"\" message = ObjectDict(escape.json_decode(message)) if message.command ==", "abspath + '.html' if os.path.exists(filepath): for line in open(filepath): if '</head>' in line:", "def allow_draft76(self): return True def on_close(self): if self in LiveReloadHandler.waiters: LiveReloadHandler.waiters.remove(self) def send_message(self,", "in LiveReloadHandler.waiters: LiveReloadHandler.waiters.remove(self) def send_message(self, message): if isinstance(message, dict): message = escape.json_encode(message) try:", "= Task.watch() if not changes: return if time.time() - self._last_reload_time < 3: #", "from tornado import ioloop from tornado import escape from tornado import websocket from", "= os.path.join(root, f) self.write('<li>') if os.path.isdir(path): self.write('<a href=\"%s/\">%s</a>' % (f, f)) else: self.write('<a", "path='/'): abspath = os.path.join(os.path.abspath(ROOT), path.lstrip('/')) mime_type, encoding = mimetypes.guess_type(abspath) if not mime_type: mime_type", "= time.time() logging.info('Start watching changes') ioloop.PeriodicCallback(self.watch_tasks, 800).start() class IndexHandler(RequestHandler): def get(self, path='/'): abspath", "time import mimetypes import webbrowser from tornado import ioloop from tornado import escape", "from tornado.util import ObjectDict from tornado.options import enable_pretty_logging from livereload.task import Task PORT", "self.create_index(abspath) return elif not os.path.exists(abspath): filepath = abspath + '.html' if os.path.exists(filepath): for", "self in LiveReloadHandler.waiters: LiveReloadHandler.waiters.remove(self) def send_message(self, message): if isinstance(message, dict): message = escape.json_encode(message)", "too many times logging.info('ignore this reload action') return logging.info('Reload %s waiters', len(self.waiters)) msg", "= time.time() for waiter in LiveReloadHandler.waiters: try: waiter.write_message(msg) except: logging.error('Error sending message', exc_info=True)", "1. client send 'hello' 2. server reply 'hello' 3. client send 'info' http://help.livereload.com/kb/ecosystem/livereload-protocol", "self.write('</li>') self.write('</ul>') class LiveReloadJSHandler(RequestHandler): def get(self): f = open(LIVERELOAD) self.set_header('Content-Type', 'application/javascript') for line", "webbrowser from tornado import ioloop from tornado import escape from tornado import websocket", "send 'info' http://help.livereload.com/kb/ecosystem/livereload-protocol \"\"\" message = ObjectDict(escape.json_decode(message)) if message.command == 'hello': handshake =", "os.path.abspath(os.path.dirname(__file__)), 'livereload.js', ) class LiveReloadHandler(websocket.WebSocketHandler): waiters = set() _last_reload_time = None def allow_draft76(self):", "from tornado.web import RequestHandler, Application from tornado.util import ObjectDict from tornado.options import enable_pretty_logging", "app = Application(handlers=handlers) app.listen(port) print('Serving path %s on 127.0.0.1:%s' % (root, port)) if", "open(LIVERELOAD) self.set_header('Content-Type', 'application/javascript') for line in f: if '{{port}}' in line: line =", "message): \"\"\"Handshake with livereload.js 1. client send 'hello' 2. server reply 'hello' 3.", "mimetypes import webbrowser from tornado import ioloop from tornado import escape from tornado", "path = os.path.join(root, f) self.write('<li>') if os.path.isdir(path): self.write('<a href=\"%s/\">%s</a>' % (f, f)) else:", "line in f: if '{{port}}' in line: line = line.replace('{{port}}', str(PORT)) self.write(line) f.close()", "in line: line = line.replace('{{port}}', str(PORT)) self.write(line) f.close() handlers = [ (r'/livereload', LiveReloadHandler),", "on 127.0.0.1:%s' % (root, port)) if autoraise: webbrowser.open( 'http://127.0.0.1:%s' % port, new=2, autoraise=True", "= os.listdir(root) self.write('<ul>') for f in files: path = os.path.join(root, f) self.write('<li>') if", "< 3: # if you changed lot of files in one time #", "os.path.exists(filepath): for line in open(filepath): if '</head>' in line: self.inject_livereload() self.write(line) return self.send_error(404)", "# if you changed lot of files in one time # it will", "= {} handshake['command'] = 'hello' protocols = message.protocols protocols.append( 'http://livereload.com/protocols/2.x-remote-control' ) handshake['protocols'] =", "root = '.' ROOT = root logging.getLogger().setLevel(logging.INFO) enable_pretty_logging() app = Application(handlers=handlers) app.listen(port) print('Serving", "self.write('<script src=\"/livereload.js\"></script>') def read_path(self, abspath): filepath = abspath if abspath.endswith('/'): filepath = os.path.join(abspath,", "ua = self.request.headers.get('User-Agent', 'bot').lower() if 'msie' not in ua: self.write('<script src=\"/livereload.js\"></script>') def read_path(self,", "PORT = 35729 ROOT = '.' LIVERELOAD = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'livereload.js', ) class", "message', exc_info=True) def watch_tasks(self): changes = Task.watch() if not changes: return if time.time()", "it will refresh too many times logging.info('ignore this reload action') return logging.info('Reload %s", "% (root, port)) if autoraise: webbrowser.open( 'http://127.0.0.1:%s' % port, new=2, autoraise=True ) ioloop.IOLoop.instance().start()", "class LiveReloadJSHandler(RequestHandler): def get(self): f = open(LIVERELOAD) self.set_header('Content-Type', 'application/javascript') for line in f:", "'{{port}}' in line: line = line.replace('{{port}}', str(PORT)) self.write(line) f.close() handlers = [ (r'/livereload',", "'http://livereload.com/protocols/2.x-remote-control' ) handshake['protocols'] = protocols handshake['serverName'] = 'livereload-tornado' self.send_message(handshake) if message.command == 'info'", "if abspath.endswith('/'): filepath = os.path.join(abspath, 'index.html') if not os.path.exists(filepath): self.create_index(abspath) return elif not", "len(self.waiters)) msg = { 'command': 'reload', 'path': '*', 'liveCSS': True } self._last_reload_time =", "LiveReloadHandler.waiters.add(self) if not LiveReloadHandler._last_reload_time: if os.path.exists('Guardfile'): logging.info('Reading Guardfile') execfile('Guardfile') else: logging.info('No Guardfile') Task.add(os.getcwd())", "= protocols handshake['serverName'] = 'livereload-tornado' self.send_message(handshake) if message.command == 'info' and 'url' in", "self._last_reload_time = time.time() for waiter in LiveReloadHandler.waiters: try: waiter.write_message(msg) except: logging.error('Error sending message',", "autoraise: webbrowser.open( 'http://127.0.0.1:%s' % port, new=2, autoraise=True ) ioloop.IOLoop.instance().start() if __name__ == '__main__':", "def get(self): f = open(LIVERELOAD) self.set_header('Content-Type', 'application/javascript') for line in f: if '{{port}}'", "self.write(line) f.close() handlers = [ (r'/livereload', LiveReloadHandler), (r'/livereload.js', LiveReloadJSHandler), (r'(.*)', IndexHandler), ] def", "time.time() - self._last_reload_time < 3: # if you changed lot of files in", "changes') ioloop.PeriodicCallback(self.watch_tasks, 800).start() class IndexHandler(RequestHandler): def get(self, path='/'): abspath = os.path.join(os.path.abspath(ROOT), path.lstrip('/')) mime_type,", "for f in files: path = os.path.join(root, f) self.write('<li>') if os.path.isdir(path): self.write('<a href=\"%s/\">%s</a>'", "execfile('Guardfile') else: logging.info('No Guardfile') Task.add(os.getcwd()) LiveReloadHandler._last_reload_time = time.time() logging.info('Start watching changes') ioloop.PeriodicCallback(self.watch_tasks, 800).start()", "Application(handlers=handlers) app.listen(port) print('Serving path %s on 127.0.0.1:%s' % (root, port)) if autoraise: webbrowser.open(", "= abspath if abspath.endswith('/'): filepath = os.path.join(abspath, 'index.html') if not os.path.exists(filepath): self.create_index(abspath) return", "'livereload-tornado' self.send_message(handshake) if message.command == 'info' and 'url' in message: logging.info('Browser Connected: %s'", "ObjectDict from tornado.options import enable_pretty_logging from livereload.task import Task PORT = 35729 ROOT", "Task.watch() if not changes: return if time.time() - self._last_reload_time < 3: # if", "allow_draft76(self): return True def on_close(self): if self in LiveReloadHandler.waiters: LiveReloadHandler.waiters.remove(self) def send_message(self, message):", "this reload action') return logging.info('Reload %s waiters', len(self.waiters)) msg = { 'command': 'reload',", "return ua = self.request.headers.get('User-Agent', 'bot').lower() if 'msie' not in ua: self.write('<script src=\"/livereload.js\"></script>') def", "'url' in message: logging.info('Browser Connected: %s' % message.url) LiveReloadHandler.waiters.add(self) if not LiveReloadHandler._last_reload_time: if", "os.path.exists('Guardfile'): logging.info('Reading Guardfile') execfile('Guardfile') else: logging.info('No Guardfile') Task.add(os.getcwd()) LiveReloadHandler._last_reload_time = time.time() logging.info('Start watching", "not os.path.exists(abspath): filepath = abspath + '.html' if os.path.exists(filepath): for line in open(filepath):", "if os.path.exists(filepath): for line in open(filepath): if '</head>' in line: self.inject_livereload() self.write(line) return", "self.write('<li>') if os.path.isdir(path): self.write('<a href=\"%s/\">%s</a>' % (f, f)) else: self.write('<a href=\"%s\">%s</a>' % (f,", "(f, f)) else: self.write('<a href=\"%s\">%s</a>' % (f, f)) self.write('</li>') self.write('</ul>') class LiveReloadJSHandler(RequestHandler): def", "os.path.exists(abspath): filepath = abspath + '.html' if os.path.exists(filepath): for line in open(filepath): if", "IndexHandler), ] def start(port=35729, root='.', autoraise=False): global PORT PORT = port global ROOT", "global ROOT if root is None: root = '.' ROOT = root logging.getLogger().setLevel(logging.INFO)", "filepath = abspath if abspath.endswith('/'): filepath = os.path.join(abspath, 'index.html') if not os.path.exists(filepath): self.create_index(abspath)", "send_message(self, message): if isinstance(message, dict): message = escape.json_encode(message) try: self.write_message(message) except: logging.error('Error sending", "files: path = os.path.join(root, f) self.write('<li>') if os.path.isdir(path): self.write('<a href=\"%s/\">%s</a>' % (f, f))", "'hello' 2. server reply 'hello' 3. client send 'info' http://help.livereload.com/kb/ecosystem/livereload-protocol \"\"\" message =", "if '</head>' in line: self.inject_livereload() self.write(line) return self.send_error(404) return def create_index(self, root): self.inject_livereload()", "Application from tornado.util import ObjectDict from tornado.options import enable_pretty_logging from livereload.task import Task", "= os.path.join( os.path.abspath(os.path.dirname(__file__)), 'livereload.js', ) class LiveReloadHandler(websocket.WebSocketHandler): waiters = set() _last_reload_time = None", "'index.html') if not os.path.exists(filepath): self.create_index(abspath) return elif not os.path.exists(abspath): filepath = abspath +", "= Application(handlers=handlers) app.listen(port) print('Serving path %s on 127.0.0.1:%s' % (root, port)) if autoraise:", "ROOT = '.' LIVERELOAD = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'livereload.js', ) class LiveReloadHandler(websocket.WebSocketHandler): waiters =", "tornado.options import enable_pretty_logging from livereload.task import Task PORT = 35729 ROOT = '.'", "time.time() for waiter in LiveReloadHandler.waiters: try: waiter.write_message(msg) except: logging.error('Error sending message', exc_info=True) LiveReloadHandler.waiters.remove(waiter)", "class LiveReloadHandler(websocket.WebSocketHandler): waiters = set() _last_reload_time = None def allow_draft76(self): return True def", "from livereload.task import Task PORT = 35729 ROOT = '.' LIVERELOAD = os.path.join(", "import logging import time import mimetypes import webbrowser from tornado import ioloop from", "} self._last_reload_time = time.time() for waiter in LiveReloadHandler.waiters: try: waiter.write_message(msg) except: logging.error('Error sending", "def start(port=35729, root='.', autoraise=False): global PORT PORT = port global ROOT if root", "\"\"\" message = ObjectDict(escape.json_decode(message)) if message.command == 'hello': handshake = {} handshake['command'] =", "import escape from tornado import websocket from tornado.web import RequestHandler, Application from tornado.util", "= '.' LIVERELOAD = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'livereload.js', ) class LiveReloadHandler(websocket.WebSocketHandler): waiters = set()", ") handshake['protocols'] = protocols handshake['serverName'] = 'livereload-tornado' self.send_message(handshake) if message.command == 'info' and", "will refresh too many times logging.info('ignore this reload action') return logging.info('Reload %s waiters',", "os.path.isdir(path): self.write('<a href=\"%s/\">%s</a>' % (f, f)) else: self.write('<a href=\"%s\">%s</a>' % (f, f)) self.write('</li>')", "self.write('<ul>') for f in files: path = os.path.join(root, f) self.write('<li>') if os.path.isdir(path): self.write('<a", "%s' % message.url) LiveReloadHandler.waiters.add(self) if not LiveReloadHandler._last_reload_time: if os.path.exists('Guardfile'): logging.info('Reading Guardfile') execfile('Guardfile') else:", "self.mime_type != 'text/html': return ua = self.request.headers.get('User-Agent', 'bot').lower() if 'msie' not in ua:", "= 'hello' protocols = message.protocols protocols.append( 'http://livereload.com/protocols/2.x-remote-control' ) handshake['protocols'] = protocols handshake['serverName'] =", "send 'hello' 2. server reply 'hello' 3. client send 'info' http://help.livereload.com/kb/ecosystem/livereload-protocol \"\"\" message", "escape.json_encode(message) try: self.write_message(message) except: logging.error('Error sending message', exc_info=True) def watch_tasks(self): changes = Task.watch()", "'.html' if os.path.exists(filepath): for line in open(filepath): if '</head>' in line: self.inject_livereload() self.write(line)", "Guardfile') execfile('Guardfile') else: logging.info('No Guardfile') Task.add(os.getcwd()) LiveReloadHandler._last_reload_time = time.time() logging.info('Start watching changes') ioloop.PeriodicCallback(self.watch_tasks,", "not LiveReloadHandler._last_reload_time: if os.path.exists('Guardfile'): logging.info('Reading Guardfile') execfile('Guardfile') else: logging.info('No Guardfile') Task.add(os.getcwd()) LiveReloadHandler._last_reload_time =", "from tornado import escape from tornado import websocket from tornado.web import RequestHandler, Application", "PORT PORT = port global ROOT if root is None: root = '.'", "{ 'command': 'reload', 'path': '*', 'liveCSS': True } self._last_reload_time = time.time() for waiter", "'command': 'reload', 'path': '*', 'liveCSS': True } self._last_reload_time = time.time() for waiter in", "mime_type = 'text/html' self.mime_type = mime_type self.set_header('Content-Type', mime_type) self.read_path(abspath) def inject_livereload(self): if self.mime_type", "LiveReloadHandler._last_reload_time: if os.path.exists('Guardfile'): logging.info('Reading Guardfile') execfile('Guardfile') else: logging.info('No Guardfile') Task.add(os.getcwd()) LiveReloadHandler._last_reload_time = time.time()", "= root logging.getLogger().setLevel(logging.INFO) enable_pretty_logging() app = Application(handlers=handlers) app.listen(port) print('Serving path %s on 127.0.0.1:%s'", "abspath if abspath.endswith('/'): filepath = os.path.join(abspath, 'index.html') if not os.path.exists(filepath): self.create_index(abspath) return elif", "- self._last_reload_time < 3: # if you changed lot of files in one", "protocols.append( 'http://livereload.com/protocols/2.x-remote-control' ) handshake['protocols'] = protocols handshake['serverName'] = 'livereload-tornado' self.send_message(handshake) if message.command ==", "import webbrowser from tornado import ioloop from tornado import escape from tornado import", "message.protocols protocols.append( 'http://livereload.com/protocols/2.x-remote-control' ) handshake['protocols'] = protocols handshake['serverName'] = 'livereload-tornado' self.send_message(handshake) if message.command", "logging.getLogger().setLevel(logging.INFO) enable_pretty_logging() app = Application(handlers=handlers) app.listen(port) print('Serving path %s on 127.0.0.1:%s' % (root,", "logging.error('Error sending message', exc_info=True) LiveReloadHandler.waiters.remove(waiter) def on_message(self, message): \"\"\"Handshake with livereload.js 1. client", "= os.path.join(abspath, 'index.html') if not os.path.exists(filepath): self.create_index(abspath) return elif not os.path.exists(abspath): filepath =", "get(self, path='/'): abspath = os.path.join(os.path.abspath(ROOT), path.lstrip('/')) mime_type, encoding = mimetypes.guess_type(abspath) if not mime_type:", "except: logging.error('Error sending message', exc_info=True) def watch_tasks(self): changes = Task.watch() if not changes:", "if isinstance(message, dict): message = escape.json_encode(message) try: self.write_message(message) except: logging.error('Error sending message', exc_info=True)", "LiveReloadHandler(websocket.WebSocketHandler): waiters = set() _last_reload_time = None def allow_draft76(self): return True def on_close(self):", "waiters', len(self.waiters)) msg = { 'command': 'reload', 'path': '*', 'liveCSS': True } self._last_reload_time", "and 'url' in message: logging.info('Browser Connected: %s' % message.url) LiveReloadHandler.waiters.add(self) if not LiveReloadHandler._last_reload_time:", "if you changed lot of files in one time # it will refresh", "waiters = set() _last_reload_time = None def allow_draft76(self): return True def on_close(self): if", "def read_path(self, abspath): filepath = abspath if abspath.endswith('/'): filepath = os.path.join(abspath, 'index.html') if", "line in open(filepath): if '</head>' in line: self.inject_livereload() self.write(line) return self.send_error(404) return def", "import ObjectDict from tornado.options import enable_pretty_logging from livereload.task import Task PORT = 35729", "server reply 'hello' 3. client send 'info' http://help.livereload.com/kb/ecosystem/livereload-protocol \"\"\" message = ObjectDict(escape.json_decode(message)) if", "ROOT = root logging.getLogger().setLevel(logging.INFO) enable_pretty_logging() app = Application(handlers=handlers) app.listen(port) print('Serving path %s on", "-*- \"\"\"livereload.app Core Server of LiveReload. \"\"\" import os import logging import time", "time # it will refresh too many times logging.info('ignore this reload action') return", "= open(LIVERELOAD) self.set_header('Content-Type', 'application/javascript') for line in f: if '{{port}}' in line: line", "abspath): filepath = abspath if abspath.endswith('/'): filepath = os.path.join(abspath, 'index.html') if not os.path.exists(filepath):", "if os.path.isdir(path): self.write('<a href=\"%s/\">%s</a>' % (f, f)) else: self.write('<a href=\"%s\">%s</a>' % (f, f))", "port global ROOT if root is None: root = '.' ROOT = root", "'liveCSS': True } self._last_reload_time = time.time() for waiter in LiveReloadHandler.waiters: try: waiter.write_message(msg) except:", "IndexHandler(RequestHandler): def get(self, path='/'): abspath = os.path.join(os.path.abspath(ROOT), path.lstrip('/')) mime_type, encoding = mimetypes.guess_type(abspath) if", "client send 'info' http://help.livereload.com/kb/ecosystem/livereload-protocol \"\"\" message = ObjectDict(escape.json_decode(message)) if message.command == 'hello': handshake", "if not LiveReloadHandler._last_reload_time: if os.path.exists('Guardfile'): logging.info('Reading Guardfile') execfile('Guardfile') else: logging.info('No Guardfile') Task.add(os.getcwd()) LiveReloadHandler._last_reload_time", "LiveReloadHandler._last_reload_time = time.time() logging.info('Start watching changes') ioloop.PeriodicCallback(self.watch_tasks, 800).start() class IndexHandler(RequestHandler): def get(self, path='/'):", "port)) if autoraise: webbrowser.open( 'http://127.0.0.1:%s' % port, new=2, autoraise=True ) ioloop.IOLoop.instance().start() if __name__", "os.path.join(os.path.abspath(ROOT), path.lstrip('/')) mime_type, encoding = mimetypes.guess_type(abspath) if not mime_type: mime_type = 'text/html' self.mime_type", "handshake['protocols'] = protocols handshake['serverName'] = 'livereload-tornado' self.send_message(handshake) if message.command == 'info' and 'url'", "mimetypes.guess_type(abspath) if not mime_type: mime_type = 'text/html' self.mime_type = mime_type self.set_header('Content-Type', mime_type) self.read_path(abspath)", "if '{{port}}' in line: line = line.replace('{{port}}', str(PORT)) self.write(line) f.close() handlers = [", "os.path.join(root, f) self.write('<li>') if os.path.isdir(path): self.write('<a href=\"%s/\">%s</a>' % (f, f)) else: self.write('<a href=\"%s\">%s</a>'", "handshake['command'] = 'hello' protocols = message.protocols protocols.append( 'http://livereload.com/protocols/2.x-remote-control' ) handshake['protocols'] = protocols handshake['serverName']", "reload action') return logging.info('Reload %s waiters', len(self.waiters)) msg = { 'command': 'reload', 'path':", "Core Server of LiveReload. \"\"\" import os import logging import time import mimetypes", "self._last_reload_time < 3: # if you changed lot of files in one time", "is None: root = '.' ROOT = root logging.getLogger().setLevel(logging.INFO) enable_pretty_logging() app = Application(handlers=handlers)", "message: logging.info('Browser Connected: %s' % message.url) LiveReloadHandler.waiters.add(self) if not LiveReloadHandler._last_reload_time: if os.path.exists('Guardfile'): logging.info('Reading", "href=\"%s\">%s</a>' % (f, f)) self.write('</li>') self.write('</ul>') class LiveReloadJSHandler(RequestHandler): def get(self): f = open(LIVERELOAD)", "webbrowser.open( 'http://127.0.0.1:%s' % port, new=2, autoraise=True ) ioloop.IOLoop.instance().start() if __name__ == '__main__': start(8000)", "os.path.join(abspath, 'index.html') if not os.path.exists(filepath): self.create_index(abspath) return elif not os.path.exists(abspath): filepath = abspath", "self.write('<a href=\"%s\">%s</a>' % (f, f)) self.write('</li>') self.write('</ul>') class LiveReloadJSHandler(RequestHandler): def get(self): f =", "= message.protocols protocols.append( 'http://livereload.com/protocols/2.x-remote-control' ) handshake['protocols'] = protocols handshake['serverName'] = 'livereload-tornado' self.send_message(handshake) if", "of files in one time # it will refresh too many times logging.info('ignore", "with livereload.js 1. client send 'hello' 2. server reply 'hello' 3. client send", "def send_message(self, message): if isinstance(message, dict): message = escape.json_encode(message) try: self.write_message(message) except: logging.error('Error", "\"\"\" import os import logging import time import mimetypes import webbrowser from tornado", "message.url) LiveReloadHandler.waiters.add(self) if not LiveReloadHandler._last_reload_time: if os.path.exists('Guardfile'): logging.info('Reading Guardfile') execfile('Guardfile') else: logging.info('No Guardfile')", "message', exc_info=True) LiveReloadHandler.waiters.remove(waiter) def on_message(self, message): \"\"\"Handshake with livereload.js 1. client send 'hello'", "print('Serving path %s on 127.0.0.1:%s' % (root, port)) if autoraise: webbrowser.open( 'http://127.0.0.1:%s' %", "logging.error('Error sending message', exc_info=True) def watch_tasks(self): changes = Task.watch() if not changes: return", "from tornado import websocket from tornado.web import RequestHandler, Application from tornado.util import ObjectDict", "for line in open(filepath): if '</head>' in line: self.inject_livereload() self.write(line) return self.send_error(404) return", "str(PORT)) self.write(line) f.close() handlers = [ (r'/livereload', LiveReloadHandler), (r'/livereload.js', LiveReloadJSHandler), (r'(.*)', IndexHandler), ]", "os.path.exists(filepath): self.create_index(abspath) return elif not os.path.exists(abspath): filepath = abspath + '.html' if os.path.exists(filepath):", "set() _last_reload_time = None def allow_draft76(self): return True def on_close(self): if self in", "root is None: root = '.' ROOT = root logging.getLogger().setLevel(logging.INFO) enable_pretty_logging() app =", "= None def allow_draft76(self): return True def on_close(self): if self in LiveReloadHandler.waiters: LiveReloadHandler.waiters.remove(self)", "-*- coding: utf-8 -*- \"\"\"livereload.app Core Server of LiveReload. \"\"\" import os import", "import mimetypes import webbrowser from tornado import ioloop from tornado import escape from", "f) self.write('<li>') if os.path.isdir(path): self.write('<a href=\"%s/\">%s</a>' % (f, f)) else: self.write('<a href=\"%s\">%s</a>' %", "many times logging.info('ignore this reload action') return logging.info('Reload %s waiters', len(self.waiters)) msg =", "logging.info('ignore this reload action') return logging.info('Reload %s waiters', len(self.waiters)) msg = { 'command':", "= [ (r'/livereload', LiveReloadHandler), (r'/livereload.js', LiveReloadJSHandler), (r'(.*)', IndexHandler), ] def start(port=35729, root='.', autoraise=False):", "except: logging.error('Error sending message', exc_info=True) LiveReloadHandler.waiters.remove(waiter) def on_message(self, message): \"\"\"Handshake with livereload.js 1.", "'msie' not in ua: self.write('<script src=\"/livereload.js\"></script>') def read_path(self, abspath): filepath = abspath if", "in open(filepath): if '</head>' in line: self.inject_livereload() self.write(line) return self.send_error(404) return def create_index(self,", "handshake['serverName'] = 'livereload-tornado' self.send_message(handshake) if message.command == 'info' and 'url' in message: logging.info('Browser", "logging.info('No Guardfile') Task.add(os.getcwd()) LiveReloadHandler._last_reload_time = time.time() logging.info('Start watching changes') ioloop.PeriodicCallback(self.watch_tasks, 800).start() class IndexHandler(RequestHandler):", "escape from tornado import websocket from tornado.web import RequestHandler, Application from tornado.util import", "create_index(self, root): self.inject_livereload() files = os.listdir(root) self.write('<ul>') for f in files: path =", "def get(self, path='/'): abspath = os.path.join(os.path.abspath(ROOT), path.lstrip('/')) mime_type, encoding = mimetypes.guess_type(abspath) if not", "time.time() logging.info('Start watching changes') ioloop.PeriodicCallback(self.watch_tasks, 800).start() class IndexHandler(RequestHandler): def get(self, path='/'): abspath =", "'path': '*', 'liveCSS': True } self._last_reload_time = time.time() for waiter in LiveReloadHandler.waiters: try:", "os.listdir(root) self.write('<ul>') for f in files: path = os.path.join(root, f) self.write('<li>') if os.path.isdir(path):", "PORT = port global ROOT if root is None: root = '.' ROOT", "abspath.endswith('/'): filepath = os.path.join(abspath, 'index.html') if not os.path.exists(filepath): self.create_index(abspath) return elif not os.path.exists(abspath):", "3. client send 'info' http://help.livereload.com/kb/ecosystem/livereload-protocol \"\"\" message = ObjectDict(escape.json_decode(message)) if message.command == 'hello':", "sending message', exc_info=True) def watch_tasks(self): changes = Task.watch() if not changes: return if", "Connected: %s' % message.url) LiveReloadHandler.waiters.add(self) if not LiveReloadHandler._last_reload_time: if os.path.exists('Guardfile'): logging.info('Reading Guardfile') execfile('Guardfile')", "get(self): f = open(LIVERELOAD) self.set_header('Content-Type', 'application/javascript') for line in f: if '{{port}}' in", "return True def on_close(self): if self in LiveReloadHandler.waiters: LiveReloadHandler.waiters.remove(self) def send_message(self, message): if", "LiveReloadJSHandler), (r'(.*)', IndexHandler), ] def start(port=35729, root='.', autoraise=False): global PORT PORT = port", "read_path(self, abspath): filepath = abspath if abspath.endswith('/'): filepath = os.path.join(abspath, 'index.html') if not", "[ (r'/livereload', LiveReloadHandler), (r'/livereload.js', LiveReloadJSHandler), (r'(.*)', IndexHandler), ] def start(port=35729, root='.', autoraise=False): global", "= mimetypes.guess_type(abspath) if not mime_type: mime_type = 'text/html' self.mime_type = mime_type self.set_header('Content-Type', mime_type)", "mime_type: mime_type = 'text/html' self.mime_type = mime_type self.set_header('Content-Type', mime_type) self.read_path(abspath) def inject_livereload(self): if", "root logging.getLogger().setLevel(logging.INFO) enable_pretty_logging() app = Application(handlers=handlers) app.listen(port) print('Serving path %s on 127.0.0.1:%s' %", "changed lot of files in one time # it will refresh too many", "protocols handshake['serverName'] = 'livereload-tornado' self.send_message(handshake) if message.command == 'info' and 'url' in message:", "encoding = mimetypes.guess_type(abspath) if not mime_type: mime_type = 'text/html' self.mime_type = mime_type self.set_header('Content-Type',", "tornado.util import ObjectDict from tornado.options import enable_pretty_logging from livereload.task import Task PORT =", "in one time # it will refresh too many times logging.info('ignore this reload", "not os.path.exists(filepath): self.create_index(abspath) return elif not os.path.exists(abspath): filepath = abspath + '.html' if", "{} handshake['command'] = 'hello' protocols = message.protocols protocols.append( 'http://livereload.com/protocols/2.x-remote-control' ) handshake['protocols'] = protocols", "LIVERELOAD = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'livereload.js', ) class LiveReloadHandler(websocket.WebSocketHandler): waiters = set() _last_reload_time =", "'livereload.js', ) class LiveReloadHandler(websocket.WebSocketHandler): waiters = set() _last_reload_time = None def allow_draft76(self): return", "message.command == 'info' and 'url' in message: logging.info('Browser Connected: %s' % message.url) LiveReloadHandler.waiters.add(self)", "\"\"\"Handshake with livereload.js 1. client send 'hello' 2. server reply 'hello' 3. client", "= abspath + '.html' if os.path.exists(filepath): for line in open(filepath): if '</head>' in", "in LiveReloadHandler.waiters: try: waiter.write_message(msg) except: logging.error('Error sending message', exc_info=True) LiveReloadHandler.waiters.remove(waiter) def on_message(self, message):", "global PORT PORT = port global ROOT if root is None: root =", "message): if isinstance(message, dict): message = escape.json_encode(message) try: self.write_message(message) except: logging.error('Error sending message',", "changes = Task.watch() if not changes: return if time.time() - self._last_reload_time < 3:", "enable_pretty_logging from livereload.task import Task PORT = 35729 ROOT = '.' LIVERELOAD =", "tornado import ioloop from tornado import escape from tornado import websocket from tornado.web", "LiveReload. \"\"\" import os import logging import time import mimetypes import webbrowser from", "f)) self.write('</li>') self.write('</ul>') class LiveReloadJSHandler(RequestHandler): def get(self): f = open(LIVERELOAD) self.set_header('Content-Type', 'application/javascript') for", "%s waiters', len(self.waiters)) msg = { 'command': 'reload', 'path': '*', 'liveCSS': True }", "class IndexHandler(RequestHandler): def get(self, path='/'): abspath = os.path.join(os.path.abspath(ROOT), path.lstrip('/')) mime_type, encoding = mimetypes.guess_type(abspath)", "you changed lot of files in one time # it will refresh too", "mime_type, encoding = mimetypes.guess_type(abspath) if not mime_type: mime_type = 'text/html' self.mime_type = mime_type", "exc_info=True) LiveReloadHandler.waiters.remove(waiter) def on_message(self, message): \"\"\"Handshake with livereload.js 1. client send 'hello' 2.", "def create_index(self, root): self.inject_livereload() files = os.listdir(root) self.write('<ul>') for f in files: path", "http://help.livereload.com/kb/ecosystem/livereload-protocol \"\"\" message = ObjectDict(escape.json_decode(message)) if message.command == 'hello': handshake = {} handshake['command']", "'.' ROOT = root logging.getLogger().setLevel(logging.INFO) enable_pretty_logging() app = Application(handlers=handlers) app.listen(port) print('Serving path %s", "websocket from tornado.web import RequestHandler, Application from tornado.util import ObjectDict from tornado.options import", "LiveReloadHandler.waiters: LiveReloadHandler.waiters.remove(self) def send_message(self, message): if isinstance(message, dict): message = escape.json_encode(message) try: self.write_message(message)", "message = escape.json_encode(message) try: self.write_message(message) except: logging.error('Error sending message', exc_info=True) def watch_tasks(self): changes", "message = ObjectDict(escape.json_decode(message)) if message.command == 'hello': handshake = {} handshake['command'] = 'hello'", "import os import logging import time import mimetypes import webbrowser from tornado import", "'hello': handshake = {} handshake['command'] = 'hello' protocols = message.protocols protocols.append( 'http://livereload.com/protocols/2.x-remote-control' )", "try: self.write_message(message) except: logging.error('Error sending message', exc_info=True) def watch_tasks(self): changes = Task.watch() if", "return logging.info('Reload %s waiters', len(self.waiters)) msg = { 'command': 'reload', 'path': '*', 'liveCSS':", "return self.send_error(404) return def create_index(self, root): self.inject_livereload() files = os.listdir(root) self.write('<ul>') for f", "f.close() handlers = [ (r'/livereload', LiveReloadHandler), (r'/livereload.js', LiveReloadJSHandler), (r'(.*)', IndexHandler), ] def start(port=35729,", "watching changes') ioloop.PeriodicCallback(self.watch_tasks, 800).start() class IndexHandler(RequestHandler): def get(self, path='/'): abspath = os.path.join(os.path.abspath(ROOT), path.lstrip('/'))", "%s on 127.0.0.1:%s' % (root, port)) if autoraise: webbrowser.open( 'http://127.0.0.1:%s' % port, new=2,", "LiveReloadHandler), (r'/livereload.js', LiveReloadJSHandler), (r'(.*)', IndexHandler), ] def start(port=35729, root='.', autoraise=False): global PORT PORT", "import Task PORT = 35729 ROOT = '.' LIVERELOAD = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'livereload.js',", "logging.info('Start watching changes') ioloop.PeriodicCallback(self.watch_tasks, 800).start() class IndexHandler(RequestHandler): def get(self, path='/'): abspath = os.path.join(os.path.abspath(ROOT),", "self.set_header('Content-Type', mime_type) self.read_path(abspath) def inject_livereload(self): if self.mime_type != 'text/html': return ua = self.request.headers.get('User-Agent',", "% message.url) LiveReloadHandler.waiters.add(self) if not LiveReloadHandler._last_reload_time: if os.path.exists('Guardfile'): logging.info('Reading Guardfile') execfile('Guardfile') else: logging.info('No", "of LiveReload. \"\"\" import os import logging import time import mimetypes import webbrowser", "= port global ROOT if root is None: root = '.' ROOT =", "+ '.html' if os.path.exists(filepath): for line in open(filepath): if '</head>' in line: self.inject_livereload()", "ObjectDict(escape.json_decode(message)) if message.command == 'hello': handshake = {} handshake['command'] = 'hello' protocols =", "open(filepath): if '</head>' in line: self.inject_livereload() self.write(line) return self.send_error(404) return def create_index(self, root):", "logging.info('Reload %s waiters', len(self.waiters)) msg = { 'command': 'reload', 'path': '*', 'liveCSS': True", "== 'info' and 'url' in message: logging.info('Browser Connected: %s' % message.url) LiveReloadHandler.waiters.add(self) if", "os.path.join( os.path.abspath(os.path.dirname(__file__)), 'livereload.js', ) class LiveReloadHandler(websocket.WebSocketHandler): waiters = set() _last_reload_time = None def", "ioloop.PeriodicCallback(self.watch_tasks, 800).start() class IndexHandler(RequestHandler): def get(self, path='/'): abspath = os.path.join(os.path.abspath(ROOT), path.lstrip('/')) mime_type, encoding", "if not mime_type: mime_type = 'text/html' self.mime_type = mime_type self.set_header('Content-Type', mime_type) self.read_path(abspath) def", "if root is None: root = '.' ROOT = root logging.getLogger().setLevel(logging.INFO) enable_pretty_logging() app", "if self in LiveReloadHandler.waiters: LiveReloadHandler.waiters.remove(self) def send_message(self, message): if isinstance(message, dict): message =", "root): self.inject_livereload() files = os.listdir(root) self.write('<ul>') for f in files: path = os.path.join(root,", "filepath = abspath + '.html' if os.path.exists(filepath): for line in open(filepath): if '</head>'", "changes: return if time.time() - self._last_reload_time < 3: # if you changed lot", "sending message', exc_info=True) LiveReloadHandler.waiters.remove(waiter) def on_message(self, message): \"\"\"Handshake with livereload.js 1. client send", "(f, f)) self.write('</li>') self.write('</ul>') class LiveReloadJSHandler(RequestHandler): def get(self): f = open(LIVERELOAD) self.set_header('Content-Type', 'application/javascript')", "if 'msie' not in ua: self.write('<script src=\"/livereload.js\"></script>') def read_path(self, abspath): filepath = abspath", "True def on_close(self): if self in LiveReloadHandler.waiters: LiveReloadHandler.waiters.remove(self) def send_message(self, message): if isinstance(message,", "filepath = os.path.join(abspath, 'index.html') if not os.path.exists(filepath): self.create_index(abspath) return elif not os.path.exists(abspath): filepath", "for line in f: if '{{port}}' in line: line = line.replace('{{port}}', str(PORT)) self.write(line)", "Task PORT = 35729 ROOT = '.' LIVERELOAD = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'livereload.js', )", "one time # it will refresh too many times logging.info('ignore this reload action')", "if not changes: return if time.time() - self._last_reload_time < 3: # if you", "def inject_livereload(self): if self.mime_type != 'text/html': return ua = self.request.headers.get('User-Agent', 'bot').lower() if 'msie'", "f)) else: self.write('<a href=\"%s\">%s</a>' % (f, f)) self.write('</li>') self.write('</ul>') class LiveReloadJSHandler(RequestHandler): def get(self):", "(root, port)) if autoraise: webbrowser.open( 'http://127.0.0.1:%s' % port, new=2, autoraise=True ) ioloop.IOLoop.instance().start() if", "tornado.web import RequestHandler, Application from tornado.util import ObjectDict from tornado.options import enable_pretty_logging from", "handshake = {} handshake['command'] = 'hello' protocols = message.protocols protocols.append( 'http://livereload.com/protocols/2.x-remote-control' ) handshake['protocols']", "line.replace('{{port}}', str(PORT)) self.write(line) f.close() handlers = [ (r'/livereload', LiveReloadHandler), (r'/livereload.js', LiveReloadJSHandler), (r'(.*)', IndexHandler),", "in files: path = os.path.join(root, f) self.write('<li>') if os.path.isdir(path): self.write('<a href=\"%s/\">%s</a>' % (f,", "path.lstrip('/')) mime_type, encoding = mimetypes.guess_type(abspath) if not mime_type: mime_type = 'text/html' self.mime_type =", "if self.mime_type != 'text/html': return ua = self.request.headers.get('User-Agent', 'bot').lower() if 'msie' not in", "= escape.json_encode(message) try: self.write_message(message) except: logging.error('Error sending message', exc_info=True) def watch_tasks(self): changes =", "coding: utf-8 -*- \"\"\"livereload.app Core Server of LiveReload. \"\"\" import os import logging", "= set() _last_reload_time = None def allow_draft76(self): return True def on_close(self): if self", "src=\"/livereload.js\"></script>') def read_path(self, abspath): filepath = abspath if abspath.endswith('/'): filepath = os.path.join(abspath, 'index.html')", "elif not os.path.exists(abspath): filepath = abspath + '.html' if os.path.exists(filepath): for line in", "else: self.write('<a href=\"%s\">%s</a>' % (f, f)) self.write('</li>') self.write('</ul>') class LiveReloadJSHandler(RequestHandler): def get(self): f", "= '.' ROOT = root logging.getLogger().setLevel(logging.INFO) enable_pretty_logging() app = Application(handlers=handlers) app.listen(port) print('Serving path", "for waiter in LiveReloadHandler.waiters: try: waiter.write_message(msg) except: logging.error('Error sending message', exc_info=True) LiveReloadHandler.waiters.remove(waiter) def", "None: root = '.' ROOT = root logging.getLogger().setLevel(logging.INFO) enable_pretty_logging() app = Application(handlers=handlers) app.listen(port)", "= ObjectDict(escape.json_decode(message)) if message.command == 'hello': handshake = {} handshake['command'] = 'hello' protocols", "abspath = os.path.join(os.path.abspath(ROOT), path.lstrip('/')) mime_type, encoding = mimetypes.guess_type(abspath) if not mime_type: mime_type =", "self.send_error(404) return def create_index(self, root): self.inject_livereload() files = os.listdir(root) self.write('<ul>') for f in", "== 'hello': handshake = {} handshake['command'] = 'hello' protocols = message.protocols protocols.append( 'http://livereload.com/protocols/2.x-remote-control'", "(r'/livereload', LiveReloadHandler), (r'/livereload.js', LiveReloadJSHandler), (r'(.*)', IndexHandler), ] def start(port=35729, root='.', autoraise=False): global PORT", "waiter in LiveReloadHandler.waiters: try: waiter.write_message(msg) except: logging.error('Error sending message', exc_info=True) LiveReloadHandler.waiters.remove(waiter) def on_message(self,", "'</head>' in line: self.inject_livereload() self.write(line) return self.send_error(404) return def create_index(self, root): self.inject_livereload() files", "logging import time import mimetypes import webbrowser from tornado import ioloop from tornado", "Task.add(os.getcwd()) LiveReloadHandler._last_reload_time = time.time() logging.info('Start watching changes') ioloop.PeriodicCallback(self.watch_tasks, 800).start() class IndexHandler(RequestHandler): def get(self,", "35729 ROOT = '.' LIVERELOAD = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'livereload.js', ) class LiveReloadHandler(websocket.WebSocketHandler): waiters", "self.write(line) return self.send_error(404) return def create_index(self, root): self.inject_livereload() files = os.listdir(root) self.write('<ul>') for", "% (f, f)) else: self.write('<a href=\"%s\">%s</a>' % (f, f)) self.write('</li>') self.write('</ul>') class LiveReloadJSHandler(RequestHandler):", "self.write('</ul>') class LiveReloadJSHandler(RequestHandler): def get(self): f = open(LIVERELOAD) self.set_header('Content-Type', 'application/javascript') for line in", "in line: self.inject_livereload() self.write(line) return self.send_error(404) return def create_index(self, root): self.inject_livereload() files =", "on_close(self): if self in LiveReloadHandler.waiters: LiveReloadHandler.waiters.remove(self) def send_message(self, message): if isinstance(message, dict): message", "inject_livereload(self): if self.mime_type != 'text/html': return ua = self.request.headers.get('User-Agent', 'bot').lower() if 'msie' not", "'*', 'liveCSS': True } self._last_reload_time = time.time() for waiter in LiveReloadHandler.waiters: try: waiter.write_message(msg)", "on_message(self, message): \"\"\"Handshake with livereload.js 1. client send 'hello' 2. server reply 'hello'", "self.write('<a href=\"%s/\">%s</a>' % (f, f)) else: self.write('<a href=\"%s\">%s</a>' % (f, f)) self.write('</li>') self.write('</ul>')", "(r'(.*)', IndexHandler), ] def start(port=35729, root='.', autoraise=False): global PORT PORT = port global", "self.write_message(message) except: logging.error('Error sending message', exc_info=True) def watch_tasks(self): changes = Task.watch() if not", "autoraise=False): global PORT PORT = port global ROOT if root is None: root", "ioloop from tornado import escape from tornado import websocket from tornado.web import RequestHandler,", "self.inject_livereload() files = os.listdir(root) self.write('<ul>') for f in files: path = os.path.join(root, f)", "= self.request.headers.get('User-Agent', 'bot').lower() if 'msie' not in ua: self.write('<script src=\"/livereload.js\"></script>') def read_path(self, abspath):", "if message.command == 'hello': handshake = {} handshake['command'] = 'hello' protocols = message.protocols", "import RequestHandler, Application from tornado.util import ObjectDict from tornado.options import enable_pretty_logging from livereload.task", "(r'/livereload.js', LiveReloadJSHandler), (r'(.*)', IndexHandler), ] def start(port=35729, root='.', autoraise=False): global PORT PORT =", "reply 'hello' 3. client send 'info' http://help.livereload.com/kb/ecosystem/livereload-protocol \"\"\" message = ObjectDict(escape.json_decode(message)) if message.command", "Guardfile') Task.add(os.getcwd()) LiveReloadHandler._last_reload_time = time.time() logging.info('Start watching changes') ioloop.PeriodicCallback(self.watch_tasks, 800).start() class IndexHandler(RequestHandler): def", "f in files: path = os.path.join(root, f) self.write('<li>') if os.path.isdir(path): self.write('<a href=\"%s/\">%s</a>' %", "lot of files in one time # it will refresh too many times" ]
[ "IntegerField('Spell Crit Rating', [NumberRange(0,500)]) haste_score = IntegerField('Spell Haste Rating', [NumberRange(0,1000)]) num_fights = IntegerField('#", "import StringField, IntegerField from wtforms.fields.simple import SubmitField from wtforms.validators import DataRequired, NumberRange class", "spellpower = IntegerField('Spellpower', [NumberRange(0,1000)]) hit_score = IntegerField('Spell Hit Rating', [NumberRange(0,202)]) crit_score = IntegerField('Spell", "Rating', [NumberRange(0,500)]) haste_score = IntegerField('Spell Haste Rating', [NumberRange(0,1000)]) num_fights = IntegerField('# of fights", "Crit Rating', [NumberRange(0,500)]) haste_score = IntegerField('Spell Haste Rating', [NumberRange(0,1000)]) num_fights = IntegerField('# of", "Hit Rating', [NumberRange(0,202)]) crit_score = IntegerField('Spell Crit Rating', [NumberRange(0,500)]) haste_score = IntegerField('Spell Haste", "flask_wtf import FlaskForm from wtforms import StringField, IntegerField from wtforms.fields.simple import SubmitField from", "wtforms import StringField, IntegerField from wtforms.fields.simple import SubmitField from wtforms.validators import DataRequired, NumberRange", "import SubmitField from wtforms.validators import DataRequired, NumberRange class SimParamsForm(FlaskForm): intellect = IntegerField('Intellect', [NumberRange(0,1000)])", "= IntegerField('Spell Crit Rating', [NumberRange(0,500)]) haste_score = IntegerField('Spell Haste Rating', [NumberRange(0,1000)]) num_fights =", "IntegerField('Spell Hit Rating', [NumberRange(0,202)]) crit_score = IntegerField('Spell Crit Rating', [NumberRange(0,500)]) haste_score = IntegerField('Spell", "Rating', [NumberRange(0,202)]) crit_score = IntegerField('Spell Crit Rating', [NumberRange(0,500)]) haste_score = IntegerField('Spell Haste Rating',", "[NumberRange(0,1000)]) hit_score = IntegerField('Spell Hit Rating', [NumberRange(0,202)]) crit_score = IntegerField('Spell Crit Rating', [NumberRange(0,500)])", "intellect = IntegerField('Intellect', [NumberRange(0,1000)]) spellpower = IntegerField('Spellpower', [NumberRange(0,1000)]) hit_score = IntegerField('Spell Hit Rating',", "from wtforms.fields.simple import SubmitField from wtforms.validators import DataRequired, NumberRange class SimParamsForm(FlaskForm): intellect =", "FlaskForm from wtforms import StringField, IntegerField from wtforms.fields.simple import SubmitField from wtforms.validators import", "from flask_wtf import FlaskForm from wtforms import StringField, IntegerField from wtforms.fields.simple import SubmitField", "wtforms.fields.simple import SubmitField from wtforms.validators import DataRequired, NumberRange class SimParamsForm(FlaskForm): intellect = IntegerField('Intellect',", "= IntegerField('Spell Haste Rating', [NumberRange(0,1000)]) num_fights = IntegerField('# of fights to simulate', [NumberRange(1,2500)])", "= IntegerField('Intellect', [NumberRange(0,1000)]) spellpower = IntegerField('Spellpower', [NumberRange(0,1000)]) hit_score = IntegerField('Spell Hit Rating', [NumberRange(0,202)])", "[NumberRange(0,500)]) haste_score = IntegerField('Spell Haste Rating', [NumberRange(0,1000)]) num_fights = IntegerField('# of fights to", "wtforms.validators import DataRequired, NumberRange class SimParamsForm(FlaskForm): intellect = IntegerField('Intellect', [NumberRange(0,1000)]) spellpower = IntegerField('Spellpower',", "DataRequired, NumberRange class SimParamsForm(FlaskForm): intellect = IntegerField('Intellect', [NumberRange(0,1000)]) spellpower = IntegerField('Spellpower', [NumberRange(0,1000)]) hit_score", "[NumberRange(0,1000)]) spellpower = IntegerField('Spellpower', [NumberRange(0,1000)]) hit_score = IntegerField('Spell Hit Rating', [NumberRange(0,202)]) crit_score =", "from wtforms.validators import DataRequired, NumberRange class SimParamsForm(FlaskForm): intellect = IntegerField('Intellect', [NumberRange(0,1000)]) spellpower =", "= IntegerField('Spellpower', [NumberRange(0,1000)]) hit_score = IntegerField('Spell Hit Rating', [NumberRange(0,202)]) crit_score = IntegerField('Spell Crit", "import DataRequired, NumberRange class SimParamsForm(FlaskForm): intellect = IntegerField('Intellect', [NumberRange(0,1000)]) spellpower = IntegerField('Spellpower', [NumberRange(0,1000)])", "NumberRange class SimParamsForm(FlaskForm): intellect = IntegerField('Intellect', [NumberRange(0,1000)]) spellpower = IntegerField('Spellpower', [NumberRange(0,1000)]) hit_score =", "import FlaskForm from wtforms import StringField, IntegerField from wtforms.fields.simple import SubmitField from wtforms.validators", "IntegerField('Intellect', [NumberRange(0,1000)]) spellpower = IntegerField('Spellpower', [NumberRange(0,1000)]) hit_score = IntegerField('Spell Hit Rating', [NumberRange(0,202)]) crit_score", "haste_score = IntegerField('Spell Haste Rating', [NumberRange(0,1000)]) num_fights = IntegerField('# of fights to simulate',", "IntegerField from wtforms.fields.simple import SubmitField from wtforms.validators import DataRequired, NumberRange class SimParamsForm(FlaskForm): intellect", "SubmitField from wtforms.validators import DataRequired, NumberRange class SimParamsForm(FlaskForm): intellect = IntegerField('Intellect', [NumberRange(0,1000)]) spellpower", "[NumberRange(0,202)]) crit_score = IntegerField('Spell Crit Rating', [NumberRange(0,500)]) haste_score = IntegerField('Spell Haste Rating', [NumberRange(0,1000)])", "from wtforms import StringField, IntegerField from wtforms.fields.simple import SubmitField from wtforms.validators import DataRequired,", "StringField, IntegerField from wtforms.fields.simple import SubmitField from wtforms.validators import DataRequired, NumberRange class SimParamsForm(FlaskForm):", "hit_score = IntegerField('Spell Hit Rating', [NumberRange(0,202)]) crit_score = IntegerField('Spell Crit Rating', [NumberRange(0,500)]) haste_score", "SimParamsForm(FlaskForm): intellect = IntegerField('Intellect', [NumberRange(0,1000)]) spellpower = IntegerField('Spellpower', [NumberRange(0,1000)]) hit_score = IntegerField('Spell Hit", "crit_score = IntegerField('Spell Crit Rating', [NumberRange(0,500)]) haste_score = IntegerField('Spell Haste Rating', [NumberRange(0,1000)]) num_fights", "class SimParamsForm(FlaskForm): intellect = IntegerField('Intellect', [NumberRange(0,1000)]) spellpower = IntegerField('Spellpower', [NumberRange(0,1000)]) hit_score = IntegerField('Spell", "= IntegerField('Spell Hit Rating', [NumberRange(0,202)]) crit_score = IntegerField('Spell Crit Rating', [NumberRange(0,500)]) haste_score =", "IntegerField('Spellpower', [NumberRange(0,1000)]) hit_score = IntegerField('Spell Hit Rating', [NumberRange(0,202)]) crit_score = IntegerField('Spell Crit Rating'," ]
[ "None headers = None def __init__(self, team_id, proxy=None, headers=None, timeout=30, get_request=True): self.proxy =", "'NICKNAME', 'YEARFOUNDED', 'CITY', 'ARENA', 'ARENACAPACITY', 'OWNER', 'GENERALMANAGER', 'HEADCOACH', 'DLEAGUEAFFILIATION'], 'TeamHistory': ['TEAM_ID', 'CITY', 'NICKNAME',", "'OPPOSITETEAM'], 'TeamAwardsConf': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsDiv': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamBackground': ['TEAM_ID', 'ABBREVIATION', 'NICKNAME', 'YEARFOUNDED', 'CITY',", "NBAStatsHTTP class TeamDetails(Endpoint): endpoint = 'teamdetails' expected_data = {'TeamAwardsChampionships': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsConf': ['YEARAWARDED',", "self.parameters = { 'TeamID': team_id } if get_request: self.get_request() def get_request(self): self.nba_response =", "def __init__(self, team_id, proxy=None, headers=None, timeout=30, get_request=True): self.proxy = proxy if headers is", "'HEADCOACH', 'DLEAGUEAFFILIATION'], 'TeamHistory': ['TEAM_ID', 'CITY', 'NICKNAME', 'YEARFOUNDED', 'YEARACTIVETILL'], 'TeamHof': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY',", "from nba_api.stats.library.http import NBAStatsHTTP class TeamDetails(Endpoint): endpoint = 'teamdetails' expected_data = {'TeamAwardsChampionships': ['YEARAWARDED',", "timeout self.parameters = { 'TeamID': team_id } if get_request: self.get_request() def get_request(self): self.nba_response", "'ARENACAPACITY', 'OWNER', 'GENERALMANAGER', 'HEADCOACH', 'DLEAGUEAFFILIATION'], 'TeamHistory': ['TEAM_ID', 'CITY', 'NICKNAME', 'YEARFOUNDED', 'YEARACTIVETILL'], 'TeamHof': ['PLAYERID',", "'TeamHof': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamRetired': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM',", "'CITY', 'ARENA', 'ARENACAPACITY', 'OWNER', 'GENERALMANAGER', 'HEADCOACH', 'DLEAGUEAFFILIATION'], 'TeamHistory': ['TEAM_ID', 'CITY', 'NICKNAME', 'YEARFOUNDED', 'YEARACTIVETILL'],", "None: self.headers = headers self.timeout = timeout self.parameters = { 'TeamID': team_id }", "= Endpoint.DataSet(data=data_sets['TeamAwardsChampionships']) self.team_awards_conf = Endpoint.DataSet(data=data_sets['TeamAwardsConf']) self.team_awards_div = Endpoint.DataSet(data=data_sets['TeamAwardsDiv']) self.team_background = Endpoint.DataSet(data=data_sets['TeamBackground']) self.team_history =", "self.get_request() def get_request(self): self.nba_response = NBAStatsHTTP().send_api_request( endpoint=self.endpoint, parameters=self.parameters, proxy=self.proxy, headers=self.headers, timeout=self.timeout, ) self.load_response()", "= headers self.timeout = timeout self.parameters = { 'TeamID': team_id } if get_request:", "'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamSocialSites': ['ACCOUNTTYPE', 'WEBSITE_LINK']} nba_response = None data_sets = None", "['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamRetired': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'],", "player_stats = None team_stats = None headers = None def __init__(self, team_id, proxy=None,", "None def __init__(self, team_id, proxy=None, headers=None, timeout=30, get_request=True): self.proxy = proxy if headers", "'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamRetired': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamSocialSites':", "'YEARFOUNDED', 'CITY', 'ARENA', 'ARENACAPACITY', 'OWNER', 'GENERALMANAGER', 'HEADCOACH', 'DLEAGUEAFFILIATION'], 'TeamHistory': ['TEAM_ID', 'CITY', 'NICKNAME', 'YEARFOUNDED',", "Endpoint.DataSet(data=data_sets['TeamAwardsConf']) self.team_awards_div = Endpoint.DataSet(data=data_sets['TeamAwardsDiv']) self.team_background = Endpoint.DataSet(data=data_sets['TeamBackground']) self.team_history = Endpoint.DataSet(data=data_sets['TeamHistory']) self.team_hof = Endpoint.DataSet(data=data_sets['TeamHof'])", "'ARENA', 'ARENACAPACITY', 'OWNER', 'GENERALMANAGER', 'HEADCOACH', 'DLEAGUEAFFILIATION'], 'TeamHistory': ['TEAM_ID', 'CITY', 'NICKNAME', 'YEARFOUNDED', 'YEARACTIVETILL'], 'TeamHof':", "['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsDiv': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamBackground': ['TEAM_ID', 'ABBREVIATION', 'NICKNAME', 'YEARFOUNDED', 'CITY', 'ARENA', 'ARENACAPACITY',", "'WEBSITE_LINK']} nba_response = None data_sets = None player_stats = None team_stats = None", "= { 'TeamID': team_id } if get_request: self.get_request() def get_request(self): self.nba_response = NBAStatsHTTP().send_api_request(", "team_id, proxy=None, headers=None, timeout=30, get_request=True): self.proxy = proxy if headers is not None:", "'GENERALMANAGER', 'HEADCOACH', 'DLEAGUEAFFILIATION'], 'TeamHistory': ['TEAM_ID', 'CITY', 'NICKNAME', 'YEARFOUNDED', 'YEARACTIVETILL'], 'TeamHof': ['PLAYERID', 'PLAYER', 'POSITION',", "'SEASONSWITHTEAM', 'YEAR'], 'TeamSocialSites': ['ACCOUNTTYPE', 'WEBSITE_LINK']} nba_response = None data_sets = None player_stats =", "= Endpoint.DataSet(data=data_sets['TeamAwardsConf']) self.team_awards_div = Endpoint.DataSet(data=data_sets['TeamAwardsDiv']) self.team_background = Endpoint.DataSet(data=data_sets['TeamBackground']) self.team_history = Endpoint.DataSet(data=data_sets['TeamHistory']) self.team_hof =", "__init__(self, team_id, proxy=None, headers=None, timeout=30, get_request=True): self.proxy = proxy if headers is not", "'TeamAwardsConf': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsDiv': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamBackground': ['TEAM_ID', 'ABBREVIATION', 'NICKNAME', 'YEARFOUNDED', 'CITY', 'ARENA',", "'SEASONSWITHTEAM', 'YEAR'], 'TeamRetired': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamSocialSites': ['ACCOUNTTYPE', 'WEBSITE_LINK']} nba_response", "is not None: self.headers = headers self.timeout = timeout self.parameters = { 'TeamID':", "def get_request(self): self.nba_response = NBAStatsHTTP().send_api_request( endpoint=self.endpoint, parameters=self.parameters, proxy=self.proxy, headers=self.headers, timeout=self.timeout, ) self.load_response() def", "self.data_sets = [Endpoint.DataSet(data=data_set) for data_set_name, data_set in data_sets.items()] self.team_awards_championships = Endpoint.DataSet(data=data_sets['TeamAwardsChampionships']) self.team_awards_conf =", "import Endpoint from nba_api.stats.library.http import NBAStatsHTTP class TeamDetails(Endpoint): endpoint = 'teamdetails' expected_data =", "self.proxy = proxy if headers is not None: self.headers = headers self.timeout =", "= None headers = None def __init__(self, team_id, proxy=None, headers=None, timeout=30, get_request=True): self.proxy", "self.headers = headers self.timeout = timeout self.parameters = { 'TeamID': team_id } if", "= {'TeamAwardsChampionships': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsConf': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsDiv': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamBackground': ['TEAM_ID', 'ABBREVIATION',", "team_id } if get_request: self.get_request() def get_request(self): self.nba_response = NBAStatsHTTP().send_api_request( endpoint=self.endpoint, parameters=self.parameters, proxy=self.proxy,", "= [Endpoint.DataSet(data=data_set) for data_set_name, data_set in data_sets.items()] self.team_awards_championships = Endpoint.DataSet(data=data_sets['TeamAwardsChampionships']) self.team_awards_conf = Endpoint.DataSet(data=data_sets['TeamAwardsConf'])", "[Endpoint.DataSet(data=data_set) for data_set_name, data_set in data_sets.items()] self.team_awards_championships = Endpoint.DataSet(data=data_sets['TeamAwardsChampionships']) self.team_awards_conf = Endpoint.DataSet(data=data_sets['TeamAwardsConf']) self.team_awards_div", "get_request(self): self.nba_response = NBAStatsHTTP().send_api_request( endpoint=self.endpoint, parameters=self.parameters, proxy=self.proxy, headers=self.headers, timeout=self.timeout, ) self.load_response() def load_response(self):", "in data_sets.items()] self.team_awards_championships = Endpoint.DataSet(data=data_sets['TeamAwardsChampionships']) self.team_awards_conf = Endpoint.DataSet(data=data_sets['TeamAwardsConf']) self.team_awards_div = Endpoint.DataSet(data=data_sets['TeamAwardsDiv']) self.team_background =", "= Endpoint.DataSet(data=data_sets['TeamAwardsDiv']) self.team_background = Endpoint.DataSet(data=data_sets['TeamBackground']) self.team_history = Endpoint.DataSet(data=data_sets['TeamHistory']) self.team_hof = Endpoint.DataSet(data=data_sets['TeamHof']) self.team_retired =", "Endpoint.DataSet(data=data_sets['TeamBackground']) self.team_history = Endpoint.DataSet(data=data_sets['TeamHistory']) self.team_hof = Endpoint.DataSet(data=data_sets['TeamHof']) self.team_retired = Endpoint.DataSet(data=data_sets['TeamRetired']) self.team_social_sites = Endpoint.DataSet(data=data_sets['TeamSocialSites'])", "from nba_api.stats.endpoints._base import Endpoint from nba_api.stats.library.http import NBAStatsHTTP class TeamDetails(Endpoint): endpoint = 'teamdetails'", "['ACCOUNTTYPE', 'WEBSITE_LINK']} nba_response = None data_sets = None player_stats = None team_stats =", "['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamSocialSites': ['ACCOUNTTYPE', 'WEBSITE_LINK']} nba_response = None data_sets", "= timeout self.parameters = { 'TeamID': team_id } if get_request: self.get_request() def get_request(self):", "expected_data = {'TeamAwardsChampionships': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsConf': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsDiv': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamBackground': ['TEAM_ID',", "'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamRetired': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamSocialSites': ['ACCOUNTTYPE',", "'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamRetired': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamSocialSites': ['ACCOUNTTYPE', 'WEBSITE_LINK']}", "data_sets = self.nba_response.get_data_sets() self.data_sets = [Endpoint.DataSet(data=data_set) for data_set_name, data_set in data_sets.items()] self.team_awards_championships =", "self.nba_response.get_data_sets() self.data_sets = [Endpoint.DataSet(data=data_set) for data_set_name, data_set in data_sets.items()] self.team_awards_championships = Endpoint.DataSet(data=data_sets['TeamAwardsChampionships']) self.team_awards_conf", "'YEARACTIVETILL'], 'TeamHof': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamRetired': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY',", "nba_response = None data_sets = None player_stats = None team_stats = None headers", "data_set in data_sets.items()] self.team_awards_championships = Endpoint.DataSet(data=data_sets['TeamAwardsChampionships']) self.team_awards_conf = Endpoint.DataSet(data=data_sets['TeamAwardsConf']) self.team_awards_div = Endpoint.DataSet(data=data_sets['TeamAwardsDiv']) self.team_background", "'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamSocialSites': ['ACCOUNTTYPE', 'WEBSITE_LINK']} nba_response = None data_sets =", "None player_stats = None team_stats = None headers = None def __init__(self, team_id,", "NBAStatsHTTP().send_api_request( endpoint=self.endpoint, parameters=self.parameters, proxy=self.proxy, headers=self.headers, timeout=self.timeout, ) self.load_response() def load_response(self): data_sets = self.nba_response.get_data_sets()", "Endpoint.DataSet(data=data_sets['TeamAwardsDiv']) self.team_background = Endpoint.DataSet(data=data_sets['TeamBackground']) self.team_history = Endpoint.DataSet(data=data_sets['TeamHistory']) self.team_hof = Endpoint.DataSet(data=data_sets['TeamHof']) self.team_retired = Endpoint.DataSet(data=data_sets['TeamRetired'])", "'NICKNAME', 'YEARFOUNDED', 'YEARACTIVETILL'], 'TeamHof': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamRetired': ['PLAYERID', 'PLAYER',", "Endpoint.DataSet(data=data_sets['TeamAwardsChampionships']) self.team_awards_conf = Endpoint.DataSet(data=data_sets['TeamAwardsConf']) self.team_awards_div = Endpoint.DataSet(data=data_sets['TeamAwardsDiv']) self.team_background = Endpoint.DataSet(data=data_sets['TeamBackground']) self.team_history = Endpoint.DataSet(data=data_sets['TeamHistory'])", "get_request=True): self.proxy = proxy if headers is not None: self.headers = headers self.timeout", "'CITY', 'NICKNAME', 'YEARFOUNDED', 'YEARACTIVETILL'], 'TeamHof': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamRetired': ['PLAYERID',", "get_request: self.get_request() def get_request(self): self.nba_response = NBAStatsHTTP().send_api_request( endpoint=self.endpoint, parameters=self.parameters, proxy=self.proxy, headers=self.headers, timeout=self.timeout, )", "data_sets = None player_stats = None team_stats = None headers = None def", "self.team_awards_championships = Endpoint.DataSet(data=data_sets['TeamAwardsChampionships']) self.team_awards_conf = Endpoint.DataSet(data=data_sets['TeamAwardsConf']) self.team_awards_div = Endpoint.DataSet(data=data_sets['TeamAwardsDiv']) self.team_background = Endpoint.DataSet(data=data_sets['TeamBackground']) self.team_history", "def load_response(self): data_sets = self.nba_response.get_data_sets() self.data_sets = [Endpoint.DataSet(data=data_set) for data_set_name, data_set in data_sets.items()]", "endpoint = 'teamdetails' expected_data = {'TeamAwardsChampionships': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsConf': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsDiv': ['YEARAWARDED',", "['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsConf': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsDiv': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamBackground': ['TEAM_ID', 'ABBREVIATION', 'NICKNAME', 'YEARFOUNDED',", "{ 'TeamID': team_id } if get_request: self.get_request() def get_request(self): self.nba_response = NBAStatsHTTP().send_api_request( endpoint=self.endpoint,", "'TeamAwardsDiv': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamBackground': ['TEAM_ID', 'ABBREVIATION', 'NICKNAME', 'YEARFOUNDED', 'CITY', 'ARENA', 'ARENACAPACITY', 'OWNER', 'GENERALMANAGER',", ") self.load_response() def load_response(self): data_sets = self.nba_response.get_data_sets() self.data_sets = [Endpoint.DataSet(data=data_set) for data_set_name, data_set", "= None player_stats = None team_stats = None headers = None def __init__(self,", "'YEARFOUNDED', 'YEARACTIVETILL'], 'TeamHof': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamRetired': ['PLAYERID', 'PLAYER', 'POSITION',", "= self.nba_response.get_data_sets() self.data_sets = [Endpoint.DataSet(data=data_set) for data_set_name, data_set in data_sets.items()] self.team_awards_championships = Endpoint.DataSet(data=data_sets['TeamAwardsChampionships'])", "['TEAM_ID', 'ABBREVIATION', 'NICKNAME', 'YEARFOUNDED', 'CITY', 'ARENA', 'ARENACAPACITY', 'OWNER', 'GENERALMANAGER', 'HEADCOACH', 'DLEAGUEAFFILIATION'], 'TeamHistory': ['TEAM_ID',", "} if get_request: self.get_request() def get_request(self): self.nba_response = NBAStatsHTTP().send_api_request( endpoint=self.endpoint, parameters=self.parameters, proxy=self.proxy, headers=self.headers,", "'OPPOSITETEAM'], 'TeamAwardsDiv': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamBackground': ['TEAM_ID', 'ABBREVIATION', 'NICKNAME', 'YEARFOUNDED', 'CITY', 'ARENA', 'ARENACAPACITY', 'OWNER',", "= proxy if headers is not None: self.headers = headers self.timeout = timeout", "'TeamBackground': ['TEAM_ID', 'ABBREVIATION', 'NICKNAME', 'YEARFOUNDED', 'CITY', 'ARENA', 'ARENACAPACITY', 'OWNER', 'GENERALMANAGER', 'HEADCOACH', 'DLEAGUEAFFILIATION'], 'TeamHistory':", "{'TeamAwardsChampionships': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsConf': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsDiv': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamBackground': ['TEAM_ID', 'ABBREVIATION', 'NICKNAME',", "'TeamSocialSites': ['ACCOUNTTYPE', 'WEBSITE_LINK']} nba_response = None data_sets = None player_stats = None team_stats", "'TeamID': team_id } if get_request: self.get_request() def get_request(self): self.nba_response = NBAStatsHTTP().send_api_request( endpoint=self.endpoint, parameters=self.parameters,", "data_set_name, data_set in data_sets.items()] self.team_awards_championships = Endpoint.DataSet(data=data_sets['TeamAwardsChampionships']) self.team_awards_conf = Endpoint.DataSet(data=data_sets['TeamAwardsConf']) self.team_awards_div = Endpoint.DataSet(data=data_sets['TeamAwardsDiv'])", "'OPPOSITETEAM'], 'TeamBackground': ['TEAM_ID', 'ABBREVIATION', 'NICKNAME', 'YEARFOUNDED', 'CITY', 'ARENA', 'ARENACAPACITY', 'OWNER', 'GENERALMANAGER', 'HEADCOACH', 'DLEAGUEAFFILIATION'],", "Endpoint from nba_api.stats.library.http import NBAStatsHTTP class TeamDetails(Endpoint): endpoint = 'teamdetails' expected_data = {'TeamAwardsChampionships':", "timeout=self.timeout, ) self.load_response() def load_response(self): data_sets = self.nba_response.get_data_sets() self.data_sets = [Endpoint.DataSet(data=data_set) for data_set_name,", "class TeamDetails(Endpoint): endpoint = 'teamdetails' expected_data = {'TeamAwardsChampionships': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsConf': ['YEARAWARDED', 'OPPOSITETEAM'],", "'TeamHistory': ['TEAM_ID', 'CITY', 'NICKNAME', 'YEARFOUNDED', 'YEARACTIVETILL'], 'TeamHof': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'],", "team_stats = None headers = None def __init__(self, team_id, proxy=None, headers=None, timeout=30, get_request=True):", "'DLEAGUEAFFILIATION'], 'TeamHistory': ['TEAM_ID', 'CITY', 'NICKNAME', 'YEARFOUNDED', 'YEARACTIVETILL'], 'TeamHof': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM',", "data_sets.items()] self.team_awards_championships = Endpoint.DataSet(data=data_sets['TeamAwardsChampionships']) self.team_awards_conf = Endpoint.DataSet(data=data_sets['TeamAwardsConf']) self.team_awards_div = Endpoint.DataSet(data=data_sets['TeamAwardsDiv']) self.team_background = Endpoint.DataSet(data=data_sets['TeamBackground'])", "['YEARAWARDED', 'OPPOSITETEAM'], 'TeamBackground': ['TEAM_ID', 'ABBREVIATION', 'NICKNAME', 'YEARFOUNDED', 'CITY', 'ARENA', 'ARENACAPACITY', 'OWNER', 'GENERALMANAGER', 'HEADCOACH',", "headers=self.headers, timeout=self.timeout, ) self.load_response() def load_response(self): data_sets = self.nba_response.get_data_sets() self.data_sets = [Endpoint.DataSet(data=data_set) for", "nba_api.stats.endpoints._base import Endpoint from nba_api.stats.library.http import NBAStatsHTTP class TeamDetails(Endpoint): endpoint = 'teamdetails' expected_data", "= NBAStatsHTTP().send_api_request( endpoint=self.endpoint, parameters=self.parameters, proxy=self.proxy, headers=self.headers, timeout=self.timeout, ) self.load_response() def load_response(self): data_sets =", "nba_api.stats.library.http import NBAStatsHTTP class TeamDetails(Endpoint): endpoint = 'teamdetails' expected_data = {'TeamAwardsChampionships': ['YEARAWARDED', 'OPPOSITETEAM'],", "TeamDetails(Endpoint): endpoint = 'teamdetails' expected_data = {'TeamAwardsChampionships': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsConf': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsDiv':", "= None data_sets = None player_stats = None team_stats = None headers =", "'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamSocialSites': ['ACCOUNTTYPE', 'WEBSITE_LINK']} nba_response = None data_sets = None player_stats", "timeout=30, get_request=True): self.proxy = proxy if headers is not None: self.headers = headers", "'YEAR'], 'TeamRetired': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamSocialSites': ['ACCOUNTTYPE', 'WEBSITE_LINK']} nba_response =", "proxy=self.proxy, headers=self.headers, timeout=self.timeout, ) self.load_response() def load_response(self): data_sets = self.nba_response.get_data_sets() self.data_sets = [Endpoint.DataSet(data=data_set)", "self.nba_response = NBAStatsHTTP().send_api_request( endpoint=self.endpoint, parameters=self.parameters, proxy=self.proxy, headers=self.headers, timeout=self.timeout, ) self.load_response() def load_response(self): data_sets", "proxy=None, headers=None, timeout=30, get_request=True): self.proxy = proxy if headers is not None: self.headers", "headers = None def __init__(self, team_id, proxy=None, headers=None, timeout=30, get_request=True): self.proxy = proxy", "= None def __init__(self, team_id, proxy=None, headers=None, timeout=30, get_request=True): self.proxy = proxy if", "None data_sets = None player_stats = None team_stats = None headers = None", "if headers is not None: self.headers = headers self.timeout = timeout self.parameters =", "self.timeout = timeout self.parameters = { 'TeamID': team_id } if get_request: self.get_request() def", "not None: self.headers = headers self.timeout = timeout self.parameters = { 'TeamID': team_id", "= Endpoint.DataSet(data=data_sets['TeamBackground']) self.team_history = Endpoint.DataSet(data=data_sets['TeamHistory']) self.team_hof = Endpoint.DataSet(data=data_sets['TeamHof']) self.team_retired = Endpoint.DataSet(data=data_sets['TeamRetired']) self.team_social_sites =", "self.load_response() def load_response(self): data_sets = self.nba_response.get_data_sets() self.data_sets = [Endpoint.DataSet(data=data_set) for data_set_name, data_set in", "'OWNER', 'GENERALMANAGER', 'HEADCOACH', 'DLEAGUEAFFILIATION'], 'TeamHistory': ['TEAM_ID', 'CITY', 'NICKNAME', 'YEARFOUNDED', 'YEARACTIVETILL'], 'TeamHof': ['PLAYERID', 'PLAYER',", "'YEAR'], 'TeamSocialSites': ['ACCOUNTTYPE', 'WEBSITE_LINK']} nba_response = None data_sets = None player_stats = None", "proxy if headers is not None: self.headers = headers self.timeout = timeout self.parameters", "'teamdetails' expected_data = {'TeamAwardsChampionships': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsConf': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsDiv': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamBackground':", "headers=None, timeout=30, get_request=True): self.proxy = proxy if headers is not None: self.headers =", "None team_stats = None headers = None def __init__(self, team_id, proxy=None, headers=None, timeout=30,", "import NBAStatsHTTP class TeamDetails(Endpoint): endpoint = 'teamdetails' expected_data = {'TeamAwardsChampionships': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsConf':", "= 'teamdetails' expected_data = {'TeamAwardsChampionships': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsConf': ['YEARAWARDED', 'OPPOSITETEAM'], 'TeamAwardsDiv': ['YEARAWARDED', 'OPPOSITETEAM'],", "headers self.timeout = timeout self.parameters = { 'TeamID': team_id } if get_request: self.get_request()", "self.team_awards_div = Endpoint.DataSet(data=data_sets['TeamAwardsDiv']) self.team_background = Endpoint.DataSet(data=data_sets['TeamBackground']) self.team_history = Endpoint.DataSet(data=data_sets['TeamHistory']) self.team_hof = Endpoint.DataSet(data=data_sets['TeamHof']) self.team_retired", "headers is not None: self.headers = headers self.timeout = timeout self.parameters = {", "endpoint=self.endpoint, parameters=self.parameters, proxy=self.proxy, headers=self.headers, timeout=self.timeout, ) self.load_response() def load_response(self): data_sets = self.nba_response.get_data_sets() self.data_sets", "load_response(self): data_sets = self.nba_response.get_data_sets() self.data_sets = [Endpoint.DataSet(data=data_set) for data_set_name, data_set in data_sets.items()] self.team_awards_championships", "= None team_stats = None headers = None def __init__(self, team_id, proxy=None, headers=None,", "for data_set_name, data_set in data_sets.items()] self.team_awards_championships = Endpoint.DataSet(data=data_sets['TeamAwardsChampionships']) self.team_awards_conf = Endpoint.DataSet(data=data_sets['TeamAwardsConf']) self.team_awards_div =", "'ABBREVIATION', 'NICKNAME', 'YEARFOUNDED', 'CITY', 'ARENA', 'ARENACAPACITY', 'OWNER', 'GENERALMANAGER', 'HEADCOACH', 'DLEAGUEAFFILIATION'], 'TeamHistory': ['TEAM_ID', 'CITY',", "parameters=self.parameters, proxy=self.proxy, headers=self.headers, timeout=self.timeout, ) self.load_response() def load_response(self): data_sets = self.nba_response.get_data_sets() self.data_sets =", "self.team_awards_conf = Endpoint.DataSet(data=data_sets['TeamAwardsConf']) self.team_awards_div = Endpoint.DataSet(data=data_sets['TeamAwardsDiv']) self.team_background = Endpoint.DataSet(data=data_sets['TeamBackground']) self.team_history = Endpoint.DataSet(data=data_sets['TeamHistory']) self.team_hof", "'TeamRetired': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamSocialSites': ['ACCOUNTTYPE', 'WEBSITE_LINK']} nba_response = None", "self.team_background = Endpoint.DataSet(data=data_sets['TeamBackground']) self.team_history = Endpoint.DataSet(data=data_sets['TeamHistory']) self.team_hof = Endpoint.DataSet(data=data_sets['TeamHof']) self.team_retired = Endpoint.DataSet(data=data_sets['TeamRetired']) self.team_social_sites", "if get_request: self.get_request() def get_request(self): self.nba_response = NBAStatsHTTP().send_api_request( endpoint=self.endpoint, parameters=self.parameters, proxy=self.proxy, headers=self.headers, timeout=self.timeout,", "['TEAM_ID', 'CITY', 'NICKNAME', 'YEARFOUNDED', 'YEARACTIVETILL'], 'TeamHof': ['PLAYERID', 'PLAYER', 'POSITION', 'JERSEY', 'SEASONSWITHTEAM', 'YEAR'], 'TeamRetired':" ]
[ "[ migrations.AlterModelOptions( name='tableassignment', options={'permissions': (('view_table_assignments', 'Can view table assignments'), ('edit_table_assignments', 'Can edit table", "('seating_charts', '0005_auto_20160203_1110'), ] operations = [ migrations.AlterModelOptions( name='tableassignment', options={'permissions': (('view_table_assignments', 'Can view table", "migrations, models class Migration(migrations.Migration): dependencies = [ ('seating_charts', '0005_auto_20160203_1110'), ] operations = [", "= [ ('seating_charts', '0005_auto_20160203_1110'), ] operations = [ migrations.AlterModelOptions( name='tableassignment', options={'permissions': (('view_table_assignments', 'Can", "-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models", "dependencies = [ ('seating_charts', '0005_auto_20160203_1110'), ] operations = [ migrations.AlterModelOptions( name='tableassignment', options={'permissions': (('view_table_assignments',", "Migration(migrations.Migration): dependencies = [ ('seating_charts', '0005_auto_20160203_1110'), ] operations = [ migrations.AlterModelOptions( name='tableassignment', options={'permissions':", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('seating_charts', '0005_auto_20160203_1110'), ] operations", "migrations.AlterModelOptions( name='tableassignment', options={'permissions': (('view_table_assignments', 'Can view table assignments'), ('edit_table_assignments', 'Can edit table assignments'))},", "-*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies", "name='tableassignment', options={'permissions': (('view_table_assignments', 'Can view table assignments'), ('edit_table_assignments', 'Can edit table assignments'))}, ),", "models class Migration(migrations.Migration): dependencies = [ ('seating_charts', '0005_auto_20160203_1110'), ] operations = [ migrations.AlterModelOptions(", "unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('seating_charts', '0005_auto_20160203_1110'),", "<reponame>rectory-school/rectory-apps # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import", "options={'permissions': (('view_table_assignments', 'Can view table assignments'), ('edit_table_assignments', 'Can edit table assignments'))}, ), ]", "] operations = [ migrations.AlterModelOptions( name='tableassignment', options={'permissions': (('view_table_assignments', 'Can view table assignments'), ('edit_table_assignments',", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('seating_charts', '0005_auto_20160203_1110'), ]", "utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('seating_charts', '0005_auto_20160203_1110'), ] operations =", "# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations,", "from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "[ ('seating_charts', '0005_auto_20160203_1110'), ] operations = [ migrations.AlterModelOptions( name='tableassignment', options={'permissions': (('view_table_assignments', 'Can view", "operations = [ migrations.AlterModelOptions( name='tableassignment', options={'permissions': (('view_table_assignments', 'Can view table assignments'), ('edit_table_assignments', 'Can", "= [ migrations.AlterModelOptions( name='tableassignment', options={'permissions': (('view_table_assignments', 'Can view table assignments'), ('edit_table_assignments', 'Can edit", "import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('seating_charts',", "class Migration(migrations.Migration): dependencies = [ ('seating_charts', '0005_auto_20160203_1110'), ] operations = [ migrations.AlterModelOptions( name='tableassignment',", "coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class", "'0005_auto_20160203_1110'), ] operations = [ migrations.AlterModelOptions( name='tableassignment', options={'permissions': (('view_table_assignments', 'Can view table assignments')," ]
[ "n.left: queue.append(n.left) if n.right: queue.append(n.right) for level in res: print(*[n.value for n in", "in res: print(*[n.value for n in level]) return res class Test(unittest.TestCase): tree_1 =", "= node(3) tree_1.left.left = node(4) tree_1.left.right = node(5) tree_1.right.left = node(6) tree_1.right.right =", "tree_1.left.left = node(4) tree_1.left.right = node(5) tree_1.right.left = node(6) tree_1.right.right = node(7) def", "level]) return res class Test(unittest.TestCase): tree_1 = node(1) tree_1.left = node(2) tree_1.right =", "self.left = None self.right = None def solution(root): res = [] queue =", "[queue.pop() for _ in range(numberOfNodesInThisLevel)] res.append(level) for n in level: if n.left: queue.append(n.left)", "node(4) tree_1.left.right = node(5) tree_1.right.left = node(6) tree_1.right.right = node(7) def testTree1(self): solution(self.tree_1)", "= None self.right = None def solution(root): res = [] queue = []", "for n in level]) return res class Test(unittest.TestCase): tree_1 = node(1) tree_1.left =", "res.append(level) for n in level: if n.left: queue.append(n.left) if n.right: queue.append(n.right) for level", "in range(numberOfNodesInThisLevel)] res.append(level) for n in level: if n.left: queue.append(n.left) if n.right: queue.append(n.right)", "n.right: queue.append(n.right) for level in res: print(*[n.value for n in level]) return res", "level: if n.left: queue.append(n.left) if n.right: queue.append(n.right) for level in res: print(*[n.value for", "solution(root): res = [] queue = [] queue.append(root) while queue: numberOfNodesInThisLevel = len(queue)", "res = [] queue = [] queue.append(root) while queue: numberOfNodesInThisLevel = len(queue) level", "[] queue.append(root) while queue: numberOfNodesInThisLevel = len(queue) level = [queue.pop() for _ in", "tree_1.right = node(3) tree_1.left.left = node(4) tree_1.left.right = node(5) tree_1.right.left = node(6) tree_1.right.right", "class node(): def __init__(self, value=None): self.value = value self.left = None self.right =", "node(2) tree_1.right = node(3) tree_1.left.left = node(4) tree_1.left.right = node(5) tree_1.right.left = node(6)", "class Test(unittest.TestCase): tree_1 = node(1) tree_1.left = node(2) tree_1.right = node(3) tree_1.left.left =", "tree_1.left = node(2) tree_1.right = node(3) tree_1.left.left = node(4) tree_1.left.right = node(5) tree_1.right.left", "for n in level: if n.left: queue.append(n.left) if n.right: queue.append(n.right) for level in", "= node(5) tree_1.right.left = node(6) tree_1.right.right = node(7) def testTree1(self): solution(self.tree_1) if __name__", "for level in res: print(*[n.value for n in level]) return res class Test(unittest.TestCase):", "level = [queue.pop() for _ in range(numberOfNodesInThisLevel)] res.append(level) for n in level: if", "Test(unittest.TestCase): tree_1 = node(1) tree_1.left = node(2) tree_1.right = node(3) tree_1.left.left = node(4)", "[] queue = [] queue.append(root) while queue: numberOfNodesInThisLevel = len(queue) level = [queue.pop()", "= len(queue) level = [queue.pop() for _ in range(numberOfNodesInThisLevel)] res.append(level) for n in", "len(queue) level = [queue.pop() for _ in range(numberOfNodesInThisLevel)] res.append(level) for n in level:", "level in res: print(*[n.value for n in level]) return res class Test(unittest.TestCase): tree_1", "in level: if n.left: queue.append(n.left) if n.right: queue.append(n.right) for level in res: print(*[n.value", "None self.right = None def solution(root): res = [] queue = [] queue.append(root)", "= node(4) tree_1.left.right = node(5) tree_1.right.left = node(6) tree_1.right.right = node(7) def testTree1(self):", "queue = [] queue.append(root) while queue: numberOfNodesInThisLevel = len(queue) level = [queue.pop() for", "n in level: if n.left: queue.append(n.left) if n.right: queue.append(n.right) for level in res:", "value self.left = None self.right = None def solution(root): res = [] queue", "node(5) tree_1.right.left = node(6) tree_1.right.right = node(7) def testTree1(self): solution(self.tree_1) if __name__ ==", "= [] queue.append(root) while queue: numberOfNodesInThisLevel = len(queue) level = [queue.pop() for _", "queue: numberOfNodesInThisLevel = len(queue) level = [queue.pop() for _ in range(numberOfNodesInThisLevel)] res.append(level) for", "= [] queue = [] queue.append(root) while queue: numberOfNodesInThisLevel = len(queue) level =", "tree_1 = node(1) tree_1.left = node(2) tree_1.right = node(3) tree_1.left.left = node(4) tree_1.left.right", "node(): def __init__(self, value=None): self.value = value self.left = None self.right = None", "queue.append(root) while queue: numberOfNodesInThisLevel = len(queue) level = [queue.pop() for _ in range(numberOfNodesInThisLevel)]", "= [queue.pop() for _ in range(numberOfNodesInThisLevel)] res.append(level) for n in level: if n.left:", "tree_1.left.right = node(5) tree_1.right.left = node(6) tree_1.right.right = node(7) def testTree1(self): solution(self.tree_1) if", "print(*[n.value for n in level]) return res class Test(unittest.TestCase): tree_1 = node(1) tree_1.left", "return res class Test(unittest.TestCase): tree_1 = node(1) tree_1.left = node(2) tree_1.right = node(3)", "import unittest class node(): def __init__(self, value=None): self.value = value self.left = None", "self.value = value self.left = None self.right = None def solution(root): res =", "self.right = None def solution(root): res = [] queue = [] queue.append(root) while", "in level]) return res class Test(unittest.TestCase): tree_1 = node(1) tree_1.left = node(2) tree_1.right", "res: print(*[n.value for n in level]) return res class Test(unittest.TestCase): tree_1 = node(1)", "= value self.left = None self.right = None def solution(root): res = []", "numberOfNodesInThisLevel = len(queue) level = [queue.pop() for _ in range(numberOfNodesInThisLevel)] res.append(level) for n", "range(numberOfNodesInThisLevel)] res.append(level) for n in level: if n.left: queue.append(n.left) if n.right: queue.append(n.right) for", "node(3) tree_1.left.left = node(4) tree_1.left.right = node(5) tree_1.right.left = node(6) tree_1.right.right = node(7)", "unittest class node(): def __init__(self, value=None): self.value = value self.left = None self.right", "def __init__(self, value=None): self.value = value self.left = None self.right = None def", "= node(2) tree_1.right = node(3) tree_1.left.left = node(4) tree_1.left.right = node(5) tree_1.right.left =", "while queue: numberOfNodesInThisLevel = len(queue) level = [queue.pop() for _ in range(numberOfNodesInThisLevel)] res.append(level)", "if n.left: queue.append(n.left) if n.right: queue.append(n.right) for level in res: print(*[n.value for n", "node(1) tree_1.left = node(2) tree_1.right = node(3) tree_1.left.left = node(4) tree_1.left.right = node(5)", "for _ in range(numberOfNodesInThisLevel)] res.append(level) for n in level: if n.left: queue.append(n.left) if", "value=None): self.value = value self.left = None self.right = None def solution(root): res", "queue.append(n.right) for level in res: print(*[n.value for n in level]) return res class", "= None def solution(root): res = [] queue = [] queue.append(root) while queue:", "= node(6) tree_1.right.right = node(7) def testTree1(self): solution(self.tree_1) if __name__ == \"__main__\": unittest.main()", "queue.append(n.left) if n.right: queue.append(n.right) for level in res: print(*[n.value for n in level])", "n in level]) return res class Test(unittest.TestCase): tree_1 = node(1) tree_1.left = node(2)", "if n.right: queue.append(n.right) for level in res: print(*[n.value for n in level]) return", "def solution(root): res = [] queue = [] queue.append(root) while queue: numberOfNodesInThisLevel =", "_ in range(numberOfNodesInThisLevel)] res.append(level) for n in level: if n.left: queue.append(n.left) if n.right:", "None def solution(root): res = [] queue = [] queue.append(root) while queue: numberOfNodesInThisLevel", "= node(1) tree_1.left = node(2) tree_1.right = node(3) tree_1.left.left = node(4) tree_1.left.right =", "res class Test(unittest.TestCase): tree_1 = node(1) tree_1.left = node(2) tree_1.right = node(3) tree_1.left.left", "__init__(self, value=None): self.value = value self.left = None self.right = None def solution(root):", "tree_1.right.left = node(6) tree_1.right.right = node(7) def testTree1(self): solution(self.tree_1) if __name__ == \"__main__\":" ]
[ "rolls. dice_pool: int threshold: int prime: bool exploding: bool -> {success, rolls, totals", ": int -> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool) if 6 in rolls:", "with a boolean representing success status and a list of int lists representing", "\"totals\": { \"total_hits\": total_hits, \"running_total\": totals}} async def is_glitch(self, rolls, hits): \"\"\" Checks", "int, threshold: int, prime: boolean) -> {success: bool, rolls: list[int], totals {total_hits: int,", "This allows for exploding 6's with exploding=True dice_pool: int exploding: Boolean -> list[int]", "by the License. \"\"\" from utils.rolling import rolling_utils class Shadowrun3Roller(): \"\"\" The shadowrun", "modifier=1): \"\"\" Rolls initiative dice and adds reaction in. dice_pool: int reaction: int", "{\"hits\": hits, \"misses\": misses, \"ones\": ones} async def extended_test(self, dice_pool, threshold, prime=False, exploding=False):", "list[int] -> bool \"\"\" ones = [x for x in rolls if x", "False return successes async def is_failure(self, rolls): \"\"\" Checks to see if the", "\"\"\" initiative_roll = await self.roll(dice_pool) for i in initiative_roll: modifier += i return", "return {\"hits\": hits, \"misses\": misses, \"ones\": ones} async def extended_test(self, dice_pool, threshold, prime=False,", "async def roll(self, dice_pool): \"\"\" Rolls and counts the dice according to shadowrun", "{total_hits: int, running_total: list[int]}} Runs extended tests by shadowrun 5E rules. Stops as", "pass async def buy_hits(self, dice_pool=0): \"\"\" \"buys\" hits at a 1 hit :", "int, rolls: list[int]) -> dict(successes: int, rolls: list[int], failure: bool) Checks how many", "Runs an extended test with a dice pool to see if it is", "int modifier: int -> initiative: int \"\"\" initiative_roll = await self.roll(dice_pool) for i", "+= 1 elif i > 1: misses += 1 else: ones += 1", "is only the case if all items in the roll are a 1.", "extended_test(dice_pool: int, threshold: int, prime: boolean) -> {success: bool, rolls: list[int], totals {total_hits:", "handles basic dice rolling. This allows for exploding 6's with exploding=True dice_pool: int", "1's by shadowrun 1E rules. Returns True if the roll is a failure.", "is_failure(self, rolls): \"\"\" Checks to see if the roll is a failure. This", "misses, ones} \"\"\" hit_limit = 5 # Lower the hit threshold if rolling", "lists representing the rolls. dice_pool: int threshold: int prime: bool exploding: bool ->", "all shadowrun 5E related rolling functions. Types of rolls that are completed inlcude", "\"\"\" rolls = [] totals = [] success = False total_hits = 0", "> 0: roll = await self.roll(dice_pool, exploding=exploding) if prime: counted = await self.count_hits(roll,", "async def roll_initiative(self, dice_pool=1, modifier=1): \"\"\" Rolls initiative dice and adds reaction in.", "rolls: list[int] -> {hits, misses, ones} \"\"\" hit_limit = 5 # Lower the", "bool exploding: bool -> {success, rolls, totals {total_hits, running_total}} \"\"\" rolls = []", "for shadowrun 1E games. class methods: check_successes(target: int, rolls: list[int]) -> dict(successes: int,", "a list of integers. rolls: list[int] -> {hits, misses, ones} \"\"\" hit_limit =", "been completed rather than running through all iterations if not needed. SR5E CORE", "x in rolls if x == 1] if len(ones) == len(rolls): return True", "roll(self, dice_pool): \"\"\" Rolls and counts the dice according to shadowrun 1E rules.", "general rolling and hit counting - Adding in additional dice with + -", "any of the rolls are successes target : int roll : list[int] ->", "Checks to see if the roll is a failure. This is only the", "await rolling_utils.roll(dice_pool) for i in initiative_roll: modifier += i return initiative_roll, modifier class", "roll is designated for a prime runner, it lowers the hit threshold by", "The shadowrun roller is my handler for all shadowrun 5E related rolling functions.", "[sixes[i] + added[i] for i in range(0, len(sixes))] rolls.extend(sixes) return rolls async def", "of hits, misses, and ones in a list of integers. rolls: list[int] ->", "a dict with a boolean representing success status and a list of int", "{\"glitch\": glitch, \"type\": glitch_type} async def roll(self, dice_pool, exploding=False): \"\"\" A dice roller", "return {\"glitch\": glitch, \"type\": glitch_type} async def roll(self, dice_pool, exploding=False): \"\"\" A dice", "def is_failure(self, rolls): \"\"\" Checks to see if the roll is a failure.", "else: ones += 1 return {\"hits\": hits, \"misses\": misses, \"ones\": ones} async def", "False glitch_type = None ones = [x for x in rolls if x", "self.count_hits(roll, prime=True) else: counted = await self.count_hits(roll) total_hits += counted[\"hits\"] totals.append(total_hits) rolls.append({\"hits\": counted[\"hits\"],", "self.roll(len(sixes))) rolls.sort() return rolls rolls.sort() return rolls async def roll_initiative(self, dice_pool, modifier=0): \"\"\"", "[] totals = [] success = False total_hits = 0 while dice_pool >", "[x for x in rolls if x == 6] rolls.extend(await self.roll(len(sixes))) rolls.sort() return", "whether or not the roll is a failure is_failure(rolls: list[int]) -> bool Checks", "counting. The shadowrun roller is my handler for all shadowrun 5E related rolling", "counted = await self.count_hits(roll, prime=True) else: counted = await self.count_hits(roll) total_hits += counted[\"hits\"]", "rolls that are completed inlcude general rolling and hit counting - Adding in", "{success, rolls, totals {total_hits, running_total}} \"\"\" rolls = [] totals = [] success", "If the roll is designated for a prime runner, it lowers the hit", "completed rather than running through all iterations if not needed. SR5E CORE pg.", "Rounds down. SR5E CORE pg. 45 count_hits(rolls: list[int], prime: Boolean) -> {hits, misses,", "failure is_failure(rolls: list[int]) -> bool Checks to see if the roll is a", "representing the rolls. dice_pool: int threshold: int prime: bool exploding: bool -> {success,", "Counts the amount of hits, misses, and ones in a list of integers.", "rolls.sort() return rolls async def roll_initiative(self, dice_pool, modifier=0): \"\"\" Rolls initiative for shadowrun", "hits += 1 elif i > 1: misses += 1 else: ones +=", "exceeded the target and whether or not the roll is a failure is_failure(rolls:", "\"\"\" Checks the rolls to see if any of the rolls are successes", "shadowrun 1E rules. Returns True if the roll is a failure. roll(dice_pool: int)", "int Rolls initiative dice and adds in reaction to give the initiative score.", "with + - removing dice with - class variables: roller (base_roll_functions.roller()): A roller", "0 for i in rolls: if i >= hit_limit: hits += 1 elif", "or not the roll is a failure is_failure(rolls: list[int]) -> bool Checks to", "initiative for shadowrun 5E. SR5E CORE pg. 159 \"\"\" def __init__(self): pass async", "of the rolls are successes target : int roll : list[int] -> dict{successes:", "will lower the threshold when counting hits if it is True. Returns a", "amount of successes and the integers that exceeded the target and whether or", "in a list of integers. rolls: list[int] -> {hits, misses, ones} \"\"\" hit_limit", "dice_pool: int reaction: int -> int \"\"\" # Adding 6's does not apply", "boolean representing success status and a list of int lists representing the rolls.", "located at https://github.com/ephreal/rollbot/Licence Please see the license for any restrictions or rights granted", "in initiative_roll: modifier += i return initiative_roll, modifier class Shadowrun5Roller(): \"\"\" TODO: Add", "https://github.com/ephreal/rollbot/Licence Please see the license for any restrictions or rights granted to you", "[x for x in rolls if x == 6] rolls = [x for", "representing success status and a list of int lists representing the rolls. dice_pool:", "1 if total_hits >= threshold: success = True break return {\"success\": success, \"rolls\":", ">= threshold: success = True break return {\"success\": success, \"rolls\": rolls, \"totals\": {", "SR5E CORE pg. 44 SR5E CORE pg. 56 (Edge effects) roll_initiative(dice_pool: int, modifier:", "4 dice ratio. Rounds down. SR5E CORE pg. 45 count_hits(rolls: list[int], prime: Boolean)", "SR5E CORE pg. 48 is_glitch(rolls: list[int], hits: int) -> {glitch: bool, type: str", "1: misses += 1 else: ones += 1 return {\"hits\": hits, \"misses\": misses,", "int reaction: int -> int \"\"\" # Adding 6's does not apply to", "1 elif i > 1: misses += 1 else: ones += 1 return", "self.count_hits(roll) total_hits += counted[\"hits\"] totals.append(total_hits) rolls.append({\"hits\": counted[\"hits\"], \"roll\": roll}) dice_pool -= 1 if", "None ones = [x for x in rolls if x == 1] if", "is possible to reach a threshold. Prime will lower the threshold when counting", "6's does not apply to initiative. Therefore use the general # roller. initiative_roll", "pg. 56 (Edge effects) roll_initiative(dice_pool: int, modifier: int) -> initiative: int Rolls initiative", "= False return successes async def is_failure(self, rolls): \"\"\" Checks to see if", "sides=6) if exploding: sixes = [x for x in rolls if x ==", "all iterations if not needed. SR5E CORE pg. 48 is_glitch(rolls: list[int], hits: int)", "Please see the license for any restrictions or rights granted to you by", "which is all 1's by shadowrun 1E rules. Returns True if the roll", "representing the totals. roll_initiative(dice_pool: int, modifier: int) -> initiative: int Rolls initiative dice", "\"normal\" return {\"glitch\": glitch, \"type\": glitch_type} async def roll(self, dice_pool, exploding=False): \"\"\" A", "rules. Does no checks for failures or successes. Returns a list of integers", "successes target : int roll : list[int] -> dict{successes: int, rolls[int], failure: Bool}", "runner if prime: hit_limit = 4 hits, misses, ones = 0, 0, 0", "dict{successes: int, rolls[int], failure: Bool} \"\"\" rolls = [roll for roll in rolls", "target, rolls): \"\"\" Checks the rolls to see if any of the rolls", "async def roll(self, dice_pool, exploding=False): \"\"\" A dice roller that handles basic dice", "rolls.append({\"hits\": counted[\"hits\"], \"roll\": roll}) dice_pool -= 1 if total_hits >= threshold: success =", "coding: utf-8 -*- \"\"\" This software is licensed under the License (MIT) located", "dict(successes: int, rolls: list[int], failure: bool) Checks how many integers in the rolls", "boolean) -> {success: bool, rolls: list[int], totals {total_hits: int, running_total: list[int]}} Runs extended", "return {\"success\": success, \"rolls\": rolls, \"totals\": { \"total_hits\": total_hits, \"running_total\": totals}} async def", "shadowrun 5E related rolling functions. Types of rolls that are completed inlcude general", "buy_hits(dice_pool: int) -> hits: int \"buys\" hits at a 1 hit : 4", "the License (MIT) located at https://github.com/ephreal/rollbot/Licence Please see the license for any restrictions", "roll are a 1. rolls : list[int] -> bool \"\"\" ones = [x", "CORE pg. 44 extended_test(dice_pool: int, threshold: int, prime: boolean) -> {success: bool, rolls:", "[x for x in rolls if x == 1] if len(ones) > (len(rolls)", "int exploding: Boolean -> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool=dice_pool, sides=6) if exploding:", "pg. 48 is_glitch(rolls: list[int], hits: int) -> {glitch: bool, type: str or None}", "a roll is a glitch. rolls: list[int] hits: int -> dict{glitch: bool, type:", "for shadowrun 5E. dice_pool: int modifier: int -> initiative: int \"\"\" initiative_roll =", "Checks how many integers in the rolls list exceed the target int. Returns", "prime=True) else: counted = await self.count_hits(roll) total_hits += counted[\"hits\"] totals.append(total_hits) rolls.append({\"hits\": counted[\"hits\"], \"roll\":", "counted = await self.count_hits(roll) total_hits += counted[\"hits\"] totals.append(total_hits) rolls.append({\"hits\": counted[\"hits\"], \"roll\": roll}) dice_pool", "elif i > 1: misses += 1 else: ones += 1 return {\"hits\":", "rolls = [roll for roll in rolls if roll >= target] successes =", "6's with exploding=True SR5E CORE pg. 44 SR5E CORE pg. 56 (Edge effects)", "of successes and the integers that exceeded the target and whether or not", "Add in glitch counting. The shadowrun roller is my handler for all shadowrun", "0 while dice_pool > 0: roll = await self.roll(dice_pool, exploding=exploding) if prime: counted", "hits: glitch = True glitch_type = \"critical\" elif len(ones) > (len(rolls) // 2)", "dice_pool, modifier=0): \"\"\" Rolls initiative for shadowrun 5E. dice_pool: int modifier: int ->", "pg. 44 extended_test(dice_pool: int, threshold: int, prime: boolean) -> {success: bool, rolls: list[int],", "needed. SR5E CORE pg. 48 is_glitch(rolls: list[int], hits: int) -> {glitch: bool, type:", "int, modifier: int) -> initiative: int Rolls initiative for shadowrun 5E. SR5E CORE", "exploding: sixes = [x for x in rolls if x == 6] rolls.extend(await", "only the case if all items in the roll are a 1. rolls", "additional dice with + - removing dice with - class variables: roller (base_roll_functions.roller()):", "pg. 45-46 roll(dice_pool: int, exploding: Boolean) -> list[int]: A dice roller that handles", "modifier class Shadowrun5Roller(): \"\"\" TODO: Add in glitch counting. The shadowrun roller is", "CORE pg. 44 SR5E CORE pg. 56 (Edge effects) roll_initiative(dice_pool: int, modifier: int)", "down. SR5E CORE pg. 45 count_hits(rolls: list[int], prime: Boolean) -> {hits, misses, ones}", "it lowers the hit threshold by 1. SR5E CORE pg. 44 extended_test(dice_pool: int,", "{glitch: bool, type: str or None} Checks whether or not a roll is", "of integers. rolls: list[int] -> {hits, misses, ones} \"\"\" hit_limit = 5 #", "return dice_pool // 4 async def count_hits(self, rolls, prime=False): \"\"\" Counts the amount", "dice_pool: int exploding: Boolean -> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool=dice_pool, sides=6) if", "- class variables: roller (base_roll_functions.roller()): A roller class that handles the actual dice", "modifier: int -> initiative: int \"\"\" initiative_roll = await self.roll(dice_pool) for i in", "x == 1] if len(ones) == len(rolls): return True return False async def", "the dice according to shadowrun 1E rules. Does no checks for failures or", "and the integers that exceeded the target and whether or not the roll", "rolls if x == 6] rolls = [x for x in rolls if", "allows for exploding 6's with exploding=True SR5E CORE pg. 44 SR5E CORE pg.", "dice_pool: int threshold: int prime: bool exploding: bool -> {success, rolls, totals {total_hits,", "roll_initiative(dice_pool: int, modifier: int) -> initiative: int Rolls initiative dice and adds in", "= await rolling_utils.roll(dice_pool) if 6 in rolls: # Get the sixes and remove", "my handler for all shadowrun 5E related rolling functions. Types of rolls that", "async def extended_test(self, dice_pool, threshold, prime=False, exploding=False): \"\"\" Runs an extended test with", "-> {success, rolls, totals {total_hits, running_total}} \"\"\" rolls = [] totals = []", "> (len(rolls) // 2) and hits: glitch = True glitch_type = \"normal\" return", "\"type\": glitch_type} async def roll(self, dice_pool, exploding=False): \"\"\" A dice roller that handles", "modifier += i return initiative_roll, modifier class Shadowrun5Roller(): \"\"\" TODO: Add in glitch", "a roll is a glitch. SR5E CORE pg. 45-46 roll(dice_pool: int, exploding: Boolean)", "licensed under the License (MIT) located at https://github.com/ephreal/rollbot/Licence Please see the license for", "hit_limit = 4 hits, misses, ones = 0, 0, 0 for i in", "rolls async def roll_initiative(self, dice_pool, modifier=0): \"\"\" Rolls initiative for shadowrun 5E. dice_pool:", "the hit threshold if rolling for a prime runner if prime: hit_limit =", "success = False total_hits = 0 while dice_pool > 0: roll = await", "rules. Returns True if the roll is a failure. roll(dice_pool: int) -> list[int]", "successes. dice_pool : int -> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool) if 6", "that are completed inlcude general rolling and hit counting - Adding in additional", "a glitch. SR5E CORE pg. 45-46 roll(dice_pool: int, exploding: Boolean) -> list[int]: A", "= await self.roll(dice_pool, exploding=exploding) if prime: counted = await self.count_hits(roll, prime=True) else: counted", "under the License (MIT) located at https://github.com/ephreal/rollbot/Licence Please see the license for any", "-> dict{successes: int, rolls[int], failure: Bool} \"\"\" rolls = [roll for roll in", "\"\"\" Runs an extended test with a dice pool to see if it", "that handles basic dice rolling. This allows for exploding 6's with exploding=True dice_pool:", "rolls = [x for x in rolls if x != 6] added =", "bool, type: str or None} Checks whether or not a roll is a", "type: str or None} Checks whether or not a roll is a glitch.", "+= 1 else: ones += 1 return {\"hits\": hits, \"misses\": misses, \"ones\": ones}", "many integers in the rolls list exceed the target int. Returns a dictionary", "roll is a failure, which is all 1's by shadowrun 1E rules. Returns", ": list[int] -> bool \"\"\" ones = [x for x in rolls if", "SR5E CORE pg. 45 count_hits(rolls: list[int], prime: Boolean) -> {hits, misses, ones} Creates", "{\"successes\": len(rolls), \"rolls\": rolls } if await self.is_failure(rolls): successes[\"failure\"] = True else: successes[\"failure\"]", "Returns a list of integers representing the totals. roll_initiative(dice_pool: int, modifier: int) ->", "class Shadowrun5Roller(): \"\"\" TODO: Add in glitch counting. The shadowrun roller is my", "int) -> initiative: int Rolls initiative for shadowrun 5E. SR5E CORE pg. 159", "to see if any of the rolls are successes target : int roll", "rolling_utils.roll(dice_pool) for i in initiative_roll: modifier += i return initiative_roll, modifier class Shadowrun5Roller():", "reaction: int -> int \"\"\" # Adding 6's does not apply to initiative.", "rolling. This allows for exploding 6's with exploding=True SR5E CORE pg. 44 SR5E", "while dice_pool > 0: roll = await self.roll(dice_pool, exploding=exploding) if prime: counted =", "\"misses\": misses, \"ones\": ones} async def extended_test(self, dice_pool, threshold, prime=False, exploding=False): \"\"\" Runs", "rolls are successes target : int roll : list[int] -> dict{successes: int, rolls[int],", "for a prime runner, it lowers the hit threshold by 1. SR5E CORE", "range(0, len(sixes))] rolls.extend(sixes) return rolls async def roll_initiative(self, dice_pool=1, modifier=1): \"\"\" Rolls initiative", "bool, rolls: list[int], totals {total_hits: int, running_total: list[int]}} Runs extended tests by shadowrun", "int) -> initiative: int Rolls initiative dice and adds in reaction to give", "A roller class that handles the actual dice rolling. class methods: buy_hits(dice_pool: int)", "totals}} async def is_glitch(self, rolls, hits): \"\"\" Checks whether or not a roll", "totals {total_hits, running_total}} \"\"\" rolls = [] totals = [] success = False", "\"\"\" glitch = False glitch_type = None ones = [x for x in", "dice_pool: int modifier: int -> initiative: int \"\"\" initiative_roll = await self.roll(dice_pool) for", "rules. This does no checking for successes. dice_pool : int -> list[int] \"\"\"", "- Adding in additional dice with + - removing dice with - class", "4 hits, misses, ones = 0, 0, 0 for i in rolls: if", "- removing dice with - class variables: roller (base_roll_functions.roller()): A roller class that", "dice rolling. This allows for exploding 6's with exploding=True dice_pool: int exploding: Boolean", "None} \"\"\" glitch = False glitch_type = None ones = [x for x", "len(rolls): return True return False async def roll(self, dice_pool): \"\"\" Rolls and counts", "is a glitch. rolls: list[int] hits: int -> dict{glitch: bool, type: str or", "whether or not a roll is a glitch. SR5E CORE pg. 45-46 roll(dice_pool:", "hit counting - Adding in additional dice with + - removing dice with", "possible to reach a threshold. Prime will lower the threshold when counting hits", "-> bool Checks to see if the roll is a failure, which is", "await rolling_utils.roll(dice_pool=dice_pool, sides=6) if exploding: sixes = [x for x in rolls if", "threshold: int, prime: boolean) -> {success: bool, rolls: list[int], totals {total_hits: int, running_total:", "hits, misses, and ones in the rolls. If the roll is designated for", "target int. Returns a dictionary with the amount of successes and the integers", "hits, misses, ones = 0, 0, 0 for i in rolls: if i", "or None} \"\"\" glitch = False glitch_type = None ones = [x for", "misses += 1 else: ones += 1 return {\"hits\": hits, \"misses\": misses, \"ones\":", "all 1's by shadowrun 1E rules. Returns True if the roll is a", "rolls if x != 6] added = await self.roll(len(sixes)) sixes = [sixes[i] +", "__init__(self): pass async def buy_hits(self, dice_pool=0): \"\"\" \"buys\" hits at a 1 hit", "it is possible to reach a threshold. Prime will lower the threshold when", "if prime: counted = await self.count_hits(roll, prime=True) else: counted = await self.count_hits(roll) total_hits", "list[int], totals {total_hits: int, running_total: list[int]}} Runs extended tests by shadowrun 5E rules.", "a dictionary with the amount of successes and the integers that exceeded the", "if i >= hit_limit: hits += 1 elif i > 1: misses +=", "basic dice rolling. This allows for exploding 6's with exploding=True SR5E CORE pg.", "TODO: Add in glitch counting. The shadowrun roller is my handler for all", "rolling functions. Types of rolls that are completed inlcude general rolling and hit", "totals {total_hits: int, running_total: list[int]}} Runs extended tests by shadowrun 5E rules. Stops", "the sixes and remove them from the original list. sixes = [x for", "dice rolling. class methods: buy_hits(dice_pool: int) -> hits: int \"buys\" hits at a", "at a 1 hit : 4 dice ration. Rounds down. dice_pool: int ->", "if rolling for a prime runner if prime: hit_limit = 4 hits, misses,", "dice_pool=1, modifier=1): \"\"\" Rolls initiative dice and adds reaction in. dice_pool: int reaction:", "ones} Creates the amount of hits, misses, and ones in the rolls. If", "for successes. dice_pool : int -> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool) if", "= await rolling_utils.roll(dice_pool) for i in initiative_roll: modifier += i return initiative_roll, modifier", "test has been completed rather than running through all iterations if not needed.", "0, 0 for i in rolls: if i >= hit_limit: hits += 1", "= 0, 0, 0 for i in rolls: if i >= hit_limit: hits", "1 else: ones += 1 return {\"hits\": hits, \"misses\": misses, \"ones\": ones} async", "roll = await self.roll(dice_pool, exploding=exploding) if prime: counted = await self.count_hits(roll, prime=True) else:", "them from the original list. sixes = [x for x in rolls if", "[x for x in rolls if x != 6] added = await self.roll(len(sixes))", "by shadowrun 5E rules. Stops as soon as the test has been completed", "ones += 1 return {\"hits\": hits, \"misses\": misses, \"ones\": ones} async def extended_test(self,", "rolls if x == 6] rolls.extend(await self.roll(len(sixes))) rolls.sort() return rolls rolls.sort() return rolls", "(len(rolls) // 2) and hits: glitch = True glitch_type = \"normal\" return {\"glitch\":", ": list[int] -> dict{successes: int, rolls[int], failure: Bool} \"\"\" rolls = [roll for", "# roller. initiative_roll = await rolling_utils.roll(dice_pool) for i in initiative_roll: modifier += i", "the threshold when counting hits if it is True. Returns a dict with", "if len(ones) > (len(rolls) // 2) and not hits: glitch = True glitch_type", "int) -> hits: int \"buys\" hits at a 1 hit : 4 dice", "\"\"\" hit_limit = 5 # Lower the hit threshold if rolling for a", "-> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool=dice_pool, sides=6) if exploding: sixes = [x", "ratio. Rounds down. SR5E CORE pg. 45 count_hits(rolls: list[int], prime: Boolean) -> {hits,", "Returns True if the roll is a failure. roll(dice_pool: int) -> list[int] Rolls", "Shadowrun5Roller(): \"\"\" TODO: Add in glitch counting. The shadowrun roller is my handler", "hits at a 1 hit : 4 dice ration. Rounds down. dice_pool: int", "hit_limit = 5 # Lower the hit threshold if rolling for a prime", "\"\"\" Checks whether or not a roll is a glitch. rolls: list[int] hits:", "1E rules. Does no checks for failures or successes. Returns a list of", "\"rolls\": rolls, \"totals\": { \"total_hits\": total_hits, \"running_total\": totals}} async def is_glitch(self, rolls, hits):", "shadowrun 5E. dice_pool: int modifier: int -> initiative: int \"\"\" initiative_roll = await", "the test has been completed rather than running through all iterations if not", "= [x for x in rolls if x == 1] if len(ones) ==", "all items in the roll are a 1. rolls : list[int] -> bool", "threshold if rolling for a prime runner if prime: hit_limit = 4 hits,", "adds in reaction to give the initiative score. \"\"\" def __init__(self): pass async", "int) -> {glitch: bool, type: str or None} Checks whether or not a", "\"\"\" rolls = [roll for roll in rolls if roll >= target] successes", "handles the actual dice rolling. class methods: buy_hits(dice_pool: int) -> hits: int \"buys\"", "or not a roll is a glitch. rolls: list[int] hits: int -> dict{glitch:", "roll is a glitch. rolls: list[int] hits: int -> dict{glitch: bool, type: str", "list[int] Rolls and counts the dice according to shadowrun 1E rules. Does no", "list[int] hits: int -> dict{glitch: bool, type: str or None} \"\"\" glitch =", "Checks whether or not a roll is a glitch. rolls: list[int] hits: int", "dice_pool -= 1 if total_hits >= threshold: success = True break return {\"success\":", "methods: check_successes(target: int, rolls: list[int]) -> dict(successes: int, rolls: list[int], failure: bool) Checks", "await self.roll(len(sixes)) sixes = [sixes[i] + added[i] for i in range(0, len(sixes))] rolls.extend(sixes)", "4 dice ration. Rounds down. dice_pool: int -> int \"\"\" return dice_pool //", "-> {success: bool, rolls: list[int], totals {total_hits: int, running_total: list[int]}} Runs extended tests", "Rolls initiative dice and adds in reaction to give the initiative score. \"\"\"", "int, exploding: Boolean) -> list[int]: A dice roller that handles basic dice rolling.", "with exploding=True SR5E CORE pg. 44 SR5E CORE pg. 56 (Edge effects) roll_initiative(dice_pool:", "int. Returns a dictionary with the amount of successes and the integers that", "shadowrun roller for shadowrun 1E games. class methods: check_successes(target: int, rolls: list[int]) ->", "successes async def is_failure(self, rolls): \"\"\" Checks to see if the roll is", "rolls async def roll_initiative(self, dice_pool=1, modifier=1): \"\"\" Rolls initiative dice and adds reaction", "= None ones = [x for x in rolls if x == 1]", "test with a dice pool to see if it is possible to reach", "shadowrun 1E games. class methods: check_successes(target: int, rolls: list[int]) -> dict(successes: int, rolls:", "a list of integers representing the totals. roll_initiative(dice_pool: int, modifier: int) -> initiative:", "+= i return initiative_roll, modifier class Shadowrun5Roller(): \"\"\" TODO: Add in glitch counting.", "to see if the roll is a failure, which is all 1's by", "and hits: glitch = True glitch_type = \"normal\" return {\"glitch\": glitch, \"type\": glitch_type}", "int) -> list[int] Rolls and counts the dice according to shadowrun 1E rules.", "-> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool) if 6 in rolls: # Get", "variables: roller (base_roll_functions.roller()): A roller class that handles the actual dice rolling. class", "roll_initiative(self, dice_pool, modifier=0): \"\"\" Rolls initiative for shadowrun 5E. dice_pool: int modifier: int", "rolls: list[int], failure: bool) Checks how many integers in the rolls list exceed", "a 1 hit : 4 dice ration. Rounds down. dice_pool: int -> int", "and whether or not the roll is a failure is_failure(rolls: list[int]) -> bool", "# Adding 6's does not apply to initiative. Therefore use the general #", "Rolls initiative for shadowrun 5E. SR5E CORE pg. 159 \"\"\" def __init__(self): pass", "at https://github.com/ephreal/rollbot/Licence Please see the license for any restrictions or rights granted to", "games. class methods: check_successes(target: int, rolls: list[int]) -> dict(successes: int, rolls: list[int], failure:", "for a prime runner if prime: hit_limit = 4 hits, misses, ones =", "misses, \"ones\": ones} async def extended_test(self, dice_pool, threshold, prime=False, exploding=False): \"\"\" Runs an", "Returns a dictionary with the amount of successes and the integers that exceeded", "45 count_hits(rolls: list[int], prime: Boolean) -> {hits, misses, ones} Creates the amount of", "prime: hit_limit = 4 hits, misses, ones = 0, 0, 0 for i", "and a list of int lists representing the rolls. dice_pool: int threshold: int", "failure. roll(dice_pool: int) -> list[int] Rolls and counts the dice according to shadowrun", "bool -> {success, rolls, totals {total_hits, running_total}} \"\"\" rolls = [] totals =", "granted to you by the License. \"\"\" from utils.rolling import rolling_utils class Shadowrun3Roller():", "1] if len(ones) == len(rolls): return True return False async def roll(self, dice_pool):", "a threshold. Prime will lower the threshold when counting hits if it is", "= [x for x in rolls if x == 1] if len(ones) >", "elif len(ones) > (len(rolls) // 2) and hits: glitch = True glitch_type =", "according to shadowrun 1E rules. Does no checks for failures or successes. Returns", "int, running_total: list[int]}} Runs extended tests by shadowrun 5E rules. Stops as soon", "dice pool to see if it is possible to reach a threshold. Prime", "to give the initiative score. \"\"\" def __init__(self): pass async def check_successes(self, target,", "if it is True. Returns a dict with a boolean representing success status", "not a roll is a glitch. rolls: list[int] hits: int -> dict{glitch: bool,", "and ones in a list of integers. rolls: list[int] -> {hits, misses, ones}", "prime=False): \"\"\" Counts the amount of hits, misses, and ones in a list", "This software is licensed under the License (MIT) located at https://github.com/ephreal/rollbot/Licence Please see", "successes = {\"successes\": len(rolls), \"rolls\": rolls } if await self.is_failure(rolls): successes[\"failure\"] = True", "adds reaction in. dice_pool: int reaction: int -> int \"\"\" # Adding 6's", "use the general # roller. initiative_roll = await rolling_utils.roll(dice_pool) for i in initiative_roll:", ": 4 dice ratio. Rounds down. SR5E CORE pg. 45 count_hits(rolls: list[int], prime:", "1 hit : 4 dice ration. Rounds down. dice_pool: int -> int \"\"\"", "# Lower the hit threshold if rolling for a prime runner if prime:", "bool \"\"\" ones = [x for x in rolls if x == 1]", "5E related rolling functions. Types of rolls that are completed inlcude general rolling", "list[int]: A dice roller that handles basic dice rolling. This allows for exploding", "totals.append(total_hits) rolls.append({\"hits\": counted[\"hits\"], \"roll\": roll}) dice_pool -= 1 if total_hits >= threshold: success", "glitch = True glitch_type = \"critical\" elif len(ones) > (len(rolls) // 2) and", "Rolls and counts the dice according to shadowrun 1E rules. This does no", "rolls.sort() return rolls rolls.sort() return rolls async def roll_initiative(self, dice_pool, modifier=0): \"\"\" Rolls", "no checks for failures or successes. Returns a list of integers representing the", "in rolls: # Get the sixes and remove them from the original list.", "{hits, misses, ones} \"\"\" hit_limit = 5 # Lower the hit threshold if", "you by the License. \"\"\" from utils.rolling import rolling_utils class Shadowrun3Roller(): \"\"\" The", "int lists representing the rolls. dice_pool: int threshold: int prime: bool exploding: bool", "failure: bool) Checks how many integers in the rolls list exceed the target", "\"buys\" hits at a 1 hit : 4 dice ration. Rounds down. dice_pool:", "initiative: int Rolls initiative for shadowrun 5E. SR5E CORE pg. 159 \"\"\" def", "dict{glitch: bool, type: str or None} \"\"\" glitch = False glitch_type = None", "// 2) and not hits: glitch = True glitch_type = \"critical\" elif len(ones)", "6] rolls = [x for x in rolls if x != 6] added", "in rolls if x != 6] added = await self.roll(len(sixes)) sixes = [sixes[i]", "whether or not a roll is a glitch. rolls: list[int] hits: int ->", "roll(dice_pool: int) -> list[int] Rolls and counts the dice according to shadowrun 1E", "items in the roll are a 1. rolls : list[int] -> bool \"\"\"", "if the roll is a failure. roll(dice_pool: int) -> list[int] Rolls and counts", "initiative dice and adds in reaction to give the initiative score. \"\"\" def", "\"rolls\": rolls } if await self.is_failure(rolls): successes[\"failure\"] = True else: successes[\"failure\"] = False", "[x for x in rolls if x == 1] if len(ones) == len(rolls):", "class that handles the actual dice rolling. class methods: buy_hits(dice_pool: int) -> hits:", "methods: buy_hits(dice_pool: int) -> hits: int \"buys\" hits at a 1 hit :", "int, rolls: list[int], failure: bool) Checks how many integers in the rolls list", "at a 1 hit : 4 dice ratio. Rounds down. SR5E CORE pg.", "ones = 0, 0, 0 for i in rolls: if i >= hit_limit:", "len(ones) > (len(rolls) // 2) and not hits: glitch = True glitch_type =", "is True. Returns a dict with a boolean representing success status and a", "list[int]) -> bool Checks to see if the roll is a failure, which", "async def is_failure(self, rolls): \"\"\" Checks to see if the roll is a", "roll}) dice_pool -= 1 if total_hits >= threshold: success = True break return", "Get the sixes and remove them from the original list. sixes = [x", "def roll(self, dice_pool): \"\"\" Rolls and counts the dice according to shadowrun 1E", "Checks to see if the roll is a failure, which is all 1's", "roller class that handles the actual dice rolling. class methods: buy_hits(dice_pool: int) ->", "successes and the integers that exceeded the target and whether or not the", "\"\"\" def __init__(self): pass async def buy_hits(self, dice_pool=0): \"\"\" \"buys\" hits at a", "lower the threshold when counting hits if it is True. Returns a dict", "with exploding=True dice_pool: int exploding: Boolean -> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool=dice_pool,", "== 1] if len(ones) == len(rolls): return True return False async def roll(self,", "class variables: roller (base_roll_functions.roller()): A roller class that handles the actual dice rolling.", "pass async def check_successes(self, target, rolls): \"\"\" Checks the rolls to see if", "from utils.rolling import rolling_utils class Shadowrun3Roller(): \"\"\" The shadowrun roller for shadowrun 1E", "shadowrun 1E rules. This does no checking for successes. dice_pool : int ->", "exploding: bool -> {success, rolls, totals {total_hits, running_total}} \"\"\" rolls = [] totals", "does no checking for successes. dice_pool : int -> list[int] \"\"\" rolls =", "\"\"\" # Adding 6's does not apply to initiative. Therefore use the general", "restrictions or rights granted to you by the License. \"\"\" from utils.rolling import", "are a 1. rolls : list[int] -> bool \"\"\" ones = [x for", "roll(self, dice_pool, exploding=False): \"\"\" A dice roller that handles basic dice rolling. This", "int Rolls initiative for shadowrun 5E. SR5E CORE pg. 159 \"\"\" def __init__(self):", "len(sixes))] rolls.extend(sixes) return rolls async def roll_initiative(self, dice_pool=1, modifier=1): \"\"\" Rolls initiative dice", "the amount of hits, misses, and ones in the rolls. If the roll", "{total_hits, running_total}} \"\"\" rolls = [] totals = [] success = False total_hits", "break return {\"success\": success, \"rolls\": rolls, \"totals\": { \"total_hits\": total_hits, \"running_total\": totals}} async", "exploding=False): \"\"\" Runs an extended test with a dice pool to see if", "glitch_type = \"critical\" elif len(ones) > (len(rolls) // 2) and hits: glitch =", "i return initiative_roll, modifier class Shadowrun5Roller(): \"\"\" TODO: Add in glitch counting. The", "the original list. sixes = [x for x in rolls if x ==", "handles basic dice rolling. This allows for exploding 6's with exploding=True SR5E CORE", "failures or successes. Returns a list of integers representing the totals. roll_initiative(dice_pool: int,", "0, 0, 0 for i in rolls: if i >= hit_limit: hits +=", "== 6] rolls.extend(await self.roll(len(sixes))) rolls.sort() return rolls rolls.sort() return rolls async def roll_initiative(self,", "not a roll is a glitch. SR5E CORE pg. 45-46 roll(dice_pool: int, exploding:", "iterations if not needed. SR5E CORE pg. 48 is_glitch(rolls: list[int], hits: int) ->", "to reach a threshold. Prime will lower the threshold when counting hits if", "integers in the rolls list exceed the target int. Returns a dictionary with", "see the license for any restrictions or rights granted to you by the", "see if the roll is a failure, which is all 1's by shadowrun", "Bool} \"\"\" rolls = [roll for roll in rolls if roll >= target]", "glitch counting. The shadowrun roller is my handler for all shadowrun 5E related", "dice and adds reaction in. dice_pool: int reaction: int -> int \"\"\" #", "a 1. rolls : list[int] -> bool \"\"\" ones = [x for x", "== 6] rolls = [x for x in rolls if x != 6]", "\"\"\" TODO: Add in glitch counting. The shadowrun roller is my handler for", "int threshold: int prime: bool exploding: bool -> {success, rolls, totals {total_hits, running_total}}", "exploding=exploding) if prime: counted = await self.count_hits(roll, prime=True) else: counted = await self.count_hits(roll)", "integers representing the totals. roll_initiative(dice_pool: int, modifier: int) -> initiative: int Rolls initiative", "Runs extended tests by shadowrun 5E rules. Stops as soon as the test", "48 is_glitch(rolls: list[int], hits: int) -> {glitch: bool, type: str or None} Checks", "in rolls if x == 1] if len(ones) == len(rolls): return True return", "totals = [] success = False total_hits = 0 while dice_pool > 0:", "misses, and ones in a list of integers. rolls: list[int] -> {hits, misses,", "prime: counted = await self.count_hits(roll, prime=True) else: counted = await self.count_hits(roll) total_hits +=", "amount of hits, misses, and ones in a list of integers. rolls: list[int]", "x != 6] added = await self.roll(len(sixes)) sixes = [sixes[i] + added[i] for", "exploding: Boolean) -> list[int]: A dice roller that handles basic dice rolling. This", "for exploding 6's with exploding=True dice_pool: int exploding: Boolean -> list[int] \"\"\" rolls", "False async def roll(self, dice_pool): \"\"\" Rolls and counts the dice according to", "that exceeded the target and whether or not the roll is a failure", "rolls if x == 1] if len(ones) == len(rolls): return True return False", "Therefore use the general # roller. initiative_roll = await rolling_utils.roll(dice_pool) for i in", "(Edge effects) roll_initiative(dice_pool: int, modifier: int) -> initiative: int Rolls initiative for shadowrun", "+= counted[\"hits\"] totals.append(total_hits) rolls.append({\"hits\": counted[\"hits\"], \"roll\": roll}) dice_pool -= 1 if total_hits >=", "functions. Types of rolls that are completed inlcude general rolling and hit counting", "44 extended_test(dice_pool: int, threshold: int, prime: boolean) -> {success: bool, rolls: list[int], totals", "original list. sixes = [x for x in rolls if x == 6]", "-> {glitch: bool, type: str or None} Checks whether or not a roll", "CORE pg. 45-46 roll(dice_pool: int, exploding: Boolean) -> list[int]: A dice roller that", "def __init__(self): pass async def buy_hits(self, dice_pool=0): \"\"\" \"buys\" hits at a 1", "extended_test(self, dice_pool, threshold, prime=False, exploding=False): \"\"\" Runs an extended test with a dice", "actual dice rolling. class methods: buy_hits(dice_pool: int) -> hits: int \"buys\" hits at", "basic dice rolling. This allows for exploding 6's with exploding=True dice_pool: int exploding:", "to see if the roll is a failure. This is only the case", "-> bool \"\"\" ones = [x for x in rolls if x ==", "return False async def roll(self, dice_pool): \"\"\" Rolls and counts the dice according", "through all iterations if not needed. SR5E CORE pg. 48 is_glitch(rolls: list[int], hits:", "= [x for x in rolls if x == 6] rolls = [x", "down. dice_pool: int -> int \"\"\" return dice_pool // 4 async def count_hits(self,", "for roll in rolls if roll >= target] successes = {\"successes\": len(rolls), \"rolls\":", "exceed the target int. Returns a dictionary with the amount of successes and", "Shadowrun3Roller(): \"\"\" The shadowrun roller for shadowrun 1E games. class methods: check_successes(target: int,", "list of integers. rolls: list[int] -> {hits, misses, ones} \"\"\" hit_limit = 5", "when counting hits if it is True. Returns a dict with a boolean", "int -> int \"\"\" # Adding 6's does not apply to initiative. Therefore", "rolls = [] totals = [] success = False total_hits = 0 while", "in rolls if roll >= target] successes = {\"successes\": len(rolls), \"rolls\": rolls }", "if 6 in rolls: # Get the sixes and remove them from the", "self.roll(len(sixes)) sixes = [sixes[i] + added[i] for i in range(0, len(sixes))] rolls.extend(sixes) return", "for i in initiative_roll: modifier += i return initiative_roll, modifier class Shadowrun5Roller(): \"\"\"", "roll is a failure. This is only the case if all items in", "{success: bool, rolls: list[int], totals {total_hits: int, running_total: list[int]}} Runs extended tests by", "the rolls. If the roll is designated for a prime runner, it lowers", "Lower the hit threshold if rolling for a prime runner if prime: hit_limit", "extended test with a dice pool to see if it is possible to", "no checking for successes. dice_pool : int -> list[int] \"\"\" rolls = await", "the hit threshold by 1. SR5E CORE pg. 44 extended_test(dice_pool: int, threshold: int,", "threshold when counting hits if it is True. Returns a dict with a", "= False glitch_type = None ones = [x for x in rolls if", "initiative score. \"\"\" def __init__(self): pass async def check_successes(self, target, rolls): \"\"\" Checks", "a failure, which is all 1's by shadowrun 1E rules. Returns True if", "in glitch counting. The shadowrun roller is my handler for all shadowrun 5E", "glitch. SR5E CORE pg. 45-46 roll(dice_pool: int, exploding: Boolean) -> list[int]: A dice", "pool to see if it is possible to reach a threshold. Prime will", "glitch_type = None ones = [x for x in rolls if x ==", ": int roll : list[int] -> dict{successes: int, rolls[int], failure: Bool} \"\"\" rolls", "def buy_hits(self, dice_pool=0): \"\"\" \"buys\" hits at a 1 hit : 4 dice", "def roll_initiative(self, dice_pool=1, modifier=1): \"\"\" Rolls initiative dice and adds reaction in. dice_pool:", "if exploding: sixes = [x for x in rolls if x == 6]", "\"\"\" Checks to see if the roll is a failure. This is only", "5E. dice_pool: int modifier: int -> initiative: int \"\"\" initiative_roll = await self.roll(dice_pool)", "__init__(self): pass async def check_successes(self, target, rolls): \"\"\" Checks the rolls to see", "\"\"\" Rolls and counts the dice according to shadowrun 1E rules. This does", "initiative dice and adds reaction in. dice_pool: int reaction: int -> int \"\"\"", "def roll(self, dice_pool, exploding=False): \"\"\" A dice roller that handles basic dice rolling.", "roll is a glitch. SR5E CORE pg. 45-46 roll(dice_pool: int, exploding: Boolean) ->", "with - class variables: roller (base_roll_functions.roller()): A roller class that handles the actual", "tests by shadowrun 5E rules. Stops as soon as the test has been", "the rolls list exceed the target int. Returns a dictionary with the amount", "int, prime: boolean) -> {success: bool, rolls: list[int], totals {total_hits: int, running_total: list[int]}}", "modifier=0): \"\"\" Rolls initiative for shadowrun 5E. dice_pool: int modifier: int -> initiative:", "len(ones) == len(rolls): return True return False async def roll(self, dice_pool): \"\"\" Rolls", "if not needed. SR5E CORE pg. 48 is_glitch(rolls: list[int], hits: int) -> {glitch:", "successes[\"failure\"] = False return successes async def is_failure(self, rolls): \"\"\" Checks to see", "for i in rolls: if i >= hit_limit: hits += 1 elif i", "or successes. Returns a list of integers representing the totals. roll_initiative(dice_pool: int, modifier:", "[] success = False total_hits = 0 while dice_pool > 0: roll =", "to see if it is possible to reach a threshold. Prime will lower", "True else: successes[\"failure\"] = False return successes async def is_failure(self, rolls): \"\"\" Checks", "handler for all shadowrun 5E related rolling functions. Types of rolls that are", "async def buy_hits(self, dice_pool=0): \"\"\" \"buys\" hits at a 1 hit : 4", "count_hits(rolls: list[int], prime: Boolean) -> {hits, misses, ones} Creates the amount of hits,", "1 return {\"hits\": hits, \"misses\": misses, \"ones\": ones} async def extended_test(self, dice_pool, threshold,", "bool Checks to see if the roll is a failure, which is all", "Rolls and counts the dice according to shadowrun 1E rules. Does no checks", "5 # Lower the hit threshold if rolling for a prime runner if", "not hits: glitch = True glitch_type = \"critical\" elif len(ones) > (len(rolls) //", "x in rolls if x == 1] if len(ones) > (len(rolls) // 2)", "= [] success = False total_hits = 0 while dice_pool > 0: roll", "running through all iterations if not needed. SR5E CORE pg. 48 is_glitch(rolls: list[int],", "rolls if x == 1] if len(ones) > (len(rolls) // 2) and not", "This allows for exploding 6's with exploding=True SR5E CORE pg. 44 SR5E CORE", "async def is_glitch(self, rolls, hits): \"\"\" Checks whether or not a roll is", "= [sixes[i] + added[i] for i in range(0, len(sixes))] rolls.extend(sixes) return rolls async", "shadowrun roller is my handler for all shadowrun 5E related rolling functions. Types", "the roll is designated for a prime runner, it lowers the hit threshold", "runner, it lowers the hit threshold by 1. SR5E CORE pg. 44 extended_test(dice_pool:", "to shadowrun 1E rules. This does no checking for successes. dice_pool : int", "i in initiative_roll: modifier += i return initiative_roll, modifier class Shadowrun5Roller(): \"\"\" TODO:", "dice_pool: int -> int \"\"\" return dice_pool // 4 async def count_hits(self, rolls,", "dice_pool : int -> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool) if 6 in", "is a glitch. SR5E CORE pg. 45-46 roll(dice_pool: int, exploding: Boolean) -> list[int]:", "reaction in. dice_pool: int reaction: int -> int \"\"\" # Adding 6's does", "str or None} \"\"\" glitch = False glitch_type = None ones = [x", "def is_glitch(self, rolls, hits): \"\"\" Checks whether or not a roll is a", "-> initiative: int Rolls initiative dice and adds in reaction to give the", "\"\"\" def __init__(self): pass async def check_successes(self, target, rolls): \"\"\" Checks the rolls", "a dice pool to see if it is possible to reach a threshold.", "for x in rolls if x == 1] if len(ones) > (len(rolls) //", "= 4 hits, misses, ones = 0, 0, 0 for i in rolls:", "await rolling_utils.roll(dice_pool) if 6 in rolls: # Get the sixes and remove them", "\"\"\" Rolls initiative for shadowrun 5E. dice_pool: int modifier: int -> initiative: int", "dice ratio. Rounds down. SR5E CORE pg. 45 count_hits(rolls: list[int], prime: Boolean) ->", "the roll is a failure. This is only the case if all items", "hit : 4 dice ration. Rounds down. dice_pool: int -> int \"\"\" return", "list[int]}} Runs extended tests by shadowrun 5E rules. Stops as soon as the", "= [x for x in rolls if x != 6] added = await", "if await self.is_failure(rolls): successes[\"failure\"] = True else: successes[\"failure\"] = False return successes async", "target] successes = {\"successes\": len(rolls), \"rolls\": rolls } if await self.is_failure(rolls): successes[\"failure\"] =", "!= 6] added = await self.roll(len(sixes)) sixes = [sixes[i] + added[i] for i", "not the roll is a failure is_failure(rolls: list[int]) -> bool Checks to see", "rolling and hit counting - Adding in additional dice with + - removing", "1 hit : 4 dice ratio. Rounds down. SR5E CORE pg. 45 count_hits(rolls:", "dice with + - removing dice with - class variables: roller (base_roll_functions.roller()): A", "and counts the dice according to shadowrun 1E rules. Does no checks for", "\"\"\" The shadowrun roller for shadowrun 1E games. class methods: check_successes(target: int, rolls:", "int prime: bool exploding: bool -> {success, rolls, totals {total_hits, running_total}} \"\"\" rolls", "\"ones\": ones} async def extended_test(self, dice_pool, threshold, prime=False, exploding=False): \"\"\" Runs an extended", "for x in rolls if x == 6] rolls = [x for x", "success, \"rolls\": rolls, \"totals\": { \"total_hits\": total_hits, \"running_total\": totals}} async def is_glitch(self, rolls,", "are successes target : int roll : list[int] -> dict{successes: int, rolls[int], failure:", "return rolls async def roll_initiative(self, dice_pool, modifier=0): \"\"\" Rolls initiative for shadowrun 5E.", "+= 1 return {\"hits\": hits, \"misses\": misses, \"ones\": ones} async def extended_test(self, dice_pool,", "ones in the rolls. If the roll is designated for a prime runner,", "prime runner, it lowers the hit threshold by 1. SR5E CORE pg. 44", "for failures or successes. Returns a list of integers representing the totals. roll_initiative(dice_pool:", "dice_pool > 0: roll = await self.roll(dice_pool, exploding=exploding) if prime: counted = await", "-> initiative: int Rolls initiative for shadowrun 5E. SR5E CORE pg. 159 \"\"\"", "rolls list exceed the target int. Returns a dictionary with the amount of", "\"running_total\": totals}} async def is_glitch(self, rolls, hits): \"\"\" Checks whether or not a", "allows for exploding 6's with exploding=True dice_pool: int exploding: Boolean -> list[int] \"\"\"", "1E games. class methods: check_successes(target: int, rolls: list[int]) -> dict(successes: int, rolls: list[int],", "is_glitch(rolls: list[int], hits: int) -> {glitch: bool, type: str or None} Checks whether", "= [roll for roll in rolls if roll >= target] successes = {\"successes\":", "is licensed under the License (MIT) located at https://github.com/ephreal/rollbot/Licence Please see the license", "the dice according to shadowrun 1E rules. This does no checking for successes.", ">= hit_limit: hits += 1 elif i > 1: misses += 1 else:", "rolling_utils.roll(dice_pool) if 6 in rolls: # Get the sixes and remove them from", "rolling_utils class Shadowrun3Roller(): \"\"\" The shadowrun roller for shadowrun 1E games. class methods:", "rolls[int], failure: Bool} \"\"\" rolls = [roll for roll in rolls if roll", "glitch_type = \"normal\" return {\"glitch\": glitch, \"type\": glitch_type} async def roll(self, dice_pool, exploding=False):", "success = True break return {\"success\": success, \"rolls\": rolls, \"totals\": { \"total_hits\": total_hits,", "hits: int \"buys\" hits at a 1 hit : 4 dice ratio. Rounds", "sixes = [x for x in rolls if x == 6] rolls.extend(await self.roll(len(sixes)))", "status and a list of int lists representing the rolls. dice_pool: int threshold:", "misses, and ones in the rolls. If the roll is designated for a", "= True else: successes[\"failure\"] = False return successes async def is_failure(self, rolls): \"\"\"", "in the rolls list exceed the target int. Returns a dictionary with the", "return initiative_roll, modifier class Shadowrun5Roller(): \"\"\" TODO: Add in glitch counting. The shadowrun", "ones in a list of integers. rolls: list[int] -> {hits, misses, ones} \"\"\"", "\"roll\": roll}) dice_pool -= 1 if total_hits >= threshold: success = True break", "bool, type: str or None} \"\"\" glitch = False glitch_type = None ones", "a boolean representing success status and a list of int lists representing the", "check_successes(self, target, rolls): \"\"\" Checks the rolls to see if any of the", "and adds reaction in. dice_pool: int reaction: int -> int \"\"\" # Adding", "await self.roll(dice_pool, exploding=exploding) if prime: counted = await self.count_hits(roll, prime=True) else: counted =", "checking for successes. dice_pool : int -> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool)", "else: counted = await self.count_hits(roll) total_hits += counted[\"hits\"] totals.append(total_hits) rolls.append({\"hits\": counted[\"hits\"], \"roll\": roll})", "x in rolls if x == 6] rolls = [x for x in", "True glitch_type = \"normal\" return {\"glitch\": glitch, \"type\": glitch_type} async def roll(self, dice_pool,", "str or None} Checks whether or not a roll is a glitch. SR5E", "return successes async def is_failure(self, rolls): \"\"\" Checks to see if the roll", "apply to initiative. Therefore use the general # roller. initiative_roll = await rolling_utils.roll(dice_pool)", "roller is my handler for all shadowrun 5E related rolling functions. Types of", "Adding 6's does not apply to initiative. Therefore use the general # roller.", "Boolean) -> list[int]: A dice roller that handles basic dice rolling. This allows", "roll_initiative(self, dice_pool=1, modifier=1): \"\"\" Rolls initiative dice and adds reaction in. dice_pool: int", "True if the roll is a failure. roll(dice_pool: int) -> list[int] Rolls and", "a failure. This is only the case if all items in the roll", "by shadowrun 1E rules. Returns True if the roll is a failure. roll(dice_pool:", "class methods: buy_hits(dice_pool: int) -> hits: int \"buys\" hits at a 1 hit", "software is licensed under the License (MIT) located at https://github.com/ephreal/rollbot/Licence Please see the", "hits: int) -> {glitch: bool, type: str or None} Checks whether or not", "56 (Edge effects) roll_initiative(dice_pool: int, modifier: int) -> initiative: int Rolls initiative for", "the roll are a 1. rolls : list[int] -> bool \"\"\" ones =", "return rolls rolls.sort() return rolls async def roll_initiative(self, dice_pool, modifier=0): \"\"\" Rolls initiative", "does not apply to initiative. Therefore use the general # roller. initiative_roll =", "-> {hits, misses, ones} \"\"\" hit_limit = 5 # Lower the hit threshold", "CORE pg. 56 (Edge effects) roll_initiative(dice_pool: int, modifier: int) -> initiative: int Rolls", "misses, ones} Creates the amount of hits, misses, and ones in the rolls.", "roll in rolls if roll >= target] successes = {\"successes\": len(rolls), \"rolls\": rolls", "if x == 6] rolls.extend(await self.roll(len(sixes))) rolls.sort() return rolls rolls.sort() return rolls async", "= 0 while dice_pool > 0: roll = await self.roll(dice_pool, exploding=exploding) if prime:", "= await self.roll(dice_pool) for i in initiative_roll: modifier += i return initiative_roll, modifier", "ones} \"\"\" hit_limit = 5 # Lower the hit threshold if rolling for", "an extended test with a dice pool to see if it is possible", "0: roll = await self.roll(dice_pool, exploding=exploding) if prime: counted = await self.count_hits(roll, prime=True)", "= await self.count_hits(roll, prime=True) else: counted = await self.count_hits(roll) total_hits += counted[\"hits\"] totals.append(total_hits)", "rolls): \"\"\" Checks to see if the roll is a failure. This is", "the rolls. dice_pool: int threshold: int prime: bool exploding: bool -> {success, rolls,", "hits at a 1 hit : 4 dice ratio. Rounds down. SR5E CORE", "await self.is_failure(rolls): successes[\"failure\"] = True else: successes[\"failure\"] = False return successes async def", "= {\"successes\": len(rolls), \"rolls\": rolls } if await self.is_failure(rolls): successes[\"failure\"] = True else:", "list[int]) -> dict(successes: int, rolls: list[int], failure: bool) Checks how many integers in", "initiative_roll, modifier class Shadowrun5Roller(): \"\"\" TODO: Add in glitch counting. The shadowrun roller", "SR5E CORE pg. 45-46 roll(dice_pool: int, exploding: Boolean) -> list[int]: A dice roller", "Checks whether or not a roll is a glitch. SR5E CORE pg. 45-46", "= \"critical\" elif len(ones) > (len(rolls) // 2) and hits: glitch = True", "glitch = True glitch_type = \"normal\" return {\"glitch\": glitch, \"type\": glitch_type} async def", "rolls } if await self.is_failure(rolls): successes[\"failure\"] = True else: successes[\"failure\"] = False return", "initiative. Therefore use the general # roller. initiative_roll = await rolling_utils.roll(dice_pool) for i", "added = await self.roll(len(sixes)) sixes = [sixes[i] + added[i] for i in range(0,", "not needed. SR5E CORE pg. 48 is_glitch(rolls: list[int], hits: int) -> {glitch: bool,", "list[int] -> {hits, misses, ones} \"\"\" hit_limit = 5 # Lower the hit", "await self.count_hits(roll, prime=True) else: counted = await self.count_hits(roll) total_hits += counted[\"hits\"] totals.append(total_hits) rolls.append({\"hits\":", "of int lists representing the rolls. dice_pool: int threshold: int prime: bool exploding:", "= await self.count_hits(roll) total_hits += counted[\"hits\"] totals.append(total_hits) rolls.append({\"hits\": counted[\"hits\"], \"roll\": roll}) dice_pool -=", "score. \"\"\" def __init__(self): pass async def check_successes(self, target, rolls): \"\"\" Checks the", "== 1] if len(ones) > (len(rolls) // 2) and not hits: glitch =", "Boolean) -> {hits, misses, ones} Creates the amount of hits, misses, and ones", "+ added[i] for i in range(0, len(sixes))] rolls.extend(sixes) return rolls async def roll_initiative(self,", "async def count_hits(self, rolls, prime=False): \"\"\" Counts the amount of hits, misses, and", "in rolls: if i >= hit_limit: hits += 1 elif i > 1:", "-> int \"\"\" # Adding 6's does not apply to initiative. Therefore use", "License (MIT) located at https://github.com/ephreal/rollbot/Licence Please see the license for any restrictions or", "to shadowrun 1E rules. Does no checks for failures or successes. Returns a", "rolls if roll >= target] successes = {\"successes\": len(rolls), \"rolls\": rolls } if", "// 2) and hits: glitch = True glitch_type = \"normal\" return {\"glitch\": glitch,", "x == 6] rolls.extend(await self.roll(len(sixes))) rolls.sort() return rolls rolls.sort() return rolls async def", "for exploding 6's with exploding=True SR5E CORE pg. 44 SR5E CORE pg. 56", "x == 6] rolls = [x for x in rolls if x !=", "ones} async def extended_test(self, dice_pool, threshold, prime=False, exploding=False): \"\"\" Runs an extended test", "rolling. This allows for exploding 6's with exploding=True dice_pool: int exploding: Boolean ->", "as soon as the test has been completed rather than running through all", "with a dice pool to see if it is possible to reach a", "6's with exploding=True dice_pool: int exploding: Boolean -> list[int] \"\"\" rolls = await", "rolls.extend(await self.roll(len(sixes))) rolls.sort() return rolls rolls.sort() return rolls async def roll_initiative(self, dice_pool, modifier=0):", "in reaction to give the initiative score. \"\"\" def __init__(self): pass async def", "give the initiative score. \"\"\" def __init__(self): pass async def check_successes(self, target, rolls):", "shadowrun 5E. SR5E CORE pg. 159 \"\"\" def __init__(self): pass async def buy_hits(self,", "1E rules. Returns True if the roll is a failure. roll(dice_pool: int) ->", "to you by the License. \"\"\" from utils.rolling import rolling_utils class Shadowrun3Roller(): \"\"\"", "and adds in reaction to give the initiative score. \"\"\" def __init__(self): pass", "if roll >= target] successes = {\"successes\": len(rolls), \"rolls\": rolls } if await", "and counts the dice according to shadowrun 1E rules. This does no checking", "related rolling functions. Types of rolls that are completed inlcude general rolling and", "hits): \"\"\" Checks whether or not a roll is a glitch. rolls: list[int]", ": 4 dice ration. Rounds down. dice_pool: int -> int \"\"\" return dice_pool", "see if the roll is a failure. This is only the case if", "from the original list. sixes = [x for x in rolls if x", "if total_hits >= threshold: success = True break return {\"success\": success, \"rolls\": rolls,", "inlcude general rolling and hit counting - Adding in additional dice with +", "modifier: int) -> initiative: int Rolls initiative dice and adds in reaction to", "1E rules. This does no checking for successes. dice_pool : int -> list[int]", "[roll for roll in rolls if roll >= target] successes = {\"successes\": len(rolls),", "threshold: int prime: bool exploding: bool -> {success, rolls, totals {total_hits, running_total}} \"\"\"", "ration. Rounds down. dice_pool: int -> int \"\"\" return dice_pool // 4 async", "x == 1] if len(ones) > (len(rolls) // 2) and not hits: glitch", "for any restrictions or rights granted to you by the License. \"\"\" from", "shadowrun 5E rules. Stops as soon as the test has been completed rather", "the amount of hits, misses, and ones in a list of integers. rolls:", "and remove them from the original list. sixes = [x for x in", "-> hits: int \"buys\" hits at a 1 hit : 4 dice ratio.", "a 1 hit : 4 dice ratio. Rounds down. SR5E CORE pg. 45", "\"\"\" Rolls initiative dice and adds reaction in. dice_pool: int reaction: int ->", "failure. This is only the case if all items in the roll are", "counts the dice according to shadowrun 1E rules. This does no checking for", "(MIT) located at https://github.com/ephreal/rollbot/Licence Please see the license for any restrictions or rights", "> (len(rolls) // 2) and not hits: glitch = True glitch_type = \"critical\"", "is a failure. roll(dice_pool: int) -> list[int] Rolls and counts the dice according", "def roll_initiative(self, dice_pool, modifier=0): \"\"\" Rolls initiative for shadowrun 5E. dice_pool: int modifier:", "dice and adds in reaction to give the initiative score. \"\"\" def __init__(self):", "\"buys\" hits at a 1 hit : 4 dice ratio. Rounds down. SR5E", "of hits, misses, and ones in the rolls. If the roll is designated", "glitch_type} async def roll(self, dice_pool, exploding=False): \"\"\" A dice roller that handles basic", "-> dict{glitch: bool, type: str or None} \"\"\" glitch = False glitch_type =", "\"\"\" return dice_pool // 4 async def count_hits(self, rolls, prime=False): \"\"\" Counts the", "list[int] -> dict{successes: int, rolls[int], failure: Bool} \"\"\" rolls = [roll for roll", "if x == 1] if len(ones) > (len(rolls) // 2) and not hits:", "bool) Checks how many integers in the rolls list exceed the target int.", "that handles basic dice rolling. This allows for exploding 6's with exploding=True SR5E", "int -> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool) if 6 in rolls: #", "according to shadowrun 1E rules. This does no checking for successes. dice_pool :", "by 1. SR5E CORE pg. 44 extended_test(dice_pool: int, threshold: int, prime: boolean) ->", "rolling. class methods: buy_hits(dice_pool: int) -> hits: int \"buys\" hits at a 1", "1. SR5E CORE pg. 44 extended_test(dice_pool: int, threshold: int, prime: boolean) -> {success:", "Stops as soon as the test has been completed rather than running through", "a glitch. rolls: list[int] hits: int -> dict{glitch: bool, type: str or None}", "see if any of the rolls are successes target : int roll :", "5E. SR5E CORE pg. 159 \"\"\" def __init__(self): pass async def buy_hits(self, dice_pool=0):", "\"total_hits\": total_hits, \"running_total\": totals}} async def is_glitch(self, rolls, hits): \"\"\" Checks whether or", "= await rolling_utils.roll(dice_pool=dice_pool, sides=6) if exploding: sixes = [x for x in rolls", "rolls: list[int]) -> dict(successes: int, rolls: list[int], failure: bool) Checks how many integers", "initiative_roll = await rolling_utils.roll(dice_pool) for i in initiative_roll: modifier += i return initiative_roll,", "how many integers in the rolls list exceed the target int. Returns a", "{ \"total_hits\": total_hits, \"running_total\": totals}} async def is_glitch(self, rolls, hits): \"\"\" Checks whether", "utils.rolling import rolling_utils class Shadowrun3Roller(): \"\"\" The shadowrun roller for shadowrun 1E games.", "and ones in the rolls. If the roll is designated for a prime", "= True break return {\"success\": success, \"rolls\": rolls, \"totals\": { \"total_hits\": total_hits, \"running_total\":", "hits, \"misses\": misses, \"ones\": ones} async def extended_test(self, dice_pool, threshold, prime=False, exploding=False): \"\"\"", "threshold by 1. SR5E CORE pg. 44 extended_test(dice_pool: int, threshold: int, prime: boolean)", "as the test has been completed rather than running through all iterations if", "or None} Checks whether or not a roll is a glitch. SR5E CORE", "glitch = False glitch_type = None ones = [x for x in rolls", "the license for any restrictions or rights granted to you by the License.", "target and whether or not the roll is a failure is_failure(rolls: list[int]) ->", "hit threshold by 1. SR5E CORE pg. 44 extended_test(dice_pool: int, threshold: int, prime:", "hit : 4 dice ratio. Rounds down. SR5E CORE pg. 45 count_hits(rolls: list[int],", "5E rules. Stops as soon as the test has been completed rather than", ">= target] successes = {\"successes\": len(rolls), \"rolls\": rolls } if await self.is_failure(rolls): successes[\"failure\"]", "rolls, totals {total_hits, running_total}} \"\"\" rolls = [] totals = [] success =", "list[int], hits: int) -> {glitch: bool, type: str or None} Checks whether or", "SR5E CORE pg. 44 extended_test(dice_pool: int, threshold: int, prime: boolean) -> {success: bool,", "soon as the test has been completed rather than running through all iterations", "(base_roll_functions.roller()): A roller class that handles the actual dice rolling. class methods: buy_hits(dice_pool:", "the initiative score. \"\"\" def __init__(self): pass async def check_successes(self, target, rolls): \"\"\"", "if all items in the roll are a 1. rolls : list[int] ->", "exploding=True dice_pool: int exploding: Boolean -> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool=dice_pool, sides=6)", "success status and a list of int lists representing the rolls. dice_pool: int", "4 async def count_hits(self, rolls, prime=False): \"\"\" Counts the amount of hits, misses,", "True. Returns a dict with a boolean representing success status and a list", "roller for shadowrun 1E games. class methods: check_successes(target: int, rolls: list[int]) -> dict(successes:", "if any of the rolls are successes target : int roll : list[int]", "if x == 1] if len(ones) == len(rolls): return True return False async", "roll(dice_pool: int, exploding: Boolean) -> list[int]: A dice roller that handles basic dice", "type: str or None} \"\"\" glitch = False glitch_type = None ones =", "hit_limit: hits += 1 elif i > 1: misses += 1 else: ones", "{hits, misses, ones} Creates the amount of hits, misses, and ones in the", "if len(ones) == len(rolls): return True return False async def roll(self, dice_pool): \"\"\"", "rolling for a prime runner if prime: hit_limit = 4 hits, misses, ones", "running_total}} \"\"\" rolls = [] totals = [] success = False total_hits =", "total_hits, \"running_total\": totals}} async def is_glitch(self, rolls, hits): \"\"\" Checks whether or not", "dice according to shadowrun 1E rules. Does no checks for failures or successes.", "for all shadowrun 5E related rolling functions. Types of rolls that are completed", "counted[\"hits\"], \"roll\": roll}) dice_pool -= 1 if total_hits >= threshold: success = True", "roll is a failure is_failure(rolls: list[int]) -> bool Checks to see if the", "None} Checks whether or not a roll is a glitch. SR5E CORE pg.", "counting - Adding in additional dice with + - removing dice with -", "totals. roll_initiative(dice_pool: int, modifier: int) -> initiative: int Rolls initiative dice and adds", "rolls.extend(sixes) return rolls async def roll_initiative(self, dice_pool=1, modifier=1): \"\"\" Rolls initiative dice and", "in range(0, len(sixes))] rolls.extend(sixes) return rolls async def roll_initiative(self, dice_pool=1, modifier=1): \"\"\" Rolls", "the integers that exceeded the target and whether or not the roll is", "in rolls if x == 6] rolls = [x for x in rolls", "general # roller. initiative_roll = await rolling_utils.roll(dice_pool) for i in initiative_roll: modifier +=", "# Get the sixes and remove them from the original list. sixes =", "dice rolling. This allows for exploding 6's with exploding=True SR5E CORE pg. 44", "== len(rolls): return True return False async def roll(self, dice_pool): \"\"\" Rolls and", "if the roll is a failure, which is all 1's by shadowrun 1E", "Rounds down. dice_pool: int -> int \"\"\" return dice_pool // 4 async def", "int -> initiative: int \"\"\" initiative_roll = await self.roll(dice_pool) for i in initiative_roll:", "dictionary with the amount of successes and the integers that exceeded the target", "in the rolls. If the roll is designated for a prime runner, it", "Creates the amount of hits, misses, and ones in the rolls. If the", "removing dice with - class variables: roller (base_roll_functions.roller()): A roller class that handles", "threshold, prime=False, exploding=False): \"\"\" Runs an extended test with a dice pool to", "44 SR5E CORE pg. 56 (Edge effects) roll_initiative(dice_pool: int, modifier: int) -> initiative:", "\"\"\" A dice roller that handles basic dice rolling. This allows for exploding", "A dice roller that handles basic dice rolling. This allows for exploding 6's", "-> dict(successes: int, rolls: list[int], failure: bool) Checks how many integers in the", "\"\"\" rolls = await rolling_utils.roll(dice_pool=dice_pool, sides=6) if exploding: sixes = [x for x", "total_hits += counted[\"hits\"] totals.append(total_hits) rolls.append({\"hits\": counted[\"hits\"], \"roll\": roll}) dice_pool -= 1 if total_hits", "than running through all iterations if not needed. SR5E CORE pg. 48 is_glitch(rolls:", "hits: int -> dict{glitch: bool, type: str or None} \"\"\" glitch = False", "lowers the hit threshold by 1. SR5E CORE pg. 44 extended_test(dice_pool: int, threshold:", "is a failure is_failure(rolls: list[int]) -> bool Checks to see if the roll", "not apply to initiative. Therefore use the general # roller. initiative_roll = await", "running_total: list[int]}} Runs extended tests by shadowrun 5E rules. Stops as soon as", "{\"success\": success, \"rolls\": rolls, \"totals\": { \"total_hits\": total_hits, \"running_total\": totals}} async def is_glitch(self,", "and not hits: glitch = True glitch_type = \"critical\" elif len(ones) > (len(rolls)", "initiative for shadowrun 5E. dice_pool: int modifier: int -> initiative: int \"\"\" initiative_roll", "rolls, \"totals\": { \"total_hits\": total_hits, \"running_total\": totals}} async def is_glitch(self, rolls, hits): \"\"\"", "def check_successes(self, target, rolls): \"\"\" Checks the rolls to see if any of", "-> initiative: int \"\"\" initiative_roll = await self.roll(dice_pool) for i in initiative_roll: modifier", "await self.count_hits(roll) total_hits += counted[\"hits\"] totals.append(total_hits) rolls.append({\"hits\": counted[\"hits\"], \"roll\": roll}) dice_pool -= 1", "159 \"\"\" def __init__(self): pass async def buy_hits(self, dice_pool=0): \"\"\" \"buys\" hits at", "successes[\"failure\"] = True else: successes[\"failure\"] = False return successes async def is_failure(self, rolls):", "list of int lists representing the rolls. dice_pool: int threshold: int prime: bool", "= True glitch_type = \"normal\" return {\"glitch\": glitch, \"type\": glitch_type} async def roll(self,", "it is True. Returns a dict with a boolean representing success status and", "remove them from the original list. sixes = [x for x in rolls", "dice with - class variables: roller (base_roll_functions.roller()): A roller class that handles the", "rolls: list[int], totals {total_hits: int, running_total: list[int]}} Runs extended tests by shadowrun 5E", "successes. Returns a list of integers representing the totals. roll_initiative(dice_pool: int, modifier: int)", "dice according to shadowrun 1E rules. This does no checking for successes. dice_pool", "Boolean -> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool=dice_pool, sides=6) if exploding: sixes =", "for shadowrun 5E. SR5E CORE pg. 159 \"\"\" def __init__(self): pass async def", "utf-8 -*- \"\"\" This software is licensed under the License (MIT) located at", "License. \"\"\" from utils.rolling import rolling_utils class Shadowrun3Roller(): \"\"\" The shadowrun roller for", "shadowrun 1E rules. Does no checks for failures or successes. Returns a list", "rolls = await rolling_utils.roll(dice_pool) if 6 in rolls: # Get the sixes and", "int \"buys\" hits at a 1 hit : 4 dice ratio. Rounds down.", "CORE pg. 45 count_hits(rolls: list[int], prime: Boolean) -> {hits, misses, ones} Creates the", "i in rolls: if i >= hit_limit: hits += 1 elif i >", "False total_hits = 0 while dice_pool > 0: roll = await self.roll(dice_pool, exploding=exploding)", "= True glitch_type = \"critical\" elif len(ones) > (len(rolls) // 2) and hits:", "in additional dice with + - removing dice with - class variables: roller", "total_hits >= threshold: success = True break return {\"success\": success, \"rolls\": rolls, \"totals\":", "for x in rolls if x == 6] rolls.extend(await self.roll(len(sixes))) rolls.sort() return rolls", "\"\"\" ones = [x for x in rolls if x == 1] if", "int -> dict{glitch: bool, type: str or None} \"\"\" glitch = False glitch_type", "async def check_successes(self, target, rolls): \"\"\" Checks the rolls to see if any", "if x != 6] added = await self.roll(len(sixes)) sixes = [sixes[i] + added[i]", "hits if it is True. Returns a dict with a boolean representing success", "exploding=False): \"\"\" A dice roller that handles basic dice rolling. This allows for", "prime: boolean) -> {success: bool, rolls: list[int], totals {total_hits: int, running_total: list[int]}} Runs", "6] rolls.extend(await self.roll(len(sixes))) rolls.sort() return rolls rolls.sort() return rolls async def roll_initiative(self, dice_pool,", "len(ones) > (len(rolls) // 2) and hits: glitch = True glitch_type = \"normal\"", "Prime will lower the threshold when counting hits if it is True. Returns", "6] added = await self.roll(len(sixes)) sixes = [sixes[i] + added[i] for i in", "= 5 # Lower the hit threshold if rolling for a prime runner", "are completed inlcude general rolling and hit counting - Adding in additional dice", "-*- coding: utf-8 -*- \"\"\" This software is licensed under the License (MIT)", "is all 1's by shadowrun 1E rules. Returns True if the roll is", "the roll is a failure. roll(dice_pool: int) -> list[int] Rolls and counts the", "case if all items in the roll are a 1. rolls : list[int]", "CORE pg. 159 \"\"\" def __init__(self): pass async def buy_hits(self, dice_pool=0): \"\"\" \"buys\"", "is_glitch(self, rolls, hits): \"\"\" Checks whether or not a roll is a glitch.", "initiative: int Rolls initiative dice and adds in reaction to give the initiative", "extended tests by shadowrun 5E rules. Stops as soon as the test has", "async def roll_initiative(self, dice_pool, modifier=0): \"\"\" Rolls initiative for shadowrun 5E. dice_pool: int", "This is only the case if all items in the roll are a", "glitch. rolls: list[int] hits: int -> dict{glitch: bool, type: str or None} \"\"\"", "-= 1 if total_hits >= threshold: success = True break return {\"success\": success,", "rolls, prime=False): \"\"\" Counts the amount of hits, misses, and ones in a", "hit threshold if rolling for a prime runner if prime: hit_limit = 4", "True break return {\"success\": success, \"rolls\": rolls, \"totals\": { \"total_hits\": total_hits, \"running_total\": totals}}", "buy_hits(self, dice_pool=0): \"\"\" \"buys\" hits at a 1 hit : 4 dice ration.", "the totals. roll_initiative(dice_pool: int, modifier: int) -> initiative: int Rolls initiative dice and", "failure, which is all 1's by shadowrun 1E rules. Returns True if the", "checks for failures or successes. Returns a list of integers representing the totals.", "Types of rolls that are completed inlcude general rolling and hit counting -", "list of integers representing the totals. roll_initiative(dice_pool: int, modifier: int) -> initiative: int", "1] if len(ones) > (len(rolls) // 2) and not hits: glitch = True", "the roll is a failure is_failure(rolls: list[int]) -> bool Checks to see if", "\"\"\" This software is licensed under the License (MIT) located at https://github.com/ephreal/rollbot/Licence Please", "(len(rolls) // 2) and not hits: glitch = True glitch_type = \"critical\" elif", "exploding=True SR5E CORE pg. 44 SR5E CORE pg. 56 (Edge effects) roll_initiative(dice_pool: int,", "exploding 6's with exploding=True SR5E CORE pg. 44 SR5E CORE pg. 56 (Edge", "or rights granted to you by the License. \"\"\" from utils.rolling import rolling_utils", "roller that handles basic dice rolling. This allows for exploding 6's with exploding=True", "-> {hits, misses, ones} Creates the amount of hits, misses, and ones in", "the roll is a failure, which is all 1's by shadowrun 1E rules.", "True glitch_type = \"critical\" elif len(ones) > (len(rolls) // 2) and hits: glitch", "exploding: Boolean -> list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool=dice_pool, sides=6) if exploding: sixes", "list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool=dice_pool, sides=6) if exploding: sixes = [x for", "SR5E CORE pg. 56 (Edge effects) roll_initiative(dice_pool: int, modifier: int) -> initiative: int", "misses, ones = 0, 0, 0 for i in rolls: if i >=", "45-46 roll(dice_pool: int, exploding: Boolean) -> list[int]: A dice roller that handles basic", "initiative_roll = await self.roll(dice_pool) for i in initiative_roll: modifier += i return initiative_roll,", "-> list[int] Rolls and counts the dice according to shadowrun 1E rules. Does", "rolls: # Get the sixes and remove them from the original list. sixes", "exploding 6's with exploding=True dice_pool: int exploding: Boolean -> list[int] \"\"\" rolls =", "check_successes(target: int, rolls: list[int]) -> dict(successes: int, rolls: list[int], failure: bool) Checks how", "else: successes[\"failure\"] = False return successes async def is_failure(self, rolls): \"\"\" Checks to", "initiative: int \"\"\" initiative_roll = await self.roll(dice_pool) for i in initiative_roll: modifier +=", "in. dice_pool: int reaction: int -> int \"\"\" # Adding 6's does not", "list[int], prime: Boolean) -> {hits, misses, ones} Creates the amount of hits, misses,", "if the roll is a failure. This is only the case if all", "in the roll are a 1. rolls : list[int] -> bool \"\"\" ones", "Rolls initiative dice and adds reaction in. dice_pool: int reaction: int -> int", "for x in rolls if x != 6] added = await self.roll(len(sixes)) sixes", "or not a roll is a glitch. SR5E CORE pg. 45-46 roll(dice_pool: int,", "roll is a failure. roll(dice_pool: int) -> list[int] Rolls and counts the dice", "count_hits(self, rolls, prime=False): \"\"\" Counts the amount of hits, misses, and ones in", "license for any restrictions or rights granted to you by the License. \"\"\"", "+ - removing dice with - class variables: roller (base_roll_functions.roller()): A roller class", "reaction to give the initiative score. \"\"\" def __init__(self): pass async def check_successes(self,", "failure: Bool} \"\"\" rolls = [roll for roll in rolls if roll >=", "designated for a prime runner, it lowers the hit threshold by 1. SR5E", "dice_pool): \"\"\" Rolls and counts the dice according to shadowrun 1E rules. This", "hits: glitch = True glitch_type = \"normal\" return {\"glitch\": glitch, \"type\": glitch_type} async", "is a failure. This is only the case if all items in the", "\"\"\" rolls = await rolling_utils.roll(dice_pool) if 6 in rolls: # Get the sixes", "roll_initiative(dice_pool: int, modifier: int) -> initiative: int Rolls initiative for shadowrun 5E. SR5E", "roll : list[int] -> dict{successes: int, rolls[int], failure: Bool} \"\"\" rolls = [roll", "= await self.roll(len(sixes)) sixes = [sixes[i] + added[i] for i in range(0, len(sixes))]", "to initiative. Therefore use the general # roller. initiative_roll = await rolling_utils.roll(dice_pool) for", "prime=False, exploding=False): \"\"\" Runs an extended test with a dice pool to see", "target : int roll : list[int] -> dict{successes: int, rolls[int], failure: Bool} \"\"\"", "int roll : list[int] -> dict{successes: int, rolls[int], failure: Bool} \"\"\" rolls =", "with the amount of successes and the integers that exceeded the target and", "roll >= target] successes = {\"successes\": len(rolls), \"rolls\": rolls } if await self.is_failure(rolls):", "a prime runner if prime: hit_limit = 4 hits, misses, ones = 0,", "= [x for x in rolls if x == 6] rolls.extend(await self.roll(len(sixes))) rolls.sort()", "class methods: check_successes(target: int, rolls: list[int]) -> dict(successes: int, rolls: list[int], failure: bool)", "Rolls initiative for shadowrun 5E. dice_pool: int modifier: int -> initiative: int \"\"\"", "x in rolls if x == 6] rolls.extend(await self.roll(len(sixes))) rolls.sort() return rolls rolls.sort()", "a prime runner, it lowers the hit threshold by 1. SR5E CORE pg.", "class Shadowrun3Roller(): \"\"\" The shadowrun roller for shadowrun 1E games. class methods: check_successes(target:", "if prime: hit_limit = 4 hits, misses, ones = 0, 0, 0 for", "> 1: misses += 1 else: ones += 1 return {\"hits\": hits, \"misses\":", "counting hits if it is True. Returns a dict with a boolean representing", "has been completed rather than running through all iterations if not needed. SR5E", "# -*- coding: utf-8 -*- \"\"\" This software is licensed under the License", "Returns a dict with a boolean representing success status and a list of", "pg. 45 count_hits(rolls: list[int], prime: Boolean) -> {hits, misses, ones} Creates the amount", "sixes and remove them from the original list. sixes = [x for x", "counts the dice according to shadowrun 1E rules. Does no checks for failures", "that handles the actual dice rolling. class methods: buy_hits(dice_pool: int) -> hits: int", "rolls): \"\"\" Checks the rolls to see if any of the rolls are", "dice_pool // 4 async def count_hits(self, rolls, prime=False): \"\"\" Counts the amount of", "Does no checks for failures or successes. Returns a list of integers representing", "int -> int \"\"\" return dice_pool // 4 async def count_hits(self, rolls, prime=False):", "is designated for a prime runner, it lowers the hit threshold by 1.", "rolls. If the roll is designated for a prime runner, it lowers the", "added[i] for i in range(0, len(sixes))] rolls.extend(sixes) return rolls async def roll_initiative(self, dice_pool=1,", "threshold: success = True break return {\"success\": success, \"rolls\": rolls, \"totals\": { \"total_hits\":", "return True return False async def roll(self, dice_pool): \"\"\" Rolls and counts the", "threshold. Prime will lower the threshold when counting hits if it is True.", "roller. initiative_roll = await rolling_utils.roll(dice_pool) for i in initiative_roll: modifier += i return", "rolls, hits): \"\"\" Checks whether or not a roll is a glitch. rolls:", "hits, misses, and ones in a list of integers. rolls: list[int] -> {hits,", "\"\"\" \"buys\" hits at a 1 hit : 4 dice ration. Rounds down.", "a failure. roll(dice_pool: int) -> list[int] Rolls and counts the dice according to", "rolls : list[int] -> bool \"\"\" ones = [x for x in rolls", "the rolls to see if any of the rolls are successes target :", "the case if all items in the roll are a 1. rolls :", "dice_pool, exploding=False): \"\"\" A dice roller that handles basic dice rolling. This allows", "see if it is possible to reach a threshold. Prime will lower the", "reach a threshold. Prime will lower the threshold when counting hits if it", "def __init__(self): pass async def check_successes(self, target, rolls): \"\"\" Checks the rolls to", "any restrictions or rights granted to you by the License. \"\"\" from utils.rolling", "list exceed the target int. Returns a dictionary with the amount of successes", "roller (base_roll_functions.roller()): A roller class that handles the actual dice rolling. class methods:", "dice_pool=0): \"\"\" \"buys\" hits at a 1 hit : 4 dice ration. Rounds", "x in rolls if x != 6] added = await self.roll(len(sixes)) sixes =", "2) and hits: glitch = True glitch_type = \"normal\" return {\"glitch\": glitch, \"type\":", "the amount of successes and the integers that exceeded the target and whether", "the actual dice rolling. class methods: buy_hits(dice_pool: int) -> hits: int \"buys\" hits", "counted[\"hits\"] totals.append(total_hits) rolls.append({\"hits\": counted[\"hits\"], \"roll\": roll}) dice_pool -= 1 if total_hits >= threshold:", "-*- \"\"\" This software is licensed under the License (MIT) located at https://github.com/ephreal/rollbot/Licence", "if x == 6] rolls = [x for x in rolls if x", "prime: Boolean) -> {hits, misses, ones} Creates the amount of hits, misses, and", "list. sixes = [x for x in rolls if x == 6] rolls", "len(rolls), \"rolls\": rolls } if await self.is_failure(rolls): successes[\"failure\"] = True else: successes[\"failure\"] =", "amount of hits, misses, and ones in the rolls. If the roll is", "for i in range(0, len(sixes))] rolls.extend(sixes) return rolls async def roll_initiative(self, dice_pool=1, modifier=1):", "Adding in additional dice with + - removing dice with - class variables:", "a failure is_failure(rolls: list[int]) -> bool Checks to see if the roll is", "This does no checking for successes. dice_pool : int -> list[int] \"\"\" rolls", "rules. Stops as soon as the test has been completed rather than running", "\"critical\" elif len(ones) > (len(rolls) // 2) and hits: glitch = True glitch_type", "rolling_utils.roll(dice_pool=dice_pool, sides=6) if exploding: sixes = [x for x in rolls if x", "i in range(0, len(sixes))] rolls.extend(sixes) return rolls async def roll_initiative(self, dice_pool=1, modifier=1): \"\"\"", "effects) roll_initiative(dice_pool: int, modifier: int) -> initiative: int Rolls initiative for shadowrun 5E.", "pg. 159 \"\"\" def __init__(self): pass async def buy_hits(self, dice_pool=0): \"\"\" \"buys\" hits", "in rolls if x == 6] rolls.extend(await self.roll(len(sixes))) rolls.sort() return rolls rolls.sort() return", "import rolling_utils class Shadowrun3Roller(): \"\"\" The shadowrun roller for shadowrun 1E games. class", "int \"\"\" return dice_pool // 4 async def count_hits(self, rolls, prime=False): \"\"\" Counts", "list[int], failure: bool) Checks how many integers in the rolls list exceed the", "self.is_failure(rolls): successes[\"failure\"] = True else: successes[\"failure\"] = False return successes async def is_failure(self,", "dice ration. Rounds down. dice_pool: int -> int \"\"\" return dice_pool // 4", "int, modifier: int) -> initiative: int Rolls initiative dice and adds in reaction", "of integers representing the totals. roll_initiative(dice_pool: int, modifier: int) -> initiative: int Rolls", "if it is possible to reach a threshold. Prime will lower the threshold", "2) and not hits: glitch = True glitch_type = \"critical\" elif len(ones) >", "i > 1: misses += 1 else: ones += 1 return {\"hits\": hits,", "return rolls async def roll_initiative(self, dice_pool=1, modifier=1): \"\"\" Rolls initiative dice and adds", "the target and whether or not the roll is a failure is_failure(rolls: list[int])", "and hit counting - Adding in additional dice with + - removing dice", "list[int] \"\"\" rolls = await rolling_utils.roll(dice_pool) if 6 in rolls: # Get the", "def count_hits(self, rolls, prime=False): \"\"\" Counts the amount of hits, misses, and ones", "prime: bool exploding: bool -> {success, rolls, totals {total_hits, running_total}} \"\"\" rolls =", "rolls to see if any of the rolls are successes target : int", "completed inlcude general rolling and hit counting - Adding in additional dice with", "True return False async def roll(self, dice_pool): \"\"\" Rolls and counts the dice", "// 4 async def count_hits(self, rolls, prime=False): \"\"\" Counts the amount of hits,", "prime runner if prime: hit_limit = 4 hits, misses, ones = 0, 0,", "dict with a boolean representing success status and a list of int lists", "= False total_hits = 0 while dice_pool > 0: roll = await self.roll(dice_pool,", "in rolls if x == 1] if len(ones) > (len(rolls) // 2) and", "the target int. Returns a dictionary with the amount of successes and the", "i >= hit_limit: hits += 1 elif i > 1: misses += 1", "rolls rolls.sort() return rolls async def roll_initiative(self, dice_pool, modifier=0): \"\"\" Rolls initiative for", "= [] totals = [] success = False total_hits = 0 while dice_pool", "a list of int lists representing the rolls. dice_pool: int threshold: int prime:", "pg. 44 SR5E CORE pg. 56 (Edge effects) roll_initiative(dice_pool: int, modifier: int) ->", "-> int \"\"\" return dice_pool // 4 async def count_hits(self, rolls, prime=False): \"\"\"", "int \"\"\" # Adding 6's does not apply to initiative. Therefore use the", "1. rolls : list[int] -> bool \"\"\" ones = [x for x in", "sixes = [x for x in rolls if x == 6] rolls =", "rolls = await rolling_utils.roll(dice_pool=dice_pool, sides=6) if exploding: sixes = [x for x in", "self.roll(dice_pool, exploding=exploding) if prime: counted = await self.count_hits(roll, prime=True) else: counted = await", "is my handler for all shadowrun 5E related rolling functions. Types of rolls", "rights granted to you by the License. \"\"\" from utils.rolling import rolling_utils class", "-> list[int]: A dice roller that handles basic dice rolling. This allows for", "modifier: int) -> initiative: int Rolls initiative for shadowrun 5E. SR5E CORE pg.", "SR5E CORE pg. 159 \"\"\" def __init__(self): pass async def buy_hits(self, dice_pool=0): \"\"\"", "is_failure(rolls: list[int]) -> bool Checks to see if the roll is a failure,", "int \"\"\" initiative_roll = await self.roll(dice_pool) for i in initiative_roll: modifier += i", "integers that exceeded the target and whether or not the roll is a", "6 in rolls: # Get the sixes and remove them from the original", "Checks the rolls to see if any of the rolls are successes target", "CORE pg. 48 is_glitch(rolls: list[int], hits: int) -> {glitch: bool, type: str or", "sixes = [sixes[i] + added[i] for i in range(0, len(sixes))] rolls.extend(sixes) return rolls", "the License. \"\"\" from utils.rolling import rolling_utils class Shadowrun3Roller(): \"\"\" The shadowrun roller", "rolls: if i >= hit_limit: hits += 1 elif i > 1: misses", "the general # roller. initiative_roll = await rolling_utils.roll(dice_pool) for i in initiative_roll: modifier", "initiative_roll: modifier += i return initiative_roll, modifier class Shadowrun5Roller(): \"\"\" TODO: Add in", "def extended_test(self, dice_pool, threshold, prime=False, exploding=False): \"\"\" Runs an extended test with a", "for x in rolls if x == 1] if len(ones) == len(rolls): return", "\"\"\" from utils.rolling import rolling_utils class Shadowrun3Roller(): \"\"\" The shadowrun roller for shadowrun", "glitch, \"type\": glitch_type} async def roll(self, dice_pool, exploding=False): \"\"\" A dice roller that", "\"\"\" Counts the amount of hits, misses, and ones in a list of", "total_hits = 0 while dice_pool > 0: roll = await self.roll(dice_pool, exploding=exploding) if", "rolls: list[int] hits: int -> dict{glitch: bool, type: str or None} \"\"\" glitch", "of rolls that are completed inlcude general rolling and hit counting - Adding", "the rolls are successes target : int roll : list[int] -> dict{successes: int,", "rather than running through all iterations if not needed. SR5E CORE pg. 48", "integers. rolls: list[int] -> {hits, misses, ones} \"\"\" hit_limit = 5 # Lower", "= \"normal\" return {\"glitch\": glitch, \"type\": glitch_type} async def roll(self, dice_pool, exploding=False): \"\"\"", "dice_pool, threshold, prime=False, exploding=False): \"\"\" Runs an extended test with a dice pool", "The shadowrun roller for shadowrun 1E games. class methods: check_successes(target: int, rolls: list[int])", "int, rolls[int], failure: Bool} \"\"\" rolls = [roll for roll in rolls if", "ones = [x for x in rolls if x == 1] if len(ones)", "dice roller that handles basic dice rolling. This allows for exploding 6's with", "is a failure, which is all 1's by shadowrun 1E rules. Returns True", "} if await self.is_failure(rolls): successes[\"failure\"] = True else: successes[\"failure\"] = False return successes" ]
[ "os import sys if __name__ == \"__main__\": sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from Emulator.emulator import main", "import os import sys if __name__ == \"__main__\": sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from Emulator.emulator import", "#!/usr/bin/env python3 import os import sys if __name__ == \"__main__\": sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from", "<gh_stars>0 #!/usr/bin/env python3 import os import sys if __name__ == \"__main__\": sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))", "python3 import os import sys if __name__ == \"__main__\": sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from Emulator.emulator", "import sys if __name__ == \"__main__\": sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from Emulator.emulator import main main()" ]
[ "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,", "e.findall(SMDX_POINT): pid = p.attrib.get(SMDX_ATTR_ID) label = desc = notes = None for a", "{SMDX_MANDATORY_FALSE: mdef.MANDATORY_FALSE, SMDX_MANDATORY_TRUE: mdef.MANDATORY_TRUE} smdx_type_types = [ SMDX_TYPE_INT16, SMDX_TYPE_UINT16, SMDX_TYPE_COUNT, SMDX_TYPE_ACC16, SMDX_TYPE_ENUM16, SMDX_TYPE_BITFIELD16,", "= [repeating_def] e = element.find(SMDX_STRINGS) if e.attrib.get(SMDX_ATTR_ID) == str(mid): m = e.find(SMDX_MODEL) if", "SMDX_ACCESS_R) if access not in smdx_access_types: raise mdef.ModelDefinitionError('Unknown access type: %s' % access)", "this software and associated documentation files (the \"Software\"), to deal in the Software", "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16}, {mdef.NAME: 'L', mdef.DESCRIPTION: 'Model length', mdef.LABEL:", "element.attrib.get(SMDX_ATTR_MANDATORY, SMDX_MANDATORY_FALSE) if mandatory not in smdx_mandatory_types: raise mdef.ModelDefinitionError('Unknown mandatory type: %s' %", "if no 'name' is defined 'name' = 'repeating' points: all type, access, and", "object 'name' symbol element content -> symbol object 'value' strings 'label', 'description', 'notes'", "mapping: fixed block -> top level group model 'name' attribute -> group 'name'", "the Software without restriction, including without limitation the rights to use, copy, modify,", "the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies", "attributes based on an element tree model type element contained in an SMDX", "raise mdef.ModelDefinitionError('Duplicate repeating block type definition') repeating = b else: raise mdef.ModelDefinitionError('Invalid block", "without restriction, including without limitation the rights to use, copy, modify, merge, publish,", "for e in fixed.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not in fixed_points_map: fixed_points_map[point_def[mdef.NAME]]", "= {} if repeating is not None: name = repeating.attrib.get(SMDX_ATTR_NAME) if name is", "convert to correct type value = mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE)) if value is not None: point_def[mdef.VALUE]", "elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else:", "if symbols: point_def[mdef.SYMBOLS] = symbols return point_def def indent(elem, level=0): i = os.linesep", "in m.findall(SMDX_BLOCK): btype = b.attrib.get(SMDX_ATTR_TYPE, SMDX_ATTR_TYPE_FIXED) if btype == SMDX_ATTR_TYPE_FIXED: if fixed is", "sublicense, and/or sell copies of the Software, and to permit persons to whom", "attributes based on an element tree point element contained in an SMDX model", "value}) if symbols: point_def[mdef.SYMBOLS] = symbols return point_def def indent(elem, level=0): i =", "model len shoud be used to determine number of groups) repeating block 'name'", "notice and this permission notice shall be included in all copies or substantial", "\"\"\" Sets the point attributes based on an element tree point element contained", "units: point_def[mdef.UNITS] = units # if scale factor is an number, convert to", "def to_smdx_filename(model_id): return '%s%05d%s' % (SMDX_PREFIX, int(model_id), SMDX_EXT) def model_filename_to_id(filename): f = filename", "'r' SMDX_ACCESS_RW = 'rw' SMDX_MANDATORY_FALSE = 'false' SMDX_MANDATORY_TRUE = 'true' smdx_access_types = {SMDX_ACCESS_R:", "pid ptype = element.attrib.get(SMDX_ATTR_TYPE) if ptype is None: raise mdef.ModelDefinitionError('Missing type attribute for", "preserved point symbol map to the symbol object and placed in the symbols", "mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16}, {mdef.NAME: 'L', mdef.DESCRIPTION: 'Model length', mdef.LABEL: 'Model Length',", "point_def[mdef.NAME] = pid ptype = element.attrib.get(SMDX_ATTR_TYPE) if ptype is None: raise mdef.ModelDefinitionError('Missing type", "= 'description' SMDX_NOTES = 'notes' SMDX_DETAIL = mdef.DETAIL SMDX_TYPE_INT16 = mdef.TYPE_INT16 SMDX_TYPE_UINT16 =", "point is created for model ID and 'value' is the model ID value", "fixed_points_map: fixed_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME])", "'fixed' SMDX_ATTR_TYPE_REPEATING = 'repeating' SMDX_ATTR_OFFSET = 'offset' SMDX_ATTR_MANDATORY = mdef.MANDATORY SMDX_ATTR_ACCESS = mdef.ACCESS", "'detail' ''' def from_smdx_file(filename): tree = ET.parse(filename) root = tree.getroot() return(from_smdx(root)) def from_smdx(element):", "SMDX_PREFIX = 'smdx_' SMDX_EXT = '.xml' def to_smdx_filename(model_id): return '%s%05d%s' % (SMDX_PREFIX, int(model_id),", "%s' % btype) fixed_points_map = {} if fixed is not None: points =", "to deal in the Software without restriction, including without limitation the rights to", "if sf is not None: point_def[mdef.SF] = sf # if scale factor is", "mdef.MODEL SMDX_BLOCK = 'block' SMDX_POINT = 'point' SMDX_ATTR_VERS = 'v' SMDX_ATTR_ID = 'id'", "repeating = None for b in m.findall(SMDX_BLOCK): btype = b.attrib.get(SMDX_ATTR_TYPE, SMDX_ATTR_TYPE_FIXED) if btype", "points: fixed_def[mdef.POINTS].extend(points) repeating_points_map = {} if repeating is not None: name = repeating.attrib.get(SMDX_ATTR_NAME)", "Software without restriction, including without limitation the rights to use, copy, modify, merge,", "a.text: fixed_def[mdef.LABEL] = a.text elif a.tag == SMDX_DESCRIPTION and a.text: fixed_def[mdef.DESCRIPTION] = a.text", "[ {mdef.NAME: 'ID', mdef.VALUE: mid, mdef.DESCRIPTION: 'Model identifier', mdef.LABEL: 'Model ID', mdef.SIZE: 1,", "SMDX_TYPE_ACC32, SMDX_TYPE_ENUM32, SMDX_TYPE_BITFIELD32, SMDX_TYPE_IPADDR, SMDX_TYPE_INT64, SMDX_TYPE_UINT64, SMDX_TYPE_ACC64, SMDX_TYPE_IPV6ADDR, SMDX_TYPE_FLOAT32, SMDX_TYPE_STRING, SMDX_TYPE_SUNSSF, SMDX_TYPE_EUI48 ]", "= b elif btype == SMDX_ATTR_TYPE_REPEATING: if repeating is not None: raise mdef.ModelDefinitionError('Duplicate", "mandatory == SMDX_MANDATORY_TRUE: point_def[mdef.MANDATORY] = smdx_mandatory_types.get(mandatory) access = element.attrib.get(SMDX_ATTR_ACCESS, SMDX_ACCESS_R) if access not", "a.text elif a.tag == SMDX_DESCRIPTION and a.text: fixed_def[mdef.DESCRIPTION] = a.text elif a.tag ==", "desc if notes: point_def[mdef.DETAIL] = notes point_def = repeating_points_map.get(pid) if point_def is not", "desc = a.text elif a.tag == SMDX_NOTES and a.text: notes = a.text point_def", "int(f.rsplit('_', 1)[1]) except ValueError: raise mdef.ModelDefinitionError('Error extracting model id from filename') return mid", "def model_filename_to_id(filename): f = filename if '.' in f: f = os.path.splitext(f)[0] try:", "if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and", "m = e.find(SMDX_MODEL) if m is not None: for a in m.findall('*'): if", "Length', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16} ] } repeating_def =", "ValueError: raise mdef.ModelDefinitionError('Error extracting model id from filename') return mid ''' smdx to", "except ValueError: pass symbols.append({mdef.NAME: sid, mdef.VALUE: value}) if symbols: point_def[mdef.SYMBOLS] = symbols return", "type: %s' % access) if access == SMDX_ACCESS_RW: point_def[mdef.ACCESS] = smdx_access_types.get(access) units =", "not in smdx_mandatory_types: raise mdef.ModelDefinitionError('Unknown mandatory type: %s' % mandatory) if mandatory ==", "def from_smdx_file(filename): tree = ET.parse(filename) root = tree.getroot() return(from_smdx(root)) def from_smdx(element): \"\"\" Sets", "or not elem.text.strip(): elem.text = i + \" \" if not elem.tail or", "free of charge, to any person obtaining a copy of this software and", "and this permission notice shall be included in all copies or substantial portions", "name = m.attrib.get(SMDX_ATTR_NAME) if name is None: name = 'model_' + str(mid) model_def[mdef.NAME]", "None: point_def[mdef.VALUE] = value symbols = [] for e in element.findall('*'): if e.tag", "'repeating' repeating_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.COUNT: 0} points = [] for", "p.attrib.get(SMDX_ATTR_ID) label = desc = notes = None for a in p.findall('*'): if", "rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of", "symbol element content -> symbol object 'value' strings 'label', 'description', 'notes' elements map", "fixed.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not in fixed_points_map: fixed_points_map[point_def[mdef.NAME]] = point_def points.append(point_def)", "{mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.POINTS: [ {mdef.NAME: 'ID', mdef.VALUE: mid, mdef.DESCRIPTION: 'Model identifier',", "in the symbols list for the point symbol 'name' attribute -> symbol object", "EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "mdef.ModelDefinitionError('Model definition not found') try: mid = mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID)) except ValueError: raise mdef.ModelDefinitionError('Invalid model", "= plen else: point_def[mdef.SIZE] = mdef.point_type_info.get(ptype)['len'] mandatory = element.attrib.get(SMDX_ATTR_MANDATORY, SMDX_MANDATORY_FALSE) if mandatory not", "symbols return point_def def indent(elem, level=0): i = os.linesep + level*\" \" if", "SMDX_ATTR_TYPE_FIXED) if btype == SMDX_ATTR_TYPE_FIXED: if fixed is not None: raise mdef.ModelDefinitionError('Duplicate fixed", "elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or", "= mdef.TYPE_ACC32 SMDX_TYPE_ENUM32 = mdef.TYPE_ENUM32 SMDX_TYPE_BITFIELD32 = mdef.TYPE_BITFIELD32 SMDX_TYPE_IPADDR = mdef.TYPE_IPADDR SMDX_TYPE_INT64 =", "if desc: point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL] = notes model_def = {'id':", "model id from filename') return mid ''' smdx to json mapping: fixed block", "'locale' SMDX_LABEL = mdef.LABEL SMDX_DESCRIPTION = 'description' SMDX_NOTES = 'notes' SMDX_DETAIL = mdef.DETAIL", "point_def is not None: if label: point_def[mdef.LABEL] = label if desc: point_def[mdef.DESCRIPTION] =", "notice shall be included in all copies or substantial portions of the Software.", "SMDX_TYPE_ACC16 = mdef.TYPE_ACC16 SMDX_TYPE_ENUM16 = mdef.TYPE_ENUM16 SMDX_TYPE_BITFIELD16 = mdef.TYPE_BITFIELD16 SMDX_TYPE_PAD = mdef.TYPE_PAD SMDX_TYPE_INT32", "[] for e in element.findall('*'): if e.tag == SMDX_SYMBOL: sid = e.attrib.get(SMDX_ATTR_ID) value", "as ET import sunspec2.mdef as mdef SMDX_ROOT = 'sunSpecModels' SMDX_MODEL = mdef.MODEL SMDX_BLOCK", "= [] for e in element.findall('*'): if e.tag == SMDX_SYMBOL: sid = e.attrib.get(SMDX_ATTR_ID)", "SMDX_TYPE_STRING: if plen is None: raise mdef.ModelDefinitionError('Missing len attribute for point: %s' %", "is None: raise mdef.ModelDefinitionError('Model definition not found') try: mid = mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID)) except ValueError:", "elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail", "fixed_points_map = {} if fixed is not None: points = [] for e", "model len - model len has no value specified in the model definition", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION", "SMDX_DESCRIPTION and a.text: fixed_def[mdef.DESCRIPTION] = a.text elif a.tag == SMDX_NOTES and a.text: fixed_def[mdef.DETAIL]", "id: %s' % m.attrib.get(SMDX_ATTR_ID)) name = m.attrib.get(SMDX_ATTR_NAME) if name is None: name =", "if ptype is None: raise mdef.ModelDefinitionError('Missing type attribute for point: %s' % pid)", "'false' SMDX_MANDATORY_TRUE = 'true' smdx_access_types = {SMDX_ACCESS_R: mdef.ACCESS_R, SMDX_ACCESS_RW: mdef.ACCESS_RW} smdx_mandatory_types = {SMDX_MANDATORY_FALSE:", "= element.find(SMDX_STRINGS) # create top level group with ID and L points fixed_def", "not found') try: mid = mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID)) except ValueError: raise mdef.ModelDefinitionError('Invalid model id: %s'", "point_def = from_smdx_point(e) if point_def[mdef.NAME] not in repeating_points_map: repeating_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else:", "== SMDX_ACCESS_RW: point_def[mdef.ACCESS] = smdx_access_types.get(access) units = element.attrib.get(SMDX_ATTR_UNITS) if units: point_def[mdef.UNITS] = units", "contained in an SMDX model definition. Parameters: element : Element Tree point type", "elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1)", "mdef.ModelDefinitionError('Invalid block type: %s' % btype) fixed_points_map = {} if fixed is not", "OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "SMDX_ATTR_NAME = mdef.NAME SMDX_ATTR_TYPE = mdef.TYPE SMDX_ATTR_COUNT = mdef.COUNT SMDX_ATTR_VALUE = mdef.VALUE SMDX_ATTR_TYPE_FIXED", "publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons", "= None for b in m.findall(SMDX_BLOCK): btype = b.attrib.get(SMDX_ATTR_TYPE, SMDX_ATTR_TYPE_FIXED) if btype ==", "for b in m.findall(SMDX_BLOCK): btype = b.attrib.get(SMDX_ATTR_TYPE, SMDX_ATTR_TYPE_FIXED) if btype == SMDX_ATTR_TYPE_FIXED: if", "value = mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE)) if value is not None: point_def[mdef.VALUE] = value symbols =", "point_def = repeating_points_map.get(pid) if point_def is not None: if label: point_def[mdef.LABEL] = label", "== SMDX_ATTR_TYPE_REPEATING: if repeating is not None: raise mdef.ModelDefinitionError('Duplicate repeating block type definition')", "'L', mdef.DESCRIPTION: 'Model length', mdef.LABEL: 'Model Length', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE,", "= element.attrib.get(SMDX_ATTR_TYPE) if ptype is None: raise mdef.ModelDefinitionError('Missing type attribute for point: %s'", "'desc', 'detail' ''' def from_smdx_file(filename): tree = ET.parse(filename) root = tree.getroot() return(from_smdx(root)) def", "Sets the model type attributes based on an element tree model type element", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import", "mdef.TYPE_UINT64 SMDX_TYPE_ACC64 = mdef.TYPE_ACC64 SMDX_TYPE_IPV6ADDR = mdef.TYPE_IPV6ADDR SMDX_TYPE_FLOAT32 = mdef.TYPE_FLOAT32 SMDX_TYPE_STRING = mdef.TYPE_STRING", "point_def def indent(elem, level=0): i = os.linesep + level*\" \" if len(elem): if", "if e.attrib.get(SMDX_ATTR_ID) == str(mid): m = e.find(SMDX_MODEL) if m is not None: for", "a.tag == SMDX_LABEL and a.text: label = a.text elif a.tag == SMDX_DESCRIPTION and", "element : Element Tree point type element. strings : Indicates if *element* is", "not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not", "SMDX_ATTR_VERS = 'v' SMDX_ATTR_ID = 'id' SMDX_ATTR_LEN = 'len' SMDX_ATTR_NAME = mdef.NAME SMDX_ATTR_TYPE", "is not None: raise mdef.ModelDefinitionError('Duplicate fixed block type definition') fixed = b elif", "tree = ET.parse(filename) root = tree.getroot() return(from_smdx(root)) def from_smdx(element): \"\"\" Sets the model", "raise mdef.ModelDefinitionError('Missing type attribute for point: %s' % pid) elif ptype not in", "point_def = fixed_points_map.get(pid) if point_def is not None: if label: point_def[mdef.LABEL] = label", "b else: raise mdef.ModelDefinitionError('Invalid block type: %s' % btype) fixed_points_map = {} if", "{} m = element.find(SMDX_MODEL) if m is None: raise mdef.ModelDefinitionError('Model definition not found')", "= mdef.TYPE_STRING SMDX_TYPE_SUNSSF = mdef.TYPE_SUNSSF SMDX_TYPE_EUI48 = mdef.TYPE_EUI48 SMDX_ACCESS_R = 'r' SMDX_ACCESS_RW =", "= mdef.TYPE_ENUM32 SMDX_TYPE_BITFIELD32 = mdef.TYPE_BITFIELD32 SMDX_TYPE_IPADDR = mdef.TYPE_IPADDR SMDX_TYPE_INT64 = mdef.TYPE_INT64 SMDX_TYPE_UINT64 =", "elif a.tag == SMDX_NOTES and a.text: notes = a.text point_def = fixed_points_map.get(pid) if", "not None: point_def[mdef.SF] = sf # if scale factor is an number, convert", "SMDX_COMMENT = 'comment' SMDX_STRINGS = 'strings' SMDX_ATTR_LOCALE = 'locale' SMDX_LABEL = mdef.LABEL SMDX_DESCRIPTION", "above copyright notice and this permission notice shall be included in all copies", "= from_smdx_point(e) if point_def[mdef.NAME] not in repeating_points_map: repeating_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise", "mdef.ModelDefinitionError('Unknown access type: %s' % access) if access == SMDX_ACCESS_RW: point_def[mdef.ACCESS] = smdx_access_types.get(access)", "raise mdef.ModelDefinitionError('Error extracting model id from filename') return mid ''' smdx to json", "point definition: %s' % point_def[mdef.NAME]) if points: fixed_def[mdef.POINTS].extend(points) repeating_points_map = {} if repeating", "SMDX_ATTR_UNITS = mdef.UNITS SMDX_SYMBOL = 'symbol' SMDX_COMMENT = 'comment' SMDX_STRINGS = 'strings' SMDX_ATTR_LOCALE", "mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16}, {mdef.NAME: 'L', mdef.DESCRIPTION: 'Model length', mdef.LABEL: 'Model Length', mdef.SIZE: 1,", "mdef.COUNT: 0} points = [] for e in repeating.findall(SMDX_POINT): point_def = from_smdx_point(e) if", "'ID', mdef.VALUE: mid, mdef.DESCRIPTION: 'Model identifier', mdef.LABEL: 'Model ID', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE,", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS", "if desc: point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL] = notes point_def = repeating_points_map.get(pid)", "'value' strings 'label', 'description', 'notes' elements map to point attributes 'label', 'desc', 'detail'", "desc = notes = None for a in p.findall('*'): if a.tag == SMDX_LABEL", "m.findall('*'): if a.tag == SMDX_LABEL and a.text: fixed_def[mdef.LABEL] = a.text elif a.tag ==", "elif a.tag == SMDX_DESCRIPTION and a.text: fixed_def[mdef.DESCRIPTION] = a.text elif a.tag == SMDX_NOTES", "SMDX_TYPE_INT32 = mdef.TYPE_INT32 SMDX_TYPE_UINT32 = mdef.TYPE_UINT32 SMDX_TYPE_ACC32 = mdef.TYPE_ACC32 SMDX_TYPE_ENUM32 = mdef.TYPE_ENUM32 SMDX_TYPE_BITFIELD32", "= mdef.TYPE_FLOAT32 SMDX_TYPE_STRING = mdef.TYPE_STRING SMDX_TYPE_SUNSSF = mdef.TYPE_SUNSSF SMDX_TYPE_EUI48 = mdef.TYPE_EUI48 SMDX_ACCESS_R =", "model len has no value specified in the model definition fixed block points", "Tree point type element. strings : Indicates if *element* is a subelement of", "furnished to do so, subject to the following conditions: The above copyright notice", "point_def[mdef.LABEL] = label if desc: point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL] = notes", "\" if len(elem): if not elem.text or not elem.text.strip(): elem.text = i +", "= element.attrib.get(SMDX_ATTR_MANDATORY, SMDX_MANDATORY_FALSE) if mandatory not in smdx_mandatory_types: raise mdef.ModelDefinitionError('Unknown mandatory type: %s'", "not None: point_def[mdef.VALUE] = value symbols = [] for e in element.findall('*'): if", "the model ID value as a number L point is created for model", "symbol map to the symbol object and placed in the symbols list for", "permit persons to whom the Software is furnished to do so, subject to", "= 'locale' SMDX_LABEL = mdef.LABEL SMDX_DESCRIPTION = 'description' SMDX_NOTES = 'notes' SMDX_DETAIL =", "as a number L point is created for model len - model len", "f: f = os.path.splitext(f)[0] try: mid = int(f.rsplit('_', 1)[1]) except ValueError: raise mdef.ModelDefinitionError('Error", "mdef.MANDATORY SMDX_ATTR_ACCESS = mdef.ACCESS SMDX_ATTR_SF = mdef.SF SMDX_ATTR_UNITS = mdef.UNITS SMDX_SYMBOL = 'symbol'", "= 'strings' SMDX_ATTR_LOCALE = 'locale' SMDX_LABEL = mdef.LABEL SMDX_DESCRIPTION = 'description' SMDX_NOTES =", "'len' SMDX_ATTR_NAME = mdef.NAME SMDX_ATTR_TYPE = mdef.TYPE SMDX_ATTR_COUNT = mdef.COUNT SMDX_ATTR_VALUE = mdef.VALUE", "= 0 (indicates model len shoud be used to determine number of groups)", "copies of the Software, and to permit persons to whom the Software is", "name = 'repeating' repeating_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.COUNT: 0} points =", "not None: if label: point_def[mdef.LABEL] = label if desc: point_def[mdef.DESCRIPTION] = desc if", "\" if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in", "p in e.findall(SMDX_POINT): pid = p.attrib.get(SMDX_ATTR_ID) label = desc = notes = None", "= smdx_mandatory_types.get(mandatory) access = element.attrib.get(SMDX_ATTR_ACCESS, SMDX_ACCESS_R) if access not in smdx_access_types: raise mdef.ModelDefinitionError('Unknown", "\"\"\" point_def = {} pid = element.attrib.get(SMDX_ATTR_ID) if pid is None: raise mdef.ModelDefinitionError('Missing", "mdef.VALUE SMDX_ATTR_TYPE_FIXED = 'fixed' SMDX_ATTR_TYPE_REPEATING = 'repeating' SMDX_ATTR_OFFSET = 'offset' SMDX_ATTR_MANDATORY = mdef.MANDATORY", "if units: point_def[mdef.UNITS] = units # if scale factor is an number, convert", "mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16}, {mdef.NAME: 'L', mdef.DESCRIPTION: 'Model length',", "= desc if notes: point_def[mdef.DETAIL] = notes model_def = {'id': mid, 'group': fixed_def}", "m.findall(SMDX_BLOCK): btype = b.attrib.get(SMDX_ATTR_TYPE, SMDX_ATTR_TYPE_FIXED) if btype == SMDX_ATTR_TYPE_FIXED: if fixed is not", "-> group 'name', if no 'name' is defined 'name' = 'repeating' points: all", "else: point_def[mdef.SIZE] = mdef.point_type_info.get(ptype)['len'] mandatory = element.attrib.get(SMDX_ATTR_MANDATORY, SMDX_MANDATORY_FALSE) if mandatory not in smdx_mandatory_types:", "top level group with ID and L points fixed_def = {mdef.NAME: name, mdef.TYPE:", "= notes point_def = repeating_points_map.get(pid) if point_def is not None: if label: point_def[mdef.LABEL]", "points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if points: repeating_def[mdef.POINTS] =", "to correct type sf = mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF)) if sf is not None: point_def[mdef.SF] =", "'Model Length', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16} ] } repeating_def", "mandatory) if mandatory == SMDX_MANDATORY_TRUE: point_def[mdef.MANDATORY] = smdx_mandatory_types.get(mandatory) access = element.attrib.get(SMDX_ATTR_ACCESS, SMDX_ACCESS_R) if", "= {'id': mid, 'group': fixed_def} return model_def def from_smdx_point(element): \"\"\" Sets the point", "e = element.find(SMDX_STRINGS) if e.attrib.get(SMDX_ATTR_ID) == str(mid): m = e.find(SMDX_MODEL) if m is", "%s' % point_def[mdef.NAME]) if points: repeating_def[mdef.POINTS] = points fixed_def[mdef.GROUPS] = [repeating_def] e =", "symbols list for the point symbol 'name' attribute -> symbol object 'name' symbol", "SMDX_NOTES = 'notes' SMDX_DETAIL = mdef.DETAIL SMDX_TYPE_INT16 = mdef.TYPE_INT16 SMDX_TYPE_UINT16 = mdef.TYPE_UINT16 SMDX_TYPE_COUNT", "'name', if no 'name' is defined 'name' = 'repeating' points: all type, access,", "are preserved point symbol map to the symbol object and placed in the", "ET.parse(filename) root = tree.getroot() return(from_smdx(root)) def from_smdx(element): \"\"\" Sets the model type attributes", "SMDX_LABEL and a.text: fixed_def[mdef.LABEL] = a.text elif a.tag == SMDX_DESCRIPTION and a.text: fixed_def[mdef.DESCRIPTION]", "of this software and associated documentation files (the \"Software\"), to deal in the", "if value is not None: point_def[mdef.VALUE] = value symbols = [] for e", "repeating_def[mdef.POINTS] = points fixed_def[mdef.GROUPS] = [repeating_def] e = element.find(SMDX_STRINGS) if e.attrib.get(SMDX_ATTR_ID) == str(mid):", "SMDX_TYPE_UINT64, SMDX_TYPE_ACC64, SMDX_TYPE_IPV6ADDR, SMDX_TYPE_FLOAT32, SMDX_TYPE_STRING, SMDX_TYPE_SUNSSF, SMDX_TYPE_EUI48 ] SMDX_PREFIX = 'smdx_' SMDX_EXT =", "point is created for model len - model len has no value specified", "% point_def[mdef.NAME]) if points: fixed_def[mdef.POINTS].extend(points) repeating_points_map = {} if repeating is not None:", "if name is None: name = 'repeating' repeating_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP,", "sell copies of the Software, and to permit persons to whom the Software", "Alliance Permission is hereby granted, free of charge, to any person obtaining a", "point_def = from_smdx_point(e) if point_def[mdef.NAME] not in fixed_points_map: fixed_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else:", "model definition. \"\"\" point_def = {} pid = element.attrib.get(SMDX_ATTR_ID) if pid is None:", "= element.attrib.get(SMDX_ATTR_UNITS) if units: point_def[mdef.UNITS] = units # if scale factor is an", "'value' is the model ID value as a number L point is created", "[] for e in repeating.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not in repeating_points_map:", "point_def[mdef.SIZE] = plen else: point_def[mdef.SIZE] = mdef.point_type_info.get(ptype)['len'] mandatory = element.attrib.get(SMDX_ATTR_MANDATORY, SMDX_MANDATORY_FALSE) if mandatory", "SMDX_TYPE_INT16, SMDX_TYPE_UINT16, SMDX_TYPE_COUNT, SMDX_TYPE_ACC16, SMDX_TYPE_ENUM16, SMDX_TYPE_BITFIELD16, SMDX_TYPE_PAD, SMDX_TYPE_INT32, SMDX_TYPE_UINT32, SMDX_TYPE_ACC32, SMDX_TYPE_ENUM32, SMDX_TYPE_BITFIELD32, SMDX_TYPE_IPADDR,", "SMDX_MANDATORY_TRUE: mdef.MANDATORY_TRUE} smdx_type_types = [ SMDX_TYPE_INT16, SMDX_TYPE_UINT16, SMDX_TYPE_COUNT, SMDX_TYPE_ACC16, SMDX_TYPE_ENUM16, SMDX_TYPE_BITFIELD16, SMDX_TYPE_PAD, SMDX_TYPE_INT32,", "mid ''' smdx to json mapping: fixed block -> top level group model", "points = [] for e in fixed.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not", "mdef.NAME SMDX_ATTR_TYPE = mdef.TYPE SMDX_ATTR_COUNT = mdef.COUNT SMDX_ATTR_VALUE = mdef.VALUE SMDX_ATTR_TYPE_FIXED = 'fixed'", "mdef.TYPE_ACC16 SMDX_TYPE_ENUM16 = mdef.TYPE_ENUM16 SMDX_TYPE_BITFIELD16 = mdef.TYPE_BITFIELD16 SMDX_TYPE_PAD = mdef.TYPE_PAD SMDX_TYPE_INT32 = mdef.TYPE_INT32", "= {} m = element.find(SMDX_MODEL) if m is None: raise mdef.ModelDefinitionError('Model definition not", "= [] for e in repeating.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not in", "= ptype plen = mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN)) if ptype == SMDX_TYPE_STRING: if plen is None:", "pid = element.attrib.get(SMDX_ATTR_ID) if pid is None: raise mdef.ModelDefinitionError('Missing point id attribute') point_def[mdef.NAME]", "'v' SMDX_ATTR_ID = 'id' SMDX_ATTR_LEN = 'len' SMDX_ATTR_NAME = mdef.NAME SMDX_ATTR_TYPE = mdef.TYPE", "(SMDX_PREFIX, int(model_id), SMDX_EXT) def model_filename_to_id(filename): f = filename if '.' in f: f", "mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if points: repeating_def[mdef.POINTS] = points fixed_def[mdef.GROUPS] =", "if mandatory not in smdx_mandatory_types: raise mdef.ModelDefinitionError('Unknown mandatory type: %s' % mandatory) if", "and a.text: desc = a.text elif a.tag == SMDX_NOTES and a.text: notes =", "of the Software, and to permit persons to whom the Software is furnished", "point type %s for point %s' % (ptype, pid)) point_def[mdef.TYPE] = ptype plen", "model ID and 'value' is the model ID value as a number L", "SMDX_DESCRIPTION = 'description' SMDX_NOTES = 'notes' SMDX_DETAIL = mdef.DETAIL SMDX_TYPE_INT16 = mdef.TYPE_INT16 SMDX_TYPE_UINT16", "= 'repeating' points: all type, access, and mandatory attributes are preserved point symbol", "= {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.POINTS: [ {mdef.NAME: 'ID', mdef.VALUE: mid, mdef.DESCRIPTION: 'Model", "mdef.ModelDefinitionError('Duplicate fixed block type definition') fixed = b elif btype == SMDX_ATTR_TYPE_REPEATING: if", "copyright notice and this permission notice shall be included in all copies or", "= 'false' SMDX_MANDATORY_TRUE = 'true' smdx_access_types = {SMDX_ACCESS_R: mdef.ACCESS_R, SMDX_ACCESS_RW: mdef.ACCESS_RW} smdx_mandatory_types =", "point_def[mdef.MANDATORY] = smdx_mandatory_types.get(mandatory) access = element.attrib.get(SMDX_ATTR_ACCESS, SMDX_ACCESS_R) if access not in smdx_access_types: raise", "mdef.DESCRIPTION: 'Model length', mdef.LABEL: 'Model Length', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE:", "repeating_points_map.get(pid) if point_def is not None: if label: point_def[mdef.LABEL] = label if desc:", "scale factor is an number, convert to correct type sf = mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF)) if", "points = [] for e in repeating.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not", "= mdef.NAME SMDX_ATTR_TYPE = mdef.TYPE SMDX_ATTR_COUNT = mdef.COUNT SMDX_ATTR_VALUE = mdef.VALUE SMDX_ATTR_TYPE_FIXED =", "= mdef.TYPE_IPV6ADDR SMDX_TYPE_FLOAT32 = mdef.TYPE_FLOAT32 SMDX_TYPE_STRING = mdef.TYPE_STRING SMDX_TYPE_SUNSSF = mdef.TYPE_SUNSSF SMDX_TYPE_EUI48 =", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "is not None: point_def[mdef.SF] = sf # if scale factor is an number,", "= point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if points:", "repeating_points_map: repeating_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME])", "an element tree point element contained in an SMDX model definition. Parameters: element", "SMDX_TYPE_UINT32, SMDX_TYPE_ACC32, SMDX_TYPE_ENUM32, SMDX_TYPE_BITFIELD32, SMDX_TYPE_IPADDR, SMDX_TYPE_INT64, SMDX_TYPE_UINT64, SMDX_TYPE_ACC64, SMDX_TYPE_IPV6ADDR, SMDX_TYPE_FLOAT32, SMDX_TYPE_STRING, SMDX_TYPE_SUNSSF, SMDX_TYPE_EUI48", "ID and L points fixed_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.POINTS: [ {mdef.NAME:", "a.text: label = a.text elif a.tag == SMDX_DESCRIPTION and a.text: desc = a.text", "an SMDX model definition. Parameters: element : Element Tree point type element. strings", "] SMDX_PREFIX = 'smdx_' SMDX_EXT = '.xml' def to_smdx_filename(model_id): return '%s%05d%s' % (SMDX_PREFIX,", "point: %s' % pid) elif ptype not in smdx_type_types: raise mdef.ModelDefinitionError('Unknown point type", "block type definition') repeating = b else: raise mdef.ModelDefinitionError('Invalid block type: %s' %", "extracting model id from filename') return mid ''' smdx to json mapping: fixed", "correct type value = mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE)) if value is not None: point_def[mdef.VALUE] = value", "distribute, sublicense, and/or sell copies of the Software, and to permit persons to", "software and associated documentation files (the \"Software\"), to deal in the Software without", "SMDX_ATTR_ACCESS = mdef.ACCESS SMDX_ATTR_SF = mdef.SF SMDX_ATTR_UNITS = mdef.UNITS SMDX_SYMBOL = 'symbol' SMDX_COMMENT", "SMDX_ATTR_LEN = 'len' SMDX_ATTR_NAME = mdef.NAME SMDX_ATTR_TYPE = mdef.TYPE SMDX_ATTR_COUNT = mdef.COUNT SMDX_ATTR_VALUE", "mdef.TYPE_FLOAT32 SMDX_TYPE_STRING = mdef.TYPE_STRING SMDX_TYPE_SUNSSF = mdef.TYPE_SUNSSF SMDX_TYPE_EUI48 = mdef.TYPE_EUI48 SMDX_ACCESS_R = 'r'", "Element Tree point type element. strings : Indicates if *element* is a subelement", "mdef.TYPE_ACC64 SMDX_TYPE_IPV6ADDR = mdef.TYPE_IPV6ADDR SMDX_TYPE_FLOAT32 = mdef.TYPE_FLOAT32 SMDX_TYPE_STRING = mdef.TYPE_STRING SMDX_TYPE_SUNSSF = mdef.TYPE_SUNSSF", "= b.attrib.get(SMDX_ATTR_TYPE, SMDX_ATTR_TYPE_FIXED) if btype == SMDX_ATTR_TYPE_FIXED: if fixed is not None: raise", "shall be included in all copies or substantial portions of the Software. THE", "= tree.getroot() return(from_smdx(root)) def from_smdx(element): \"\"\" Sets the model type attributes based on", "a.text: desc = a.text elif a.tag == SMDX_NOTES and a.text: notes = a.text", "point_def[mdef.UNITS] = units # if scale factor is an number, convert to correct", "Parameters: element : Element Tree point type element. strings : Indicates if *element*", "NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "mdef.TYPE_UINT16}, {mdef.NAME: 'L', mdef.DESCRIPTION: 'Model length', mdef.LABEL: 'Model Length', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE,", "notes = None for a in p.findall('*'): if a.tag == SMDX_LABEL and a.text:", "'label', 'desc', 'detail' ''' def from_smdx_file(filename): tree = ET.parse(filename) root = tree.getroot() return(from_smdx(root))", "= 'true' smdx_access_types = {SMDX_ACCESS_R: mdef.ACCESS_R, SMDX_ACCESS_RW: mdef.ACCESS_RW} smdx_mandatory_types = {SMDX_MANDATORY_FALSE: mdef.MANDATORY_FALSE, SMDX_MANDATORY_TRUE:", "SMDX_ACCESS_RW: point_def[mdef.ACCESS] = smdx_access_types.get(access) units = element.attrib.get(SMDX_ATTR_UNITS) if units: point_def[mdef.UNITS] = units #", "SMDX_TYPE_ACC32 = mdef.TYPE_ACC32 SMDX_TYPE_ENUM32 = mdef.TYPE_ENUM32 SMDX_TYPE_BITFIELD32 = mdef.TYPE_BITFIELD32 SMDX_TYPE_IPADDR = mdef.TYPE_IPADDR SMDX_TYPE_INT64", "from_smdx_point(e) if point_def[mdef.NAME] not in fixed_points_map: fixed_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate", "ID and 'value' is the model ID value as a number L point", "None: point_def[mdef.SF] = sf # if scale factor is an number, convert to", "and L points fixed_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.POINTS: [ {mdef.NAME: 'ID',", "None: raise mdef.ModelDefinitionError('Duplicate fixed block type definition') fixed = b elif btype ==", "= element.attrib.get(SMDX_ATTR_ACCESS, SMDX_ACCESS_R) if access not in smdx_access_types: raise mdef.ModelDefinitionError('Unknown access type: %s'", "mdef.TYPE_IPV6ADDR SMDX_TYPE_FLOAT32 = mdef.TYPE_FLOAT32 SMDX_TYPE_STRING = mdef.TYPE_STRING SMDX_TYPE_SUNSSF = mdef.TYPE_SUNSSF SMDX_TYPE_EUI48 = mdef.TYPE_EUI48", "in m.findall('*'): if a.tag == SMDX_LABEL and a.text: fixed_def[mdef.LABEL] = a.text elif a.tag", "None: name = 'repeating' repeating_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.COUNT: 0} points", "is hereby granted, free of charge, to any person obtaining a copy of", "SMDX_TYPE_COUNT, SMDX_TYPE_ACC16, SMDX_TYPE_ENUM16, SMDX_TYPE_BITFIELD16, SMDX_TYPE_PAD, SMDX_TYPE_INT32, SMDX_TYPE_UINT32, SMDX_TYPE_ACC32, SMDX_TYPE_ENUM32, SMDX_TYPE_BITFIELD32, SMDX_TYPE_IPADDR, SMDX_TYPE_INT64, SMDX_TYPE_UINT64,", "a in p.findall('*'): if a.tag == SMDX_LABEL and a.text: label = a.text elif", "access type: %s' % access) if access == SMDX_ACCESS_RW: point_def[mdef.ACCESS] = smdx_access_types.get(access) units", "= [] for e in fixed.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not in", "notes point_def = repeating_points_map.get(pid) if point_def is not None: if label: point_def[mdef.LABEL] =", "a.tag == SMDX_DESCRIPTION and a.text: desc = a.text elif a.tag == SMDX_NOTES and", "notes = a.text point_def = fixed_points_map.get(pid) if point_def is not None: if label:", "= mdef.COUNT SMDX_ATTR_VALUE = mdef.VALUE SMDX_ATTR_TYPE_FIXED = 'fixed' SMDX_ATTR_TYPE_REPEATING = 'repeating' SMDX_ATTR_OFFSET =", "label = desc = notes = None for a in p.findall('*'): if a.tag", "= repeating_points_map.get(pid) if point_def is not None: if label: point_def[mdef.LABEL] = label if", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "level*\" \" if len(elem): if not elem.text or not elem.text.strip(): elem.text = i", "type, access, and mandatory attributes are preserved point symbol map to the symbol", "point_def[mdef.DETAIL] = notes point_def = repeating_points_map.get(pid) if point_def is not None: if label:", "= int(f.rsplit('_', 1)[1]) except ValueError: raise mdef.ModelDefinitionError('Error extracting model id from filename') return", "None: name = 'model_' + str(mid) model_def[mdef.NAME] = name strings = element.find(SMDX_STRINGS) #", "mdef.TYPE_PAD SMDX_TYPE_INT32 = mdef.TYPE_INT32 SMDX_TYPE_UINT32 = mdef.TYPE_UINT32 SMDX_TYPE_ACC32 = mdef.TYPE_ACC32 SMDX_TYPE_ENUM32 = mdef.TYPE_ENUM32", "'block' SMDX_POINT = 'point' SMDX_ATTR_VERS = 'v' SMDX_ATTR_ID = 'id' SMDX_ATTR_LEN = 'len'", "element contained in an SMDX model definition. Parameters: element : Element Tree point", "= m.attrib.get(SMDX_ATTR_NAME) if name is None: name = 'model_' + str(mid) model_def[mdef.NAME] =", "SMDX_MANDATORY_FALSE) if mandatory not in smdx_mandatory_types: raise mdef.ModelDefinitionError('Unknown mandatory type: %s' % mandatory)", "tree model type element contained in an SMDX model definition. Parameters: element :", "{} if fixed is not None: points = [] for e in fixed.findall(SMDX_POINT):", "definition') repeating = b else: raise mdef.ModelDefinitionError('Invalid block type: %s' % btype) fixed_points_map", "'smdx_' SMDX_EXT = '.xml' def to_smdx_filename(model_id): return '%s%05d%s' % (SMDX_PREFIX, int(model_id), SMDX_EXT) def", "if name is None: name = 'model_' + str(mid) model_def[mdef.NAME] = name strings", "point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if points: repeating_def[mdef.POINTS]", "SMDX_TYPE_EUI48 = mdef.TYPE_EUI48 SMDX_ACCESS_R = 'r' SMDX_ACCESS_RW = 'rw' SMDX_MANDATORY_FALSE = 'false' SMDX_MANDATORY_TRUE", "len attribute for point: %s' % pid) point_def[mdef.SIZE] = plen else: point_def[mdef.SIZE] =", "{} if repeating is not None: name = repeating.attrib.get(SMDX_ATTR_NAME) if name is None:", "None: if label: point_def[mdef.LABEL] = label if desc: point_def[mdef.DESCRIPTION] = desc if notes:", "definition. \"\"\" point_def = {} pid = element.attrib.get(SMDX_ATTR_ID) if pid is None: raise", "if repeating is not None: name = repeating.attrib.get(SMDX_ATTR_NAME) if name is None: name", "elif a.tag == SMDX_DESCRIPTION and a.text: desc = a.text elif a.tag == SMDX_NOTES", "point_def[mdef.NAME] not in repeating_points_map: repeating_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition:", "== str(mid): m = e.find(SMDX_MODEL) if m is not None: for a in", "len shoud be used to determine number of groups) repeating block 'name' ->", "name, mdef.TYPE: mdef.TYPE_GROUP, mdef.COUNT: 0} points = [] for e in repeating.findall(SMDX_POINT): point_def", "fixed_def[mdef.DETAIL] = a.text for p in e.findall(SMDX_POINT): pid = p.attrib.get(SMDX_ATTR_ID) label = desc", "point attributes 'label', 'desc', 'detail' ''' def from_smdx_file(filename): tree = ET.parse(filename) root =", "model_def[mdef.NAME] = name strings = element.find(SMDX_STRINGS) # create top level group with ID", "elif btype == SMDX_ATTR_TYPE_REPEATING: if repeating is not None: raise mdef.ModelDefinitionError('Duplicate repeating block", "merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit", "SMDX_TYPE_ENUM16 = mdef.TYPE_ENUM16 SMDX_TYPE_BITFIELD16 = mdef.TYPE_BITFIELD16 SMDX_TYPE_PAD = mdef.TYPE_PAD SMDX_TYPE_INT32 = mdef.TYPE_INT32 SMDX_TYPE_UINT32", "mdef.TYPE_COUNT SMDX_TYPE_ACC16 = mdef.TYPE_ACC16 SMDX_TYPE_ENUM16 = mdef.TYPE_ENUM16 SMDX_TYPE_BITFIELD16 = mdef.TYPE_BITFIELD16 SMDX_TYPE_PAD = mdef.TYPE_PAD", "L points fixed_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.POINTS: [ {mdef.NAME: 'ID', mdef.VALUE:", "if point_def[mdef.NAME] not in fixed_points_map: fixed_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point", "= a.text elif a.tag == SMDX_DESCRIPTION and a.text: desc = a.text elif a.tag", "SMDX_BLOCK = 'block' SMDX_POINT = 'point' SMDX_ATTR_VERS = 'v' SMDX_ATTR_ID = 'id' SMDX_ATTR_LEN", "model id: %s' % m.attrib.get(SMDX_ATTR_ID)) name = m.attrib.get(SMDX_ATTR_NAME) if name is None: name", "level=0): i = os.linesep + level*\" \" if len(elem): if not elem.text or", "= 'rw' SMDX_MANDATORY_FALSE = 'false' SMDX_MANDATORY_TRUE = 'true' smdx_access_types = {SMDX_ACCESS_R: mdef.ACCESS_R, SMDX_ACCESS_RW:", "= a.text elif a.tag == SMDX_NOTES and a.text: fixed_def[mdef.DETAIL] = a.text for p", "SMDX_DETAIL = mdef.DETAIL SMDX_TYPE_INT16 = mdef.TYPE_INT16 SMDX_TYPE_UINT16 = mdef.TYPE_UINT16 SMDX_TYPE_COUNT = mdef.TYPE_COUNT SMDX_TYPE_ACC16", "ET import sunspec2.mdef as mdef SMDX_ROOT = 'sunSpecModels' SMDX_MODEL = mdef.MODEL SMDX_BLOCK =", "point: %s' % pid) point_def[mdef.SIZE] = plen else: point_def[mdef.SIZE] = mdef.point_type_info.get(ptype)['len'] mandatory =", "mdef.MANDATORY_FALSE, SMDX_MANDATORY_TRUE: mdef.MANDATORY_TRUE} smdx_type_types = [ SMDX_TYPE_INT16, SMDX_TYPE_UINT16, SMDX_TYPE_COUNT, SMDX_TYPE_ACC16, SMDX_TYPE_ENUM16, SMDX_TYPE_BITFIELD16, SMDX_TYPE_PAD,", "ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "= value symbols = [] for e in element.findall('*'): if e.tag == SMDX_SYMBOL:", "definition') fixed = b elif btype == SMDX_ATTR_TYPE_REPEATING: if repeating is not None:", "WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF", "repeating is not None: name = repeating.attrib.get(SMDX_ATTR_NAME) if name is None: name =", "is not None: name = repeating.attrib.get(SMDX_ATTR_NAME) if name is None: name = 'repeating'", "attribute -> group 'name' ID point is created for model ID and 'value'", "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE", "is None: name = 'model_' + str(mid) model_def[mdef.NAME] = name strings = element.find(SMDX_STRINGS)", "if e.tag == SMDX_SYMBOL: sid = e.attrib.get(SMDX_ATTR_ID) value = e.text try: value =", "in fixed.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not in fixed_points_map: fixed_points_map[point_def[mdef.NAME]] = point_def", "desc if notes: point_def[mdef.DETAIL] = notes model_def = {'id': mid, 'group': fixed_def} return", "charge, to any person obtaining a copy of this software and associated documentation", "KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "-> symbol object 'name' symbol element content -> symbol object 'value' strings 'label',", "SMDX_TYPE_INT64 = mdef.TYPE_INT64 SMDX_TYPE_UINT64 = mdef.TYPE_UINT64 SMDX_TYPE_ACC64 = mdef.TYPE_ACC64 SMDX_TYPE_IPV6ADDR = mdef.TYPE_IPV6ADDR SMDX_TYPE_FLOAT32", "'description' SMDX_NOTES = 'notes' SMDX_DETAIL = mdef.DETAIL SMDX_TYPE_INT16 = mdef.TYPE_INT16 SMDX_TYPE_UINT16 = mdef.TYPE_UINT16", "symbol object 'value' strings 'label', 'description', 'notes' elements map to point attributes 'label',", "mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN)) if ptype == SMDX_TYPE_STRING: if plen is None: raise mdef.ModelDefinitionError('Missing len attribute", "elif a.tag == SMDX_NOTES and a.text: fixed_def[mdef.DETAIL] = a.text for p in e.findall(SMDX_POINT):", "the 'strings' definintion within the model definition. \"\"\" point_def = {} pid =", "persons to whom the Software is furnished to do so, subject to the", "access, and mandatory attributes are preserved point symbol map to the symbol object", "value = e.text try: value = int(value) except ValueError: pass symbols.append({mdef.NAME: sid, mdef.VALUE:", "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "from_smdx_point(element): \"\"\" Sets the point attributes based on an element tree point element", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND", "= mdef.SF SMDX_ATTR_UNITS = mdef.UNITS SMDX_SYMBOL = 'symbol' SMDX_COMMENT = 'comment' SMDX_STRINGS =", "access not in smdx_access_types: raise mdef.ModelDefinitionError('Unknown access type: %s' % access) if access", "definition fixed block points are placed in top level group repeating block ->", "based on an element tree point element contained in an SMDX model definition.", "== SMDX_SYMBOL: sid = e.attrib.get(SMDX_ATTR_ID) value = e.text try: value = int(value) except", "Parameters: element : Element Tree model type element. \"\"\" model_def = {} m", "model definition. Parameters: element : Element Tree point type element. strings : Indicates", "= None fixed = None repeating = None for b in m.findall(SMDX_BLOCK): btype", "if not elem.text or not elem.text.strip(): elem.text = i + \" \" if", "repeating block -> group with count = 0 (indicates model len shoud be", "raise mdef.ModelDefinitionError('Missing point id attribute') point_def[mdef.NAME] = pid ptype = element.attrib.get(SMDX_ATTR_TYPE) if ptype", "smdx_access_types.get(access) units = element.attrib.get(SMDX_ATTR_UNITS) if units: point_def[mdef.UNITS] = units # if scale factor", "to whom the Software is furnished to do so, subject to the following", "with count = 0 (indicates model len shoud be used to determine number", "mdef.TYPE_INT64 SMDX_TYPE_UINT64 = mdef.TYPE_UINT64 SMDX_TYPE_ACC64 = mdef.TYPE_ACC64 SMDX_TYPE_IPV6ADDR = mdef.TYPE_IPV6ADDR SMDX_TYPE_FLOAT32 = mdef.TYPE_FLOAT32", "'name' is defined 'name' = 'repeating' points: all type, access, and mandatory attributes", "in the model definition fixed block points are placed in top level group", "None: raise mdef.ModelDefinitionError('Duplicate repeating block type definition') repeating = b else: raise mdef.ModelDefinitionError('Invalid", "symbols: point_def[mdef.SYMBOLS] = symbols return point_def def indent(elem, level=0): i = os.linesep +", "is defined 'name' = 'repeating' points: all type, access, and mandatory attributes are", "in the Software without restriction, including without limitation the rights to use, copy,", "except ValueError: raise mdef.ModelDefinitionError('Error extracting model id from filename') return mid ''' smdx", "mdef.VALUE: value}) if symbols: point_def[mdef.SYMBOLS] = symbols return point_def def indent(elem, level=0): i", "of the 'strings' definintion within the model definition. \"\"\" point_def = {} pid", "= mdef.UNITS SMDX_SYMBOL = 'symbol' SMDX_COMMENT = 'comment' SMDX_STRINGS = 'strings' SMDX_ATTR_LOCALE =", "if fixed is not None: raise mdef.ModelDefinitionError('Duplicate fixed block type definition') fixed =", "'description', 'notes' elements map to point attributes 'label', 'desc', 'detail' ''' def from_smdx_file(filename):", "for point %s' % (ptype, pid)) point_def[mdef.TYPE] = ptype plen = mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN)) if", "btype == SMDX_ATTR_TYPE_FIXED: if fixed is not None: raise mdef.ModelDefinitionError('Duplicate fixed block type", "] } repeating_def = None fixed = None repeating = None for b", "point_def[mdef.VALUE] = value symbols = [] for e in element.findall('*'): if e.tag ==", "else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if points: fixed_def[mdef.POINTS].extend(points) repeating_points_map =", "SMDX_ATTR_MANDATORY = mdef.MANDATORY SMDX_ATTR_ACCESS = mdef.ACCESS SMDX_ATTR_SF = mdef.SF SMDX_ATTR_UNITS = mdef.UNITS SMDX_SYMBOL", "- model len has no value specified in the model definition fixed block", "and placed in the symbols list for the point symbol 'name' attribute ->", "if repeating is not None: raise mdef.ModelDefinitionError('Duplicate repeating block type definition') repeating =", "type definition') fixed = b elif btype == SMDX_ATTR_TYPE_REPEATING: if repeating is not", "the point symbol 'name' attribute -> symbol object 'name' symbol element content ->", "SMDX_TYPE_UINT16 = mdef.TYPE_UINT16 SMDX_TYPE_COUNT = mdef.TYPE_COUNT SMDX_TYPE_ACC16 = mdef.TYPE_ACC16 SMDX_TYPE_ENUM16 = mdef.TYPE_ENUM16 SMDX_TYPE_BITFIELD16", "in smdx_type_types: raise mdef.ModelDefinitionError('Unknown point type %s for point %s' % (ptype, pid))", "specified in the model definition fixed block points are placed in top level", "SMDX_TYPE_IPADDR, SMDX_TYPE_INT64, SMDX_TYPE_UINT64, SMDX_TYPE_ACC64, SMDX_TYPE_IPV6ADDR, SMDX_TYPE_FLOAT32, SMDX_TYPE_STRING, SMDX_TYPE_SUNSSF, SMDX_TYPE_EUI48 ] SMDX_PREFIX = 'smdx_'", "name is None: name = 'model_' + str(mid) model_def[mdef.NAME] = name strings =", "= notes model_def = {'id': mid, 'group': fixed_def} return model_def def from_smdx_point(element): \"\"\"", "in smdx_access_types: raise mdef.ModelDefinitionError('Unknown access type: %s' % access) if access == SMDX_ACCESS_RW:", "= mdef.MODEL SMDX_BLOCK = 'block' SMDX_POINT = 'point' SMDX_ATTR_VERS = 'v' SMDX_ATTR_ID =", "created for model len - model len has no value specified in the", "associated documentation files (the \"Software\"), to deal in the Software without restriction, including", "'.xml' def to_smdx_filename(model_id): return '%s%05d%s' % (SMDX_PREFIX, int(model_id), SMDX_EXT) def model_filename_to_id(filename): f =", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE", "%s' % pid) point_def[mdef.SIZE] = plen else: point_def[mdef.SIZE] = mdef.point_type_info.get(ptype)['len'] mandatory = element.attrib.get(SMDX_ATTR_MANDATORY,", "to determine number of groups) repeating block 'name' -> group 'name', if no", "name, mdef.TYPE: mdef.TYPE_GROUP, mdef.POINTS: [ {mdef.NAME: 'ID', mdef.VALUE: mid, mdef.DESCRIPTION: 'Model identifier', mdef.LABEL:", "{mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.COUNT: 0} points = [] for e in repeating.findall(SMDX_POINT):", "indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if", "SMDX_DESCRIPTION and a.text: desc = a.text elif a.tag == SMDX_NOTES and a.text: notes", "SMDX_TYPE_INT32, SMDX_TYPE_UINT32, SMDX_TYPE_ACC32, SMDX_TYPE_ENUM32, SMDX_TYPE_BITFIELD32, SMDX_TYPE_IPADDR, SMDX_TYPE_INT64, SMDX_TYPE_UINT64, SMDX_TYPE_ACC64, SMDX_TYPE_IPV6ADDR, SMDX_TYPE_FLOAT32, SMDX_TYPE_STRING, SMDX_TYPE_SUNSSF,", "or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or", "is an number, convert to correct type value = mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE)) if value is", "= name strings = element.find(SMDX_STRINGS) # create top level group with ID and", "mid = mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID)) except ValueError: raise mdef.ModelDefinitionError('Invalid model id: %s' % m.attrib.get(SMDX_ATTR_ID)) name", "not elem.text or not elem.text.strip(): elem.text = i + \" \" if not", "obtaining a copy of this software and associated documentation files (the \"Software\"), to", "= [ SMDX_TYPE_INT16, SMDX_TYPE_UINT16, SMDX_TYPE_COUNT, SMDX_TYPE_ACC16, SMDX_TYPE_ENUM16, SMDX_TYPE_BITFIELD16, SMDX_TYPE_PAD, SMDX_TYPE_INT32, SMDX_TYPE_UINT32, SMDX_TYPE_ACC32, SMDX_TYPE_ENUM32,", "SMDX_ACCESS_R = 'r' SMDX_ACCESS_RW = 'rw' SMDX_MANDATORY_FALSE = 'false' SMDX_MANDATORY_TRUE = 'true' smdx_access_types", "fixed_def} return model_def def from_smdx_point(element): \"\"\" Sets the point attributes based on an", "pid) elif ptype not in smdx_type_types: raise mdef.ModelDefinitionError('Unknown point type %s for point", "return '%s%05d%s' % (SMDX_PREFIX, int(model_id), SMDX_EXT) def model_filename_to_id(filename): f = filename if '.'", "SMDX_TYPE_INT16 = mdef.TYPE_INT16 SMDX_TYPE_UINT16 = mdef.TYPE_UINT16 SMDX_TYPE_COUNT = mdef.TYPE_COUNT SMDX_TYPE_ACC16 = mdef.TYPE_ACC16 SMDX_TYPE_ENUM16", "= mdef.TYPE_UINT32 SMDX_TYPE_ACC32 = mdef.TYPE_ACC32 SMDX_TYPE_ENUM32 = mdef.TYPE_ENUM32 SMDX_TYPE_BITFIELD32 = mdef.TYPE_BITFIELD32 SMDX_TYPE_IPADDR =", "# create top level group with ID and L points fixed_def = {mdef.NAME:", "model definition fixed block points are placed in top level group repeating block", "raise mdef.ModelDefinitionError('Model definition not found') try: mid = mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID)) except ValueError: raise mdef.ModelDefinitionError('Invalid", "== SMDX_NOTES and a.text: fixed_def[mdef.DETAIL] = a.text for p in e.findall(SMDX_POINT): pid =", "str(mid) model_def[mdef.NAME] = name strings = element.find(SMDX_STRINGS) # create top level group with", "type element. \"\"\" model_def = {} m = element.find(SMDX_MODEL) if m is None:", "mdef.TYPE_ACC32 SMDX_TYPE_ENUM32 = mdef.TYPE_ENUM32 SMDX_TYPE_BITFIELD32 = mdef.TYPE_BITFIELD32 SMDX_TYPE_IPADDR = mdef.TYPE_IPADDR SMDX_TYPE_INT64 = mdef.TYPE_INT64", "desc: point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL] = notes point_def = repeating_points_map.get(pid) if", "including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,", "OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import os import xml.etree.ElementTree as ET", "and a.text: fixed_def[mdef.DESCRIPTION] = a.text elif a.tag == SMDX_NOTES and a.text: fixed_def[mdef.DETAIL] =", "or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "SMDX_POINT = 'point' SMDX_ATTR_VERS = 'v' SMDX_ATTR_ID = 'id' SMDX_ATTR_LEN = 'len' SMDX_ATTR_NAME", "if points: repeating_def[mdef.POINTS] = points fixed_def[mdef.GROUPS] = [repeating_def] e = element.find(SMDX_STRINGS) if e.attrib.get(SMDX_ATTR_ID)", "for e in element.findall('*'): if e.tag == SMDX_SYMBOL: sid = e.attrib.get(SMDX_ATTR_ID) value =", "'repeating' points: all type, access, and mandatory attributes are preserved point symbol map", "mdef.TYPE_UINT16 SMDX_TYPE_COUNT = mdef.TYPE_COUNT SMDX_TYPE_ACC16 = mdef.TYPE_ACC16 SMDX_TYPE_ENUM16 = mdef.TYPE_ENUM16 SMDX_TYPE_BITFIELD16 = mdef.TYPE_BITFIELD16", "value = int(value) except ValueError: pass symbols.append({mdef.NAME: sid, mdef.VALUE: value}) if symbols: point_def[mdef.SYMBOLS]", "= mdef.MANDATORY SMDX_ATTR_ACCESS = mdef.ACCESS SMDX_ATTR_SF = mdef.SF SMDX_ATTR_UNITS = mdef.UNITS SMDX_SYMBOL =", "b elif btype == SMDX_ATTR_TYPE_REPEATING: if repeating is not None: raise mdef.ModelDefinitionError('Duplicate repeating", "definition: %s' % point_def[mdef.NAME]) if points: repeating_def[mdef.POINTS] = points fixed_def[mdef.GROUPS] = [repeating_def] e", "is created for model len - model len has no value specified in", "mandatory = element.attrib.get(SMDX_ATTR_MANDATORY, SMDX_MANDATORY_FALSE) if mandatory not in smdx_mandatory_types: raise mdef.ModelDefinitionError('Unknown mandatory type:", "str(mid): m = e.find(SMDX_MODEL) if m is not None: for a in m.findall('*'):", "block -> group with count = 0 (indicates model len shoud be used", "smdx_type_types: raise mdef.ModelDefinitionError('Unknown point type %s for point %s' % (ptype, pid)) point_def[mdef.TYPE]", "symbol object 'name' symbol element content -> symbol object 'value' strings 'label', 'description',", "SMDX_TYPE_IPV6ADDR, SMDX_TYPE_FLOAT32, SMDX_TYPE_STRING, SMDX_TYPE_SUNSSF, SMDX_TYPE_EUI48 ] SMDX_PREFIX = 'smdx_' SMDX_EXT = '.xml' def", "block type: %s' % btype) fixed_points_map = {} if fixed is not None:", "None: points = [] for e in fixed.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME]", "units # if scale factor is an number, convert to correct type sf", "== SMDX_DESCRIPTION and a.text: fixed_def[mdef.DESCRIPTION] = a.text elif a.tag == SMDX_NOTES and a.text:", "mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if points: fixed_def[mdef.POINTS].extend(points) repeating_points_map = {} if", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN", "= mdef.DETAIL SMDX_TYPE_INT16 = mdef.TYPE_INT16 SMDX_TYPE_UINT16 = mdef.TYPE_UINT16 SMDX_TYPE_COUNT = mdef.TYPE_COUNT SMDX_TYPE_ACC16 =", "ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "point symbol map to the symbol object and placed in the symbols list", "= element.find(SMDX_STRINGS) if e.attrib.get(SMDX_ATTR_ID) == str(mid): m = e.find(SMDX_MODEL) if m is not", "if fixed is not None: points = [] for e in fixed.findall(SMDX_POINT): point_def", "None: for a in m.findall('*'): if a.tag == SMDX_LABEL and a.text: fixed_def[mdef.LABEL] =", "not in fixed_points_map: fixed_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s'", "Copyright (C) 2020 SunSpec Alliance Permission is hereby granted, free of charge, to", "== SMDX_TYPE_STRING: if plen is None: raise mdef.ModelDefinitionError('Missing len attribute for point: %s'", "'name' symbol element content -> symbol object 'value' strings 'label', 'description', 'notes' elements", "% pid) point_def[mdef.SIZE] = plen else: point_def[mdef.SIZE] = mdef.point_type_info.get(ptype)['len'] mandatory = element.attrib.get(SMDX_ATTR_MANDATORY, SMDX_MANDATORY_FALSE)", "number, convert to correct type sf = mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF)) if sf is not None:", "= e.attrib.get(SMDX_ATTR_ID) value = e.text try: value = int(value) except ValueError: pass symbols.append({mdef.NAME:", "the following conditions: The above copyright notice and this permission notice shall be", "= mdef.TYPE_INT16 SMDX_TYPE_UINT16 = mdef.TYPE_UINT16 SMDX_TYPE_COUNT = mdef.TYPE_COUNT SMDX_TYPE_ACC16 = mdef.TYPE_ACC16 SMDX_TYPE_ENUM16 =", "mdef.ModelDefinitionError('Duplicate repeating block type definition') repeating = b else: raise mdef.ModelDefinitionError('Invalid block type:", "(ptype, pid)) point_def[mdef.TYPE] = ptype plen = mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN)) if ptype == SMDX_TYPE_STRING: if", "'strings' definintion within the model definition. \"\"\" point_def = {} pid = element.attrib.get(SMDX_ATTR_ID)", "number of groups) repeating block 'name' -> group 'name', if no 'name' is", "pid = p.attrib.get(SMDX_ATTR_ID) label = desc = notes = None for a in", "ptype plen = mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN)) if ptype == SMDX_TYPE_STRING: if plen is None: raise", "mdef.LABEL: 'Model Length', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16} ] }", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", "included in all copies or substantial portions of the Software. THE SOFTWARE IS", "btype = b.attrib.get(SMDX_ATTR_TYPE, SMDX_ATTR_TYPE_FIXED) if btype == SMDX_ATTR_TYPE_FIXED: if fixed is not None:", "= desc if notes: point_def[mdef.DETAIL] = notes point_def = repeating_points_map.get(pid) if point_def is", "created for model ID and 'value' is the model ID value as a", "smdx_mandatory_types.get(mandatory) access = element.attrib.get(SMDX_ATTR_ACCESS, SMDX_ACCESS_R) if access not in smdx_access_types: raise mdef.ModelDefinitionError('Unknown access", "from_smdx_point(e) if point_def[mdef.NAME] not in repeating_points_map: repeating_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate", "return model_def def from_smdx_point(element): \"\"\" Sets the point attributes based on an element", "block -> top level group model 'name' attribute -> group 'name' ID point", "type attribute for point: %s' % pid) elif ptype not in smdx_type_types: raise", "DEALINGS IN THE SOFTWARE. \"\"\" import os import xml.etree.ElementTree as ET import sunspec2.mdef", "SMDX_TYPE_SUNSSF = mdef.TYPE_SUNSSF SMDX_TYPE_EUI48 = mdef.TYPE_EUI48 SMDX_ACCESS_R = 'r' SMDX_ACCESS_RW = 'rw' SMDX_MANDATORY_FALSE", "a.text for p in e.findall(SMDX_POINT): pid = p.attrib.get(SMDX_ATTR_ID) label = desc = notes", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,", "not in smdx_access_types: raise mdef.ModelDefinitionError('Unknown access type: %s' % access) if access ==", "for p in e.findall(SMDX_POINT): pid = p.attrib.get(SMDX_ATTR_ID) label = desc = notes =", "NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "mdef.ACCESS_R, SMDX_ACCESS_RW: mdef.ACCESS_RW} smdx_mandatory_types = {SMDX_MANDATORY_FALSE: mdef.MANDATORY_FALSE, SMDX_MANDATORY_TRUE: mdef.MANDATORY_TRUE} smdx_type_types = [ SMDX_TYPE_INT16,", "raise mdef.ModelDefinitionError('Unknown point type %s for point %s' % (ptype, pid)) point_def[mdef.TYPE] =", "= fixed_points_map.get(pid) if point_def is not None: if label: point_def[mdef.LABEL] = label if", "= mdef.TYPE_ACC16 SMDX_TYPE_ENUM16 = mdef.TYPE_ENUM16 SMDX_TYPE_BITFIELD16 = mdef.TYPE_BITFIELD16 SMDX_TYPE_PAD = mdef.TYPE_PAD SMDX_TYPE_INT32 =", "*element* is a subelement of the 'strings' definintion within the model definition. \"\"\"", "mid, mdef.DESCRIPTION: 'Model identifier', mdef.LABEL: 'Model ID', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE,", "\"Software\"), to deal in the Software without restriction, including without limitation the rights", "deal in the Software without restriction, including without limitation the rights to use,", "content -> symbol object 'value' strings 'label', 'description', 'notes' elements map to point", "= mdef.TYPE_EUI48 SMDX_ACCESS_R = 'r' SMDX_ACCESS_RW = 'rw' SMDX_MANDATORY_FALSE = 'false' SMDX_MANDATORY_TRUE =", "model 'name' attribute -> group 'name' ID point is created for model ID", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import os", "is not None: point_def[mdef.VALUE] = value symbols = [] for e in element.findall('*'):", "SMDX_ROOT = 'sunSpecModels' SMDX_MODEL = mdef.MODEL SMDX_BLOCK = 'block' SMDX_POINT = 'point' SMDX_ATTR_VERS", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "element. \"\"\" model_def = {} m = element.find(SMDX_MODEL) if m is None: raise", "i + \" \" if not elem.tail or not elem.tail.strip(): elem.tail = i", "= a.text for p in e.findall(SMDX_POINT): pid = p.attrib.get(SMDX_ATTR_ID) label = desc =", "element.attrib.get(SMDX_ATTR_ACCESS, SMDX_ACCESS_R) if access not in smdx_access_types: raise mdef.ModelDefinitionError('Unknown access type: %s' %", "= 'id' SMDX_ATTR_LEN = 'len' SMDX_ATTR_NAME = mdef.NAME SMDX_ATTR_TYPE = mdef.TYPE SMDX_ATTR_COUNT =", "SMDX_STRINGS = 'strings' SMDX_ATTR_LOCALE = 'locale' SMDX_LABEL = mdef.LABEL SMDX_DESCRIPTION = 'description' SMDX_NOTES", "model_filename_to_id(filename): f = filename if '.' in f: f = os.path.splitext(f)[0] try: mid", "the symbols list for the point symbol 'name' attribute -> symbol object 'name'", "= mdef.VALUE SMDX_ATTR_TYPE_FIXED = 'fixed' SMDX_ATTR_TYPE_REPEATING = 'repeating' SMDX_ATTR_OFFSET = 'offset' SMDX_ATTR_MANDATORY =", "None: raise mdef.ModelDefinitionError('Model definition not found') try: mid = mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID)) except ValueError: raise", "mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16} ] } repeating_def = None fixed =", "mdef.ModelDefinitionError('Missing len attribute for point: %s' % pid) point_def[mdef.SIZE] = plen else: point_def[mdef.SIZE]", "\" \" if not elem.tail or not elem.tail.strip(): elem.tail = i for elem", "SMDX_TYPE_ENUM32, SMDX_TYPE_BITFIELD32, SMDX_TYPE_IPADDR, SMDX_TYPE_INT64, SMDX_TYPE_UINT64, SMDX_TYPE_ACC64, SMDX_TYPE_IPV6ADDR, SMDX_TYPE_FLOAT32, SMDX_TYPE_STRING, SMDX_TYPE_SUNSSF, SMDX_TYPE_EUI48 ] SMDX_PREFIX", "to the symbol object and placed in the symbols list for the point", "SMDX_ATTR_TYPE_REPEATING: if repeating is not None: raise mdef.ModelDefinitionError('Duplicate repeating block type definition') repeating", "pid)) point_def[mdef.TYPE] = ptype plen = mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN)) if ptype == SMDX_TYPE_STRING: if plen", "mdef.TYPE_STRING SMDX_TYPE_SUNSSF = mdef.TYPE_SUNSSF SMDX_TYPE_EUI48 = mdef.TYPE_EUI48 SMDX_ACCESS_R = 'r' SMDX_ACCESS_RW = 'rw'", "not None: name = repeating.attrib.get(SMDX_ATTR_NAME) if name is None: name = 'repeating' repeating_def", "so, subject to the following conditions: The above copyright notice and this permission", "symbol object and placed in the symbols list for the point symbol 'name'", "a.text: fixed_def[mdef.DESCRIPTION] = a.text elif a.tag == SMDX_NOTES and a.text: fixed_def[mdef.DETAIL] = a.text", "raise mdef.ModelDefinitionError('Invalid model id: %s' % m.attrib.get(SMDX_ATTR_ID)) name = m.attrib.get(SMDX_ATTR_NAME) if name is", "= os.path.splitext(f)[0] try: mid = int(f.rsplit('_', 1)[1]) except ValueError: raise mdef.ModelDefinitionError('Error extracting model", "if point_def[mdef.NAME] not in repeating_points_map: repeating_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point", "SMDX_TYPE_COUNT = mdef.TYPE_COUNT SMDX_TYPE_ACC16 = mdef.TYPE_ACC16 SMDX_TYPE_ENUM16 = mdef.TYPE_ENUM16 SMDX_TYPE_BITFIELD16 = mdef.TYPE_BITFIELD16 SMDX_TYPE_PAD", "= os.linesep + level*\" \" if len(elem): if not elem.text or not elem.text.strip():", "points are placed in top level group repeating block -> group with count", "ValueError: pass symbols.append({mdef.NAME: sid, mdef.VALUE: value}) if symbols: point_def[mdef.SYMBOLS] = symbols return point_def", "THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import os import xml.etree.ElementTree", "= repeating.attrib.get(SMDX_ATTR_NAME) if name is None: name = 'repeating' repeating_def = {mdef.NAME: name,", "not None: for a in m.findall('*'): if a.tag == SMDX_LABEL and a.text: fixed_def[mdef.LABEL]", "block points are placed in top level group repeating block -> group with", "e in element.findall('*'): if e.tag == SMDX_SYMBOL: sid = e.attrib.get(SMDX_ATTR_ID) value = e.text", "defined 'name' = 'repeating' points: all type, access, and mandatory attributes are preserved", "conditions: The above copyright notice and this permission notice shall be included in", "for model len - model len has no value specified in the model", "THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "SMDX_TYPE_PAD, SMDX_TYPE_INT32, SMDX_TYPE_UINT32, SMDX_TYPE_ACC32, SMDX_TYPE_ENUM32, SMDX_TYPE_BITFIELD32, SMDX_TYPE_IPADDR, SMDX_TYPE_INT64, SMDX_TYPE_UINT64, SMDX_TYPE_ACC64, SMDX_TYPE_IPV6ADDR, SMDX_TYPE_FLOAT32, SMDX_TYPE_STRING,", "len(elem): if not elem.text or not elem.text.strip(): elem.text = i + \" \"", "in e.findall(SMDX_POINT): pid = p.attrib.get(SMDX_ATTR_ID) label = desc = notes = None for", "%s' % access) if access == SMDX_ACCESS_RW: point_def[mdef.ACCESS] = smdx_access_types.get(access) units = element.attrib.get(SMDX_ATTR_UNITS)", "m is None: raise mdef.ModelDefinitionError('Model definition not found') try: mid = mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID)) except", "smdx_type_types = [ SMDX_TYPE_INT16, SMDX_TYPE_UINT16, SMDX_TYPE_COUNT, SMDX_TYPE_ACC16, SMDX_TYPE_ENUM16, SMDX_TYPE_BITFIELD16, SMDX_TYPE_PAD, SMDX_TYPE_INT32, SMDX_TYPE_UINT32, SMDX_TYPE_ACC32,", "attribute for point: %s' % pid) elif ptype not in smdx_type_types: raise mdef.ModelDefinitionError('Unknown", "type attributes based on an element tree model type element contained in an", "if notes: point_def[mdef.DETAIL] = notes model_def = {'id': mid, 'group': fixed_def} return model_def", "root = tree.getroot() return(from_smdx(root)) def from_smdx(element): \"\"\" Sets the model type attributes based", "mdef.ModelDefinitionError('Unknown mandatory type: %s' % mandatory) if mandatory == SMDX_MANDATORY_TRUE: point_def[mdef.MANDATORY] = smdx_mandatory_types.get(mandatory)", "= '.xml' def to_smdx_filename(model_id): return '%s%05d%s' % (SMDX_PREFIX, int(model_id), SMDX_EXT) def model_filename_to_id(filename): f", "FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "= mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID)) except ValueError: raise mdef.ModelDefinitionError('Invalid model id: %s' % m.attrib.get(SMDX_ATTR_ID)) name =", "and a.text: fixed_def[mdef.DETAIL] = a.text for p in e.findall(SMDX_POINT): pid = p.attrib.get(SMDX_ATTR_ID) label", "name = 'model_' + str(mid) model_def[mdef.NAME] = name strings = element.find(SMDX_STRINGS) # create", "mdef.MANDATORY_TRUE} smdx_type_types = [ SMDX_TYPE_INT16, SMDX_TYPE_UINT16, SMDX_TYPE_COUNT, SMDX_TYPE_ACC16, SMDX_TYPE_ENUM16, SMDX_TYPE_BITFIELD16, SMDX_TYPE_PAD, SMDX_TYPE_INT32, SMDX_TYPE_UINT32,", "mdef.DESCRIPTION: 'Model identifier', mdef.LABEL: 'Model ID', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE:", "value specified in the model definition fixed block points are placed in top", "ptype not in smdx_type_types: raise mdef.ModelDefinitionError('Unknown point type %s for point %s' %", "elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail", "ValueError: raise mdef.ModelDefinitionError('Invalid model id: %s' % m.attrib.get(SMDX_ATTR_ID)) name = m.attrib.get(SMDX_ATTR_NAME) if name", "\"\"\" Copyright (C) 2020 SunSpec Alliance Permission is hereby granted, free of charge,", "create top level group with ID and L points fixed_def = {mdef.NAME: name,", "for model ID and 'value' is the model ID value as a number", "is None: raise mdef.ModelDefinitionError('Missing point id attribute') point_def[mdef.NAME] = pid ptype = element.attrib.get(SMDX_ATTR_TYPE)", "def from_smdx(element): \"\"\" Sets the model type attributes based on an element tree", "= sf # if scale factor is an number, convert to correct type", "e.find(SMDX_MODEL) if m is not None: for a in m.findall('*'): if a.tag ==", "None: raise mdef.ModelDefinitionError('Missing len attribute for point: %s' % pid) point_def[mdef.SIZE] = plen", "is None: name = 'repeating' repeating_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.COUNT: 0}", "'name' = 'repeating' points: all type, access, and mandatory attributes are preserved point", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT", "the Software is furnished to do so, subject to the following conditions: The", "= None for a in p.findall('*'): if a.tag == SMDX_LABEL and a.text: label", "a in m.findall('*'): if a.tag == SMDX_LABEL and a.text: fixed_def[mdef.LABEL] = a.text elif", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING", "the model definition fixed block points are placed in top level group repeating", "repeating block type definition') repeating = b else: raise mdef.ModelDefinitionError('Invalid block type: %s'", "attributes are preserved point symbol map to the symbol object and placed in", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT", "'true' smdx_access_types = {SMDX_ACCESS_R: mdef.ACCESS_R, SMDX_ACCESS_RW: mdef.ACCESS_RW} smdx_mandatory_types = {SMDX_MANDATORY_FALSE: mdef.MANDATORY_FALSE, SMDX_MANDATORY_TRUE: mdef.MANDATORY_TRUE}", "if *element* is a subelement of the 'strings' definintion within the model definition.", "Element Tree model type element. \"\"\" model_def = {} m = element.find(SMDX_MODEL) if", "point_def[mdef.TYPE] = ptype plen = mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN)) if ptype == SMDX_TYPE_STRING: if plen is", "SMDX_MANDATORY_FALSE = 'false' SMDX_MANDATORY_TRUE = 'true' smdx_access_types = {SMDX_ACCESS_R: mdef.ACCESS_R, SMDX_ACCESS_RW: mdef.ACCESS_RW} smdx_mandatory_types", "if notes: point_def[mdef.DETAIL] = notes point_def = repeating_points_map.get(pid) if point_def is not None:", "if access == SMDX_ACCESS_RW: point_def[mdef.ACCESS] = smdx_access_types.get(access) units = element.attrib.get(SMDX_ATTR_UNITS) if units: point_def[mdef.UNITS]", "model definition. Parameters: element : Element Tree model type element. \"\"\" model_def =", "or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if", "SunSpec Alliance Permission is hereby granted, free of charge, to any person obtaining", "type: %s' % btype) fixed_points_map = {} if fixed is not None: points", "not in repeating_points_map: repeating_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s'", "m = element.find(SMDX_MODEL) if m is None: raise mdef.ModelDefinitionError('Model definition not found') try:", "element.findall('*'): if e.tag == SMDX_SYMBOL: sid = e.attrib.get(SMDX_ATTR_ID) value = e.text try: value", "model type element contained in an SMDX model definition. Parameters: element : Element", "= from_smdx_point(e) if point_def[mdef.NAME] not in fixed_points_map: fixed_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise", "OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR", "to the following conditions: The above copyright notice and this permission notice shall", "Software, and to permit persons to whom the Software is furnished to do", "of groups) repeating block 'name' -> group 'name', if no 'name' is defined", "= 'symbol' SMDX_COMMENT = 'comment' SMDX_STRINGS = 'strings' SMDX_ATTR_LOCALE = 'locale' SMDX_LABEL =", "if scale factor is an number, convert to correct type value = mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE))", "element tree point element contained in an SMDX model definition. Parameters: element :", "not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not", "point element contained in an SMDX model definition. Parameters: element : Element Tree", "import sunspec2.mdef as mdef SMDX_ROOT = 'sunSpecModels' SMDX_MODEL = mdef.MODEL SMDX_BLOCK = 'block'", "= i for elem in elem: indent(elem, level+1) if not elem.tail or not", "on an element tree model type element contained in an SMDX model definition.", "a.text elif a.tag == SMDX_NOTES and a.text: fixed_def[mdef.DETAIL] = a.text for p in", "% btype) fixed_points_map = {} if fixed is not None: points = []", "SMDX_LABEL = mdef.LABEL SMDX_DESCRIPTION = 'description' SMDX_NOTES = 'notes' SMDX_DETAIL = mdef.DETAIL SMDX_TYPE_INT16", "an number, convert to correct type value = mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE)) if value is not", "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "'sunSpecModels' SMDX_MODEL = mdef.MODEL SMDX_BLOCK = 'block' SMDX_POINT = 'point' SMDX_ATTR_VERS = 'v'", "point_def[mdef.SYMBOLS] = symbols return point_def def indent(elem, level=0): i = os.linesep + level*\"", "element.find(SMDX_STRINGS) # create top level group with ID and L points fixed_def =", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED", "SMDX_SYMBOL: sid = e.attrib.get(SMDX_ATTR_ID) value = e.text try: value = int(value) except ValueError:", "''' smdx to json mapping: fixed block -> top level group model 'name'", "SMDX_TYPE_ACC64, SMDX_TYPE_IPV6ADDR, SMDX_TYPE_FLOAT32, SMDX_TYPE_STRING, SMDX_TYPE_SUNSSF, SMDX_TYPE_EUI48 ] SMDX_PREFIX = 'smdx_' SMDX_EXT = '.xml'", "point_def[mdef.ACCESS] = smdx_access_types.get(access) units = element.attrib.get(SMDX_ATTR_UNITS) if units: point_def[mdef.UNITS] = units # if", "= mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN)) if ptype == SMDX_TYPE_STRING: if plen is None: raise mdef.ModelDefinitionError('Missing len", "SMDX_EXT) def model_filename_to_id(filename): f = filename if '.' in f: f = os.path.splitext(f)[0]", "elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()):", "an number, convert to correct type sf = mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF)) if sf is not", "is not None: for a in m.findall('*'): if a.tag == SMDX_LABEL and a.text:", "symbol 'name' attribute -> symbol object 'name' symbol element content -> symbol object", "type definition') repeating = b else: raise mdef.ModelDefinitionError('Invalid block type: %s' % btype)", "no value specified in the model definition fixed block points are placed in", "mdef.TYPE SMDX_ATTR_COUNT = mdef.COUNT SMDX_ATTR_VALUE = mdef.VALUE SMDX_ATTR_TYPE_FIXED = 'fixed' SMDX_ATTR_TYPE_REPEATING = 'repeating'", "elem.text.strip(): elem.text = i + \" \" if not elem.tail or not elem.tail.strip():", "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "SMDX_ATTR_COUNT = mdef.COUNT SMDX_ATTR_VALUE = mdef.VALUE SMDX_ATTR_TYPE_FIXED = 'fixed' SMDX_ATTR_TYPE_REPEATING = 'repeating' SMDX_ATTR_OFFSET", "person obtaining a copy of this software and associated documentation files (the \"Software\"),", "in top level group repeating block -> group with count = 0 (indicates", "= 'notes' SMDX_DETAIL = mdef.DETAIL SMDX_TYPE_INT16 = mdef.TYPE_INT16 SMDX_TYPE_UINT16 = mdef.TYPE_UINT16 SMDX_TYPE_COUNT =", "SMDX_ATTR_ID = 'id' SMDX_ATTR_LEN = 'len' SMDX_ATTR_NAME = mdef.NAME SMDX_ATTR_TYPE = mdef.TYPE SMDX_ATTR_COUNT", "= mdef.TYPE_SUNSSF SMDX_TYPE_EUI48 = mdef.TYPE_EUI48 SMDX_ACCESS_R = 'r' SMDX_ACCESS_RW = 'rw' SMDX_MANDATORY_FALSE =", "SMDX_TYPE_FLOAT32, SMDX_TYPE_STRING, SMDX_TYPE_SUNSSF, SMDX_TYPE_EUI48 ] SMDX_PREFIX = 'smdx_' SMDX_EXT = '.xml' def to_smdx_filename(model_id):", "label if desc: point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL] = notes model_def =", "group 'name' ID point is created for model ID and 'value' is the", "not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem,", "SMDX_TYPE_ACC16, SMDX_TYPE_ENUM16, SMDX_TYPE_BITFIELD16, SMDX_TYPE_PAD, SMDX_TYPE_INT32, SMDX_TYPE_UINT32, SMDX_TYPE_ACC32, SMDX_TYPE_ENUM32, SMDX_TYPE_BITFIELD32, SMDX_TYPE_IPADDR, SMDX_TYPE_INT64, SMDX_TYPE_UINT64, SMDX_TYPE_ACC64,", "SMDX_ACCESS_RW = 'rw' SMDX_MANDATORY_FALSE = 'false' SMDX_MANDATORY_TRUE = 'true' smdx_access_types = {SMDX_ACCESS_R: mdef.ACCESS_R,", "a subelement of the 'strings' definintion within the model definition. \"\"\" point_def =", "'.' in f: f = os.path.splitext(f)[0] try: mid = int(f.rsplit('_', 1)[1]) except ValueError:", "in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED", "to json mapping: fixed block -> top level group model 'name' attribute ->", "object and placed in the symbols list for the point symbol 'name' attribute", "mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID)) except ValueError: raise mdef.ModelDefinitionError('Invalid model id: %s' % m.attrib.get(SMDX_ATTR_ID)) name = m.attrib.get(SMDX_ATTR_NAME)", "modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to", "mandatory not in smdx_mandatory_types: raise mdef.ModelDefinitionError('Unknown mandatory type: %s' % mandatory) if mandatory", "mdef.ModelDefinitionError('Missing type attribute for point: %s' % pid) elif ptype not in smdx_type_types:", "} repeating_def = None fixed = None repeating = None for b in", "if points: fixed_def[mdef.POINTS].extend(points) repeating_points_map = {} if repeating is not None: name =", "ID value as a number L point is created for model len -", "sf is not None: point_def[mdef.SF] = sf # if scale factor is an", "in f: f = os.path.splitext(f)[0] try: mid = int(f.rsplit('_', 1)[1]) except ValueError: raise", "{SMDX_ACCESS_R: mdef.ACCESS_R, SMDX_ACCESS_RW: mdef.ACCESS_RW} smdx_mandatory_types = {SMDX_MANDATORY_FALSE: mdef.MANDATORY_FALSE, SMDX_MANDATORY_TRUE: mdef.MANDATORY_TRUE} smdx_type_types = [", "type %s for point %s' % (ptype, pid)) point_def[mdef.TYPE] = ptype plen =", "SMDX_TYPE_IPADDR = mdef.TYPE_IPADDR SMDX_TYPE_INT64 = mdef.TYPE_INT64 SMDX_TYPE_UINT64 = mdef.TYPE_UINT64 SMDX_TYPE_ACC64 = mdef.TYPE_ACC64 SMDX_TYPE_IPV6ADDR", "no 'name' is defined 'name' = 'repeating' points: all type, access, and mandatory", "elif ptype not in smdx_type_types: raise mdef.ModelDefinitionError('Unknown point type %s for point %s'", "== SMDX_ATTR_TYPE_FIXED: if fixed is not None: raise mdef.ModelDefinitionError('Duplicate fixed block type definition')", "fixed = None repeating = None for b in m.findall(SMDX_BLOCK): btype = b.attrib.get(SMDX_ATTR_TYPE,", "is an number, convert to correct type sf = mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF)) if sf is", "% point_def[mdef.NAME]) if points: repeating_def[mdef.POINTS] = points fixed_def[mdef.GROUPS] = [repeating_def] e = element.find(SMDX_STRINGS)", "not in smdx_type_types: raise mdef.ModelDefinitionError('Unknown point type %s for point %s' % (ptype,", "top level group model 'name' attribute -> group 'name' ID point is created", "mdef.ModelDefinitionError('Error extracting model id from filename') return mid ''' smdx to json mapping:", "import os import xml.etree.ElementTree as ET import sunspec2.mdef as mdef SMDX_ROOT = 'sunSpecModels'", "mdef.TYPE_ENUM16 SMDX_TYPE_BITFIELD16 = mdef.TYPE_BITFIELD16 SMDX_TYPE_PAD = mdef.TYPE_PAD SMDX_TYPE_INT32 = mdef.TYPE_INT32 SMDX_TYPE_UINT32 = mdef.TYPE_UINT32", "pid is None: raise mdef.ModelDefinitionError('Missing point id attribute') point_def[mdef.NAME] = pid ptype =", "= mdef.TYPE_PAD SMDX_TYPE_INT32 = mdef.TYPE_INT32 SMDX_TYPE_UINT32 = mdef.TYPE_UINT32 SMDX_TYPE_ACC32 = mdef.TYPE_ACC32 SMDX_TYPE_ENUM32 =", "= mdef.TYPE_INT32 SMDX_TYPE_UINT32 = mdef.TYPE_UINT32 SMDX_TYPE_ACC32 = mdef.TYPE_ACC32 SMDX_TYPE_ENUM32 = mdef.TYPE_ENUM32 SMDX_TYPE_BITFIELD32 =", "fixed_def[mdef.DESCRIPTION] = a.text elif a.tag == SMDX_NOTES and a.text: fixed_def[mdef.DETAIL] = a.text for", "on an element tree point element contained in an SMDX model definition. Parameters:", "is created for model ID and 'value' is the model ID value as", "a.tag == SMDX_NOTES and a.text: fixed_def[mdef.DETAIL] = a.text for p in e.findall(SMDX_POINT): pid", "e.attrib.get(SMDX_ATTR_ID) value = e.text try: value = int(value) except ValueError: pass symbols.append({mdef.NAME: sid,", "factor is an number, convert to correct type value = mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE)) if value", "element : Element Tree model type element. \"\"\" model_def = {} m =", "except ValueError: raise mdef.ModelDefinitionError('Invalid model id: %s' % m.attrib.get(SMDX_ATTR_ID)) name = m.attrib.get(SMDX_ATTR_NAME) if", "in an SMDX model definition. Parameters: element : Element Tree point type element.", "tree point element contained in an SMDX model definition. Parameters: element : Element", "fixed_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if", "are placed in top level group repeating block -> group with count =", "fixed block points are placed in top level group repeating block -> group", "= mdef.TYPE_BITFIELD16 SMDX_TYPE_PAD = mdef.TYPE_PAD SMDX_TYPE_INT32 = mdef.TYPE_INT32 SMDX_TYPE_UINT32 = mdef.TYPE_UINT32 SMDX_TYPE_ACC32 =", "int(value) except ValueError: pass symbols.append({mdef.NAME: sid, mdef.VALUE: value}) if symbols: point_def[mdef.SYMBOLS] = symbols", "sf # if scale factor is an number, convert to correct type value", "mdef.TYPE_INT16 SMDX_TYPE_UINT16 = mdef.TYPE_UINT16 SMDX_TYPE_COUNT = mdef.TYPE_COUNT SMDX_TYPE_ACC16 = mdef.TYPE_ACC16 SMDX_TYPE_ENUM16 = mdef.TYPE_ENUM16", "to any person obtaining a copy of this software and associated documentation files", "None: name = repeating.attrib.get(SMDX_ATTR_NAME) if name is None: name = 'repeating' repeating_def =", "a.tag == SMDX_NOTES and a.text: notes = a.text point_def = fixed_points_map.get(pid) if point_def", "IN THE SOFTWARE. \"\"\" import os import xml.etree.ElementTree as ET import sunspec2.mdef as", "point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if points: fixed_def[mdef.POINTS].extend(points)", "a copy of this software and associated documentation files (the \"Software\"), to deal", "Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF", "-> group 'name' ID point is created for model ID and 'value' is", "in smdx_mandatory_types: raise mdef.ModelDefinitionError('Unknown mandatory type: %s' % mandatory) if mandatory == SMDX_MANDATORY_TRUE:", "mdef.VALUE: mid, mdef.DESCRIPTION: 'Model identifier', mdef.LABEL: 'Model ID', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC:", "int(model_id), SMDX_EXT) def model_filename_to_id(filename): f = filename if '.' in f: f =", "and to permit persons to whom the Software is furnished to do so,", "subelement of the 'strings' definintion within the model definition. \"\"\" point_def = {}", "point id attribute') point_def[mdef.NAME] = pid ptype = element.attrib.get(SMDX_ATTR_TYPE) if ptype is None:", "(indicates model len shoud be used to determine number of groups) repeating block", "ID', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16}, {mdef.NAME: 'L', mdef.DESCRIPTION: 'Model", "= 'r' SMDX_ACCESS_RW = 'rw' SMDX_MANDATORY_FALSE = 'false' SMDX_MANDATORY_TRUE = 'true' smdx_access_types =", "determine number of groups) repeating block 'name' -> group 'name', if no 'name'", "-> top level group model 'name' attribute -> group 'name' ID point is", "SMDX_ATTR_LOCALE = 'locale' SMDX_LABEL = mdef.LABEL SMDX_DESCRIPTION = 'description' SMDX_NOTES = 'notes' SMDX_DETAIL", "None: raise mdef.ModelDefinitionError('Missing type attribute for point: %s' % pid) elif ptype not", "# if scale factor is an number, convert to correct type value =", "access) if access == SMDX_ACCESS_RW: point_def[mdef.ACCESS] = smdx_access_types.get(access) units = element.attrib.get(SMDX_ATTR_UNITS) if units:", "an element tree model type element contained in an SMDX model definition. Parameters:", "fixed_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.POINTS: [ {mdef.NAME: 'ID', mdef.VALUE: mid, mdef.DESCRIPTION:", "SMDX_SYMBOL = 'symbol' SMDX_COMMENT = 'comment' SMDX_STRINGS = 'strings' SMDX_ATTR_LOCALE = 'locale' SMDX_LABEL", "i = os.linesep + level*\" \" if len(elem): if not elem.text or not", "SMDX_TYPE_UINT64 = mdef.TYPE_UINT64 SMDX_TYPE_ACC64 = mdef.TYPE_ACC64 SMDX_TYPE_IPV6ADDR = mdef.TYPE_IPV6ADDR SMDX_TYPE_FLOAT32 = mdef.TYPE_FLOAT32 SMDX_TYPE_STRING", "mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16} ] } repeating_def = None", "'rw' SMDX_MANDATORY_FALSE = 'false' SMDX_MANDATORY_TRUE = 'true' smdx_access_types = {SMDX_ACCESS_R: mdef.ACCESS_R, SMDX_ACCESS_RW: mdef.ACCESS_RW}", "point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL] = notes point_def = repeating_points_map.get(pid) if point_def", "copy of this software and associated documentation files (the \"Software\"), to deal in", "fixed is not None: points = [] for e in fixed.findall(SMDX_POINT): point_def =", "label if desc: point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL] = notes point_def =", "= smdx_access_types.get(access) units = element.attrib.get(SMDX_ATTR_UNITS) if units: point_def[mdef.UNITS] = units # if scale", "= mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF)) if sf is not None: point_def[mdef.SF] = sf # if scale", "mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16} ] } repeating_def = None fixed = None", "SMDX_NOTES and a.text: notes = a.text point_def = fixed_points_map.get(pid) if point_def is not", "mdef.TYPE_BITFIELD16 SMDX_TYPE_PAD = mdef.TYPE_PAD SMDX_TYPE_INT32 = mdef.TYPE_INT32 SMDX_TYPE_UINT32 = mdef.TYPE_UINT32 SMDX_TYPE_ACC32 = mdef.TYPE_ACC32", "OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "% mandatory) if mandatory == SMDX_MANDATORY_TRUE: point_def[mdef.MANDATORY] = smdx_mandatory_types.get(mandatory) access = element.attrib.get(SMDX_ATTR_ACCESS, SMDX_ACCESS_R)", "SMDX_ATTR_TYPE_REPEATING = 'repeating' SMDX_ATTR_OFFSET = 'offset' SMDX_ATTR_MANDATORY = mdef.MANDATORY SMDX_ATTR_ACCESS = mdef.ACCESS SMDX_ATTR_SF", "if point_def is not None: if label: point_def[mdef.LABEL] = label if desc: point_def[mdef.DESCRIPTION]", "= 'offset' SMDX_ATTR_MANDATORY = mdef.MANDATORY SMDX_ATTR_ACCESS = mdef.ACCESS SMDX_ATTR_SF = mdef.SF SMDX_ATTR_UNITS =", "count = 0 (indicates model len shoud be used to determine number of", "repeating block 'name' -> group 'name', if no 'name' is defined 'name' =", "{mdef.NAME: 'ID', mdef.VALUE: mid, mdef.DESCRIPTION: 'Model identifier', mdef.LABEL: 'Model ID', mdef.SIZE: 1, mdef.MANDATORY:", "all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS", "SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "= mdef.point_type_info.get(ptype)['len'] mandatory = element.attrib.get(SMDX_ATTR_MANDATORY, SMDX_MANDATORY_FALSE) if mandatory not in smdx_mandatory_types: raise mdef.ModelDefinitionError('Unknown", "level group repeating block -> group with count = 0 (indicates model len", "filename if '.' in f: f = os.path.splitext(f)[0] try: mid = int(f.rsplit('_', 1)[1])", "SMDX_MANDATORY_TRUE: point_def[mdef.MANDATORY] = smdx_mandatory_types.get(mandatory) access = element.attrib.get(SMDX_ATTR_ACCESS, SMDX_ACCESS_R) if access not in smdx_access_types:", "scale factor is an number, convert to correct type value = mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE)) if", "f = os.path.splitext(f)[0] try: mid = int(f.rsplit('_', 1)[1]) except ValueError: raise mdef.ModelDefinitionError('Error extracting", "if btype == SMDX_ATTR_TYPE_FIXED: if fixed is not None: raise mdef.ModelDefinitionError('Duplicate fixed block", "2020 SunSpec Alliance Permission is hereby granted, free of charge, to any person", "SMDX_TYPE_BITFIELD16 = mdef.TYPE_BITFIELD16 SMDX_TYPE_PAD = mdef.TYPE_PAD SMDX_TYPE_INT32 = mdef.TYPE_INT32 SMDX_TYPE_UINT32 = mdef.TYPE_UINT32 SMDX_TYPE_ACC32", "an SMDX model definition. Parameters: element : Element Tree model type element. \"\"\"", "+ str(mid) model_def[mdef.NAME] = name strings = element.find(SMDX_STRINGS) # create top level group", "%s' % pid) elif ptype not in smdx_type_types: raise mdef.ModelDefinitionError('Unknown point type %s", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the", "'Model ID', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16}, {mdef.NAME: 'L', mdef.DESCRIPTION:", "L point is created for model len - model len has no value", "def indent(elem, level=0): i = os.linesep + level*\" \" if len(elem): if not", "list for the point symbol 'name' attribute -> symbol object 'name' symbol element", "mdef.ACCESS SMDX_ATTR_SF = mdef.SF SMDX_ATTR_UNITS = mdef.UNITS SMDX_SYMBOL = 'symbol' SMDX_COMMENT = 'comment'", "plen is None: raise mdef.ModelDefinitionError('Missing len attribute for point: %s' % pid) point_def[mdef.SIZE]", "symbols = [] for e in element.findall('*'): if e.tag == SMDX_SYMBOL: sid =", "OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + \"", "mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16} ] } repeating_def = None fixed = None repeating =", "= e.find(SMDX_MODEL) if m is not None: for a in m.findall('*'): if a.tag", "in p.findall('*'): if a.tag == SMDX_LABEL and a.text: label = a.text elif a.tag", "notes: point_def[mdef.DETAIL] = notes model_def = {'id': mid, 'group': fixed_def} return model_def def", "WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "SMDX_ATTR_VALUE = mdef.VALUE SMDX_ATTR_TYPE_FIXED = 'fixed' SMDX_ATTR_TYPE_REPEATING = 'repeating' SMDX_ATTR_OFFSET = 'offset' SMDX_ATTR_MANDATORY", "for a in m.findall('*'): if a.tag == SMDX_LABEL and a.text: fixed_def[mdef.LABEL] = a.text", "'name' attribute -> group 'name' ID point is created for model ID and", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS", "= label if desc: point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL] = notes model_def", "'Model length', mdef.LABEL: 'Model Length', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16}", "type element contained in an SMDX model definition. Parameters: element : Element Tree", "mdef.TYPE_ENUM32 SMDX_TYPE_BITFIELD32 = mdef.TYPE_BITFIELD32 SMDX_TYPE_IPADDR = mdef.TYPE_IPADDR SMDX_TYPE_INT64 = mdef.TYPE_INT64 SMDX_TYPE_UINT64 = mdef.TYPE_UINT64", "shoud be used to determine number of groups) repeating block 'name' -> group", "element.find(SMDX_MODEL) if m is None: raise mdef.ModelDefinitionError('Model definition not found') try: mid =", "definition. Parameters: element : Element Tree point type element. strings : Indicates if", "SMDX_TYPE_BITFIELD32, SMDX_TYPE_IPADDR, SMDX_TYPE_INT64, SMDX_TYPE_UINT64, SMDX_TYPE_ACC64, SMDX_TYPE_IPV6ADDR, SMDX_TYPE_FLOAT32, SMDX_TYPE_STRING, SMDX_TYPE_SUNSSF, SMDX_TYPE_EUI48 ] SMDX_PREFIX =", "= e.text try: value = int(value) except ValueError: pass symbols.append({mdef.NAME: sid, mdef.VALUE: value})", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT", "json mapping: fixed block -> top level group model 'name' attribute -> group", "= points fixed_def[mdef.GROUPS] = [repeating_def] e = element.find(SMDX_STRINGS) if e.attrib.get(SMDX_ATTR_ID) == str(mid): m", "any person obtaining a copy of this software and associated documentation files (the", "a.text elif a.tag == SMDX_NOTES and a.text: notes = a.text point_def = fixed_points_map.get(pid)", "within the model definition. \"\"\" point_def = {} pid = element.attrib.get(SMDX_ATTR_ID) if pid", "group 'name', if no 'name' is defined 'name' = 'repeating' points: all type,", "and a.text: notes = a.text point_def = fixed_points_map.get(pid) if point_def is not None:", "\"\"\" import os import xml.etree.ElementTree as ET import sunspec2.mdef as mdef SMDX_ROOT =", "smdx_mandatory_types = {SMDX_MANDATORY_FALSE: mdef.MANDATORY_FALSE, SMDX_MANDATORY_TRUE: mdef.MANDATORY_TRUE} smdx_type_types = [ SMDX_TYPE_INT16, SMDX_TYPE_UINT16, SMDX_TYPE_COUNT, SMDX_TYPE_ACC16,", "if mandatory == SMDX_MANDATORY_TRUE: point_def[mdef.MANDATORY] = smdx_mandatory_types.get(mandatory) access = element.attrib.get(SMDX_ATTR_ACCESS, SMDX_ACCESS_R) if access", "attribute for point: %s' % pid) point_def[mdef.SIZE] = plen else: point_def[mdef.SIZE] = mdef.point_type_info.get(ptype)['len']", "m.attrib.get(SMDX_ATTR_NAME) if name is None: name = 'model_' + str(mid) model_def[mdef.NAME] = name", "THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "'Model identifier', mdef.LABEL: 'Model ID', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16},", "group model 'name' attribute -> group 'name' ID point is created for model", "the Software, and to permit persons to whom the Software is furnished to", "os.linesep + level*\" \" if len(elem): if not elem.text or not elem.text.strip(): elem.text", "from_smdx_file(filename): tree = ET.parse(filename) root = tree.getroot() return(from_smdx(root)) def from_smdx(element): \"\"\" Sets the", "definition. Parameters: element : Element Tree model type element. \"\"\" model_def = {}", "placed in top level group repeating block -> group with count = 0", "definition: %s' % point_def[mdef.NAME]) if points: fixed_def[mdef.POINTS].extend(points) repeating_points_map = {} if repeating is", "copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",", "\"\"\" Sets the model type attributes based on an element tree model type", "for the point symbol 'name' attribute -> symbol object 'name' symbol element content", "def from_smdx_point(element): \"\"\" Sets the point attributes based on an element tree point", "-> group with count = 0 (indicates model len shoud be used to", "= 'sunSpecModels' SMDX_MODEL = mdef.MODEL SMDX_BLOCK = 'block' SMDX_POINT = 'point' SMDX_ATTR_VERS =", "SMDX_ATTR_OFFSET = 'offset' SMDX_ATTR_MANDATORY = mdef.MANDATORY SMDX_ATTR_ACCESS = mdef.ACCESS SMDX_ATTR_SF = mdef.SF SMDX_ATTR_UNITS", "elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail =", "fixed block type definition') fixed = b elif btype == SMDX_ATTR_TYPE_REPEATING: if repeating", "ptype == SMDX_TYPE_STRING: if plen is None: raise mdef.ModelDefinitionError('Missing len attribute for point:", "point_def[mdef.NAME] not in fixed_points_map: fixed_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition:", "SMDX_TYPE_ENUM16, SMDX_TYPE_BITFIELD16, SMDX_TYPE_PAD, SMDX_TYPE_INT32, SMDX_TYPE_UINT32, SMDX_TYPE_ACC32, SMDX_TYPE_ENUM32, SMDX_TYPE_BITFIELD32, SMDX_TYPE_IPADDR, SMDX_TYPE_INT64, SMDX_TYPE_UINT64, SMDX_TYPE_ACC64, SMDX_TYPE_IPV6ADDR,", "in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i", "block 'name' -> group 'name', if no 'name' is defined 'name' = 'repeating'", "= mdef.TYPE_ENUM16 SMDX_TYPE_BITFIELD16 = mdef.TYPE_BITFIELD16 SMDX_TYPE_PAD = mdef.TYPE_PAD SMDX_TYPE_INT32 = mdef.TYPE_INT32 SMDX_TYPE_UINT32 =", "'repeating' SMDX_ATTR_OFFSET = 'offset' SMDX_ATTR_MANDATORY = mdef.MANDATORY SMDX_ATTR_ACCESS = mdef.ACCESS SMDX_ATTR_SF = mdef.SF", "{'id': mid, 'group': fixed_def} return model_def def from_smdx_point(element): \"\"\" Sets the point attributes", "do so, subject to the following conditions: The above copyright notice and this", "value symbols = [] for e in element.findall('*'): if e.tag == SMDX_SYMBOL: sid", "mid, 'group': fixed_def} return model_def def from_smdx_point(element): \"\"\" Sets the point attributes based", "is furnished to do so, subject to the following conditions: The above copyright", "name = repeating.attrib.get(SMDX_ATTR_NAME) if name is None: name = 'repeating' repeating_def = {mdef.NAME:", "repeating = b else: raise mdef.ModelDefinitionError('Invalid block type: %s' % btype) fixed_points_map =", "= b else: raise mdef.ModelDefinitionError('Invalid block type: %s' % btype) fixed_points_map = {}", "type element. strings : Indicates if *element* is a subelement of the 'strings'", "attribute') point_def[mdef.NAME] = pid ptype = element.attrib.get(SMDX_ATTR_TYPE) if ptype is None: raise mdef.ModelDefinitionError('Missing", "SMDX_NOTES and a.text: fixed_def[mdef.DETAIL] = a.text for p in e.findall(SMDX_POINT): pid = p.attrib.get(SMDX_ATTR_ID)", "fixed_def[mdef.GROUPS] = [repeating_def] e = element.find(SMDX_STRINGS) if e.attrib.get(SMDX_ATTR_ID) == str(mid): m = e.find(SMDX_MODEL)", "definition not found') try: mid = mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID)) except ValueError: raise mdef.ModelDefinitionError('Invalid model id:", "points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if points: fixed_def[mdef.POINTS].extend(points) repeating_points_map", "attributes 'label', 'desc', 'detail' ''' def from_smdx_file(filename): tree = ET.parse(filename) root = tree.getroot()", "repeating_points_map = {} if repeating is not None: name = repeating.attrib.get(SMDX_ATTR_NAME) if name", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR", "SMDX_TYPE_FLOAT32 = mdef.TYPE_FLOAT32 SMDX_TYPE_STRING = mdef.TYPE_STRING SMDX_TYPE_SUNSSF = mdef.TYPE_SUNSSF SMDX_TYPE_EUI48 = mdef.TYPE_EUI48 SMDX_ACCESS_R", "group with count = 0 (indicates model len shoud be used to determine", "\"\"\" model_def = {} m = element.find(SMDX_MODEL) if m is None: raise mdef.ModelDefinitionError('Model", "return mid ''' smdx to json mapping: fixed block -> top level group", "e.text try: value = int(value) except ValueError: pass symbols.append({mdef.NAME: sid, mdef.VALUE: value}) if", "(the \"Software\"), to deal in the Software without restriction, including without limitation the", "= 'block' SMDX_POINT = 'point' SMDX_ATTR_VERS = 'v' SMDX_ATTR_ID = 'id' SMDX_ATTR_LEN =", "if '.' in f: f = os.path.splitext(f)[0] try: mid = int(f.rsplit('_', 1)[1]) except", "to point attributes 'label', 'desc', 'detail' ''' def from_smdx_file(filename): tree = ET.parse(filename) root", "mdef.TYPE_EUI48 SMDX_ACCESS_R = 'r' SMDX_ACCESS_RW = 'rw' SMDX_MANDATORY_FALSE = 'false' SMDX_MANDATORY_TRUE = 'true'", "= int(value) except ValueError: pass symbols.append({mdef.NAME: sid, mdef.VALUE: value}) if symbols: point_def[mdef.SYMBOLS] =", "points fixed_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.POINTS: [ {mdef.NAME: 'ID', mdef.VALUE: mid,", "access == SMDX_ACCESS_RW: point_def[mdef.ACCESS] = smdx_access_types.get(access) units = element.attrib.get(SMDX_ATTR_UNITS) if units: point_def[mdef.UNITS] =", "elem.text or not elem.text.strip(): elem.text = i + \" \" if not elem.tail", "to permit persons to whom the Software is furnished to do so, subject", "to correct type value = mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE)) if value is not None: point_def[mdef.VALUE] =", "'%s%05d%s' % (SMDX_PREFIX, int(model_id), SMDX_EXT) def model_filename_to_id(filename): f = filename if '.' in", "b in m.findall(SMDX_BLOCK): btype = b.attrib.get(SMDX_ATTR_TYPE, SMDX_ATTR_TYPE_FIXED) if btype == SMDX_ATTR_TYPE_FIXED: if fixed", "point_def = {} pid = element.attrib.get(SMDX_ATTR_ID) if pid is None: raise mdef.ModelDefinitionError('Missing point", "0} points = [] for e in repeating.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME]", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER", "Permission is hereby granted, free of charge, to any person obtaining a copy", "be included in all copies or substantial portions of the Software. THE SOFTWARE", "as mdef SMDX_ROOT = 'sunSpecModels' SMDX_MODEL = mdef.MODEL SMDX_BLOCK = 'block' SMDX_POINT =", "whom the Software is furnished to do so, subject to the following conditions:", "= 'v' SMDX_ATTR_ID = 'id' SMDX_ATTR_LEN = 'len' SMDX_ATTR_NAME = mdef.NAME SMDX_ATTR_TYPE =", "pid) point_def[mdef.SIZE] = plen else: point_def[mdef.SIZE] = mdef.point_type_info.get(ptype)['len'] mandatory = element.attrib.get(SMDX_ATTR_MANDATORY, SMDX_MANDATORY_FALSE) if", "= notes = None for a in p.findall('*'): if a.tag == SMDX_LABEL and", "= mdef.TYPE_IPADDR SMDX_TYPE_INT64 = mdef.TYPE_INT64 SMDX_TYPE_UINT64 = mdef.TYPE_UINT64 SMDX_TYPE_ACC64 = mdef.TYPE_ACC64 SMDX_TYPE_IPV6ADDR =", "group with ID and L points fixed_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.POINTS:", "= 'model_' + str(mid) model_def[mdef.NAME] = name strings = element.find(SMDX_STRINGS) # create top", "is a subelement of the 'strings' definintion within the model definition. \"\"\" point_def", "mandatory attributes are preserved point symbol map to the symbol object and placed", "DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "number L point is created for model len - model len has no", "repeating_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if", "e.attrib.get(SMDX_ATTR_ID) == str(mid): m = e.find(SMDX_MODEL) if m is not None: for a", "= mdef.ACCESS SMDX_ATTR_SF = mdef.SF SMDX_ATTR_UNITS = mdef.UNITS SMDX_SYMBOL = 'symbol' SMDX_COMMENT =", "= mdef.TYPE_INT64 SMDX_TYPE_UINT64 = mdef.TYPE_UINT64 SMDX_TYPE_ACC64 = mdef.TYPE_ACC64 SMDX_TYPE_IPV6ADDR = mdef.TYPE_IPV6ADDR SMDX_TYPE_FLOAT32 =", "and mandatory attributes are preserved point symbol map to the symbol object and", "mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE)) if value is not None: point_def[mdef.VALUE] = value symbols = [] for", "%s' % point_def[mdef.NAME]) if points: fixed_def[mdef.POINTS].extend(points) repeating_points_map = {} if repeating is not", "level group model 'name' attribute -> group 'name' ID point is created for", "element contained in an SMDX model definition. Parameters: element : Element Tree model", "name strings = element.find(SMDX_STRINGS) # create top level group with ID and L", "label: point_def[mdef.LABEL] = label if desc: point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL] =", "OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import os import", "e in repeating.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not in repeating_points_map: repeating_points_map[point_def[mdef.NAME]] =", "None: raise mdef.ModelDefinitionError('Missing point id attribute') point_def[mdef.NAME] = pid ptype = element.attrib.get(SMDX_ATTR_TYPE) if", "SMDX_ATTR_TYPE_FIXED: if fixed is not None: raise mdef.ModelDefinitionError('Duplicate fixed block type definition') fixed", "= 'len' SMDX_ATTR_NAME = mdef.NAME SMDX_ATTR_TYPE = mdef.TYPE SMDX_ATTR_COUNT = mdef.COUNT SMDX_ATTR_VALUE =", "= 'fixed' SMDX_ATTR_TYPE_REPEATING = 'repeating' SMDX_ATTR_OFFSET = 'offset' SMDX_ATTR_MANDATORY = mdef.MANDATORY SMDX_ATTR_ACCESS =", "[repeating_def] e = element.find(SMDX_STRINGS) if e.attrib.get(SMDX_ATTR_ID) == str(mid): m = e.find(SMDX_MODEL) if m", "mdef.TYPE_IPADDR SMDX_TYPE_INT64 = mdef.TYPE_INT64 SMDX_TYPE_UINT64 = mdef.TYPE_UINT64 SMDX_TYPE_ACC64 = mdef.TYPE_ACC64 SMDX_TYPE_IPV6ADDR = mdef.TYPE_IPV6ADDR", "SMDX model definition. Parameters: element : Element Tree model type element. \"\"\" model_def", "and associated documentation files (the \"Software\"), to deal in the Software without restriction,", "if ptype == SMDX_TYPE_STRING: if plen is None: raise mdef.ModelDefinitionError('Missing len attribute for", "without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF)) if sf is not None: point_def[mdef.SF] = sf # if scale factor", "groups) repeating block 'name' -> group 'name', if no 'name' is defined 'name'", "name is None: name = 'repeating' repeating_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.COUNT:", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE", "'comment' SMDX_STRINGS = 'strings' SMDX_ATTR_LOCALE = 'locale' SMDX_LABEL = mdef.LABEL SMDX_DESCRIPTION = 'description'", "is not None: if label: point_def[mdef.LABEL] = label if desc: point_def[mdef.DESCRIPTION] = desc", "plen = mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN)) if ptype == SMDX_TYPE_STRING: if plen is None: raise mdef.ModelDefinitionError('Missing", "mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16}, {mdef.NAME: 'L', mdef.DESCRIPTION: 'Model length', mdef.LABEL: 'Model", "SMDX_ACCESS_RW: mdef.ACCESS_RW} smdx_mandatory_types = {SMDX_MANDATORY_FALSE: mdef.MANDATORY_FALSE, SMDX_MANDATORY_TRUE: mdef.MANDATORY_TRUE} smdx_type_types = [ SMDX_TYPE_INT16, SMDX_TYPE_UINT16,", "SMDX_TYPE_UINT16, SMDX_TYPE_COUNT, SMDX_TYPE_ACC16, SMDX_TYPE_ENUM16, SMDX_TYPE_BITFIELD16, SMDX_TYPE_PAD, SMDX_TYPE_INT32, SMDX_TYPE_UINT32, SMDX_TYPE_ACC32, SMDX_TYPE_ENUM32, SMDX_TYPE_BITFIELD32, SMDX_TYPE_IPADDR, SMDX_TYPE_INT64,", "= mdef.TYPE_UINT64 SMDX_TYPE_ACC64 = mdef.TYPE_ACC64 SMDX_TYPE_IPV6ADDR = mdef.TYPE_IPV6ADDR SMDX_TYPE_FLOAT32 = mdef.TYPE_FLOAT32 SMDX_TYPE_STRING =", "ptype = element.attrib.get(SMDX_ATTR_TYPE) if ptype is None: raise mdef.ModelDefinitionError('Missing type attribute for point:", "%s' % m.attrib.get(SMDX_ATTR_ID)) name = m.attrib.get(SMDX_ATTR_NAME) if name is None: name = 'model_'", "= 'repeating' SMDX_ATTR_OFFSET = 'offset' SMDX_ATTR_MANDATORY = mdef.MANDATORY SMDX_ATTR_ACCESS = mdef.ACCESS SMDX_ATTR_SF =", "mdef.TYPE: mdef.TYPE_GROUP, mdef.POINTS: [ {mdef.NAME: 'ID', mdef.VALUE: mid, mdef.DESCRIPTION: 'Model identifier', mdef.LABEL: 'Model", "element.attrib.get(SMDX_ATTR_ID) if pid is None: raise mdef.ModelDefinitionError('Missing point id attribute') point_def[mdef.NAME] = pid", "raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if points: repeating_def[mdef.POINTS] = points fixed_def[mdef.GROUPS]", ": Indicates if *element* is a subelement of the 'strings' definintion within the", "-> symbol object 'value' strings 'label', 'description', 'notes' elements map to point attributes", "repeating is not None: raise mdef.ModelDefinitionError('Duplicate repeating block type definition') repeating = b", "USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import os import xml.etree.ElementTree as", "= element.attrib.get(SMDX_ATTR_ID) if pid is None: raise mdef.ModelDefinitionError('Missing point id attribute') point_def[mdef.NAME] =", "= None repeating = None for b in m.findall(SMDX_BLOCK): btype = b.attrib.get(SMDX_ATTR_TYPE, SMDX_ATTR_TYPE_FIXED)", "= {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.COUNT: 0} points = [] for e in", "m is not None: for a in m.findall('*'): if a.tag == SMDX_LABEL and", "'name' attribute -> symbol object 'name' symbol element content -> symbol object 'value'", "mdef.TYPE_GROUP, mdef.COUNT: 0} points = [] for e in repeating.findall(SMDX_POINT): point_def = from_smdx_point(e)", "OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "e in fixed.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not in fixed_points_map: fixed_points_map[point_def[mdef.NAME]] =", "btype) fixed_points_map = {} if fixed is not None: points = [] for", "and 'value' is the model ID value as a number L point is", "in an SMDX model definition. Parameters: element : Element Tree model type element.", "model type element. \"\"\" model_def = {} m = element.find(SMDX_MODEL) if m is", "None repeating = None for b in m.findall(SMDX_BLOCK): btype = b.attrib.get(SMDX_ATTR_TYPE, SMDX_ATTR_TYPE_FIXED) if", "None for a in p.findall('*'): if a.tag == SMDX_LABEL and a.text: label =", "repeating.attrib.get(SMDX_ATTR_NAME) if name is None: name = 'repeating' repeating_def = {mdef.NAME: name, mdef.TYPE:", "and a.text: label = a.text elif a.tag == SMDX_DESCRIPTION and a.text: desc =", "= mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE)) if value is not None: point_def[mdef.VALUE] = value symbols = []", "label = a.text elif a.tag == SMDX_DESCRIPTION and a.text: desc = a.text elif", ": Element Tree model type element. \"\"\" model_def = {} m = element.find(SMDX_MODEL)", "mdef.ModelDefinitionError('Invalid model id: %s' % m.attrib.get(SMDX_ATTR_ID)) name = m.attrib.get(SMDX_ATTR_NAME) if name is None:", "point attributes based on an element tree point element contained in an SMDX", "= {} if fixed is not None: points = [] for e in", "this permission notice shall be included in all copies or substantial portions of", "if scale factor is an number, convert to correct type sf = mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF))", "not None: raise mdef.ModelDefinitionError('Duplicate repeating block type definition') repeating = b else: raise", "mdef.LABEL: 'Model ID', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16}, {mdef.NAME: 'L',", "% access) if access == SMDX_ACCESS_RW: point_def[mdef.ACCESS] = smdx_access_types.get(access) units = element.attrib.get(SMDX_ATTR_UNITS) if", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A", "mdef.TYPE_UINT16} ] } repeating_def = None fixed = None repeating = None for", "= mdef.TYPE_UINT16 SMDX_TYPE_COUNT = mdef.TYPE_COUNT SMDX_TYPE_ACC16 = mdef.TYPE_ACC16 SMDX_TYPE_ENUM16 = mdef.TYPE_ENUM16 SMDX_TYPE_BITFIELD16 =", "model_def def from_smdx_point(element): \"\"\" Sets the point attributes based on an element tree", "[ SMDX_TYPE_INT16, SMDX_TYPE_UINT16, SMDX_TYPE_COUNT, SMDX_TYPE_ACC16, SMDX_TYPE_ENUM16, SMDX_TYPE_BITFIELD16, SMDX_TYPE_PAD, SMDX_TYPE_INT32, SMDX_TYPE_UINT32, SMDX_TYPE_ACC32, SMDX_TYPE_ENUM32, SMDX_TYPE_BITFIELD32,", "= 'comment' SMDX_STRINGS = 'strings' SMDX_ATTR_LOCALE = 'locale' SMDX_LABEL = mdef.LABEL SMDX_DESCRIPTION =", "points: all type, access, and mandatory attributes are preserved point symbol map to", "mid = int(f.rsplit('_', 1)[1]) except ValueError: raise mdef.ModelDefinitionError('Error extracting model id from filename')", "'label', 'description', 'notes' elements map to point attributes 'label', 'desc', 'detail' ''' def", "element.attrib.get(SMDX_ATTR_TYPE) if ptype is None: raise mdef.ModelDefinitionError('Missing type attribute for point: %s' %", "if a.tag == SMDX_LABEL and a.text: label = a.text elif a.tag == SMDX_DESCRIPTION", "None for b in m.findall(SMDX_BLOCK): btype = b.attrib.get(SMDX_ATTR_TYPE, SMDX_ATTR_TYPE_FIXED) if btype == SMDX_ATTR_TYPE_FIXED:", "notes: point_def[mdef.DETAIL] = notes point_def = repeating_points_map.get(pid) if point_def is not None: if", "raise mdef.ModelDefinitionError('Invalid block type: %s' % btype) fixed_points_map = {} if fixed is", "block type definition') fixed = b elif btype == SMDX_ATTR_TYPE_REPEATING: if repeating is", "id from filename') return mid ''' smdx to json mapping: fixed block ->", "% (ptype, pid)) point_def[mdef.TYPE] = ptype plen = mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN)) if ptype == SMDX_TYPE_STRING:", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION", "a.text elif a.tag == SMDX_DESCRIPTION and a.text: desc = a.text elif a.tag ==", "element content -> symbol object 'value' strings 'label', 'description', 'notes' elements map to", "Software is furnished to do so, subject to the following conditions: The above", "not None: raise mdef.ModelDefinitionError('Duplicate fixed block type definition') fixed = b elif btype", "definintion within the model definition. \"\"\" point_def = {} pid = element.attrib.get(SMDX_ATTR_ID) if", "factor is an number, convert to correct type sf = mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF)) if sf", "mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16} ] } repeating_def = None fixed = None repeating", "plen else: point_def[mdef.SIZE] = mdef.point_type_info.get(ptype)['len'] mandatory = element.attrib.get(SMDX_ATTR_MANDATORY, SMDX_MANDATORY_FALSE) if mandatory not in", "documentation files (the \"Software\"), to deal in the Software without restriction, including without", "files (the \"Software\"), to deal in the Software without restriction, including without limitation", "contained in an SMDX model definition. Parameters: element : Element Tree model type", "not None: points = [] for e in fixed.findall(SMDX_POINT): point_def = from_smdx_point(e) if", "to do so, subject to the following conditions: The above copyright notice and", "attribute -> symbol object 'name' symbol element content -> symbol object 'value' strings", "else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if points: repeating_def[mdef.POINTS] = points", "a.tag == SMDX_DESCRIPTION and a.text: fixed_def[mdef.DESCRIPTION] = a.text elif a.tag == SMDX_NOTES and", "point_def[mdef.SIZE] = mdef.point_type_info.get(ptype)['len'] mandatory = element.attrib.get(SMDX_ATTR_MANDATORY, SMDX_MANDATORY_FALSE) if mandatory not in smdx_mandatory_types: raise", "e.tag == SMDX_SYMBOL: sid = e.attrib.get(SMDX_ATTR_ID) value = e.text try: value = int(value)", "type sf = mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF)) if sf is not None: point_def[mdef.SF] = sf #", "has no value specified in the model definition fixed block points are placed", "SMDX_TYPE_SUNSSF, SMDX_TYPE_EUI48 ] SMDX_PREFIX = 'smdx_' SMDX_EXT = '.xml' def to_smdx_filename(model_id): return '%s%05d%s'", "symbols.append({mdef.NAME: sid, mdef.VALUE: value}) if symbols: point_def[mdef.SYMBOLS] = symbols return point_def def indent(elem,", "'name' -> group 'name', if no 'name' is defined 'name' = 'repeating' points:", "if label: point_def[mdef.LABEL] = label if desc: point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL]", "model_def = {'id': mid, 'group': fixed_def} return model_def def from_smdx_point(element): \"\"\" Sets the", "the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "a.tag == SMDX_LABEL and a.text: fixed_def[mdef.LABEL] = a.text elif a.tag == SMDX_DESCRIPTION and", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN", "is not None: raise mdef.ModelDefinitionError('Duplicate repeating block type definition') repeating = b else:", "SMDX_MODEL = mdef.MODEL SMDX_BLOCK = 'block' SMDX_POINT = 'point' SMDX_ATTR_VERS = 'v' SMDX_ATTR_ID", "'model_' + str(mid) model_def[mdef.NAME] = name strings = element.find(SMDX_STRINGS) # create top level", "elements map to point attributes 'label', 'desc', 'detail' ''' def from_smdx_file(filename): tree =", "= {} pid = element.attrib.get(SMDX_ATTR_ID) if pid is None: raise mdef.ModelDefinitionError('Missing point id", "= mdef.LABEL SMDX_DESCRIPTION = 'description' SMDX_NOTES = 'notes' SMDX_DETAIL = mdef.DETAIL SMDX_TYPE_INT16 =", "+ \" \" if not elem.tail or not elem.tail.strip(): elem.tail = i for", "SMDX_TYPE_PAD = mdef.TYPE_PAD SMDX_TYPE_INT32 = mdef.TYPE_INT32 SMDX_TYPE_UINT32 = mdef.TYPE_UINT32 SMDX_TYPE_ACC32 = mdef.TYPE_ACC32 SMDX_TYPE_ENUM32", "if m is not None: for a in m.findall('*'): if a.tag == SMDX_LABEL", "SMDX_MANDATORY_TRUE = 'true' smdx_access_types = {SMDX_ACCESS_R: mdef.ACCESS_R, SMDX_ACCESS_RW: mdef.ACCESS_RW} smdx_mandatory_types = {SMDX_MANDATORY_FALSE: mdef.MANDATORY_FALSE,", "value as a number L point is created for model len - model", "model type attributes based on an element tree model type element contained in", "SMDX_ATTR_TYPE_FIXED = 'fixed' SMDX_ATTR_TYPE_REPEATING = 'repeating' SMDX_ATTR_OFFSET = 'offset' SMDX_ATTR_MANDATORY = mdef.MANDATORY SMDX_ATTR_ACCESS", "number, convert to correct type value = mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE)) if value is not None:", "return point_def def indent(elem, level=0): i = os.linesep + level*\" \" if len(elem):", "in repeating.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not in repeating_points_map: repeating_points_map[point_def[mdef.NAME]] = point_def", "== SMDX_LABEL and a.text: label = a.text elif a.tag == SMDX_DESCRIPTION and a.text:", "THE SOFTWARE. \"\"\" import os import xml.etree.ElementTree as ET import sunspec2.mdef as mdef", "= a.text elif a.tag == SMDX_NOTES and a.text: notes = a.text point_def =", "mandatory type: %s' % mandatory) if mandatory == SMDX_MANDATORY_TRUE: point_def[mdef.MANDATORY] = smdx_mandatory_types.get(mandatory) access", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,", "'point' SMDX_ATTR_VERS = 'v' SMDX_ATTR_ID = 'id' SMDX_ATTR_LEN = 'len' SMDX_ATTR_NAME = mdef.NAME", "pass symbols.append({mdef.NAME: sid, mdef.VALUE: value}) if symbols: point_def[mdef.SYMBOLS] = symbols return point_def def", "not elem.text.strip(): elem.text = i + \" \" if not elem.tail or not", "to_smdx_filename(model_id): return '%s%05d%s' % (SMDX_PREFIX, int(model_id), SMDX_EXT) def model_filename_to_id(filename): f = filename if", "units = element.attrib.get(SMDX_ATTR_UNITS) if units: point_def[mdef.UNITS] = units # if scale factor is", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT", "substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "b.attrib.get(SMDX_ATTR_TYPE, SMDX_ATTR_TYPE_FIXED) if btype == SMDX_ATTR_TYPE_FIXED: if fixed is not None: raise mdef.ModelDefinitionError('Duplicate", "point %s' % (ptype, pid)) point_def[mdef.TYPE] = ptype plen = mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN)) if ptype", "try: mid = int(f.rsplit('_', 1)[1]) except ValueError: raise mdef.ModelDefinitionError('Error extracting model id from", "SMDX_TYPE_ACC64 = mdef.TYPE_ACC64 SMDX_TYPE_IPV6ADDR = mdef.TYPE_IPV6ADDR SMDX_TYPE_FLOAT32 = mdef.TYPE_FLOAT32 SMDX_TYPE_STRING = mdef.TYPE_STRING SMDX_TYPE_SUNSSF", "TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "SMDX_EXT = '.xml' def to_smdx_filename(model_id): return '%s%05d%s' % (SMDX_PREFIX, int(model_id), SMDX_EXT) def model_filename_to_id(filename):", "element.attrib.get(SMDX_ATTR_UNITS) if units: point_def[mdef.UNITS] = units # if scale factor is an number,", "fixed_def[mdef.LABEL] = a.text elif a.tag == SMDX_DESCRIPTION and a.text: fixed_def[mdef.DESCRIPTION] = a.text elif", "raise mdef.ModelDefinitionError('Unknown access type: %s' % access) if access == SMDX_ACCESS_RW: point_def[mdef.ACCESS] =", "the model type attributes based on an element tree model type element contained", "a number L point is created for model len - model len has", "in element.findall('*'): if e.tag == SMDX_SYMBOL: sid = e.attrib.get(SMDX_ATTR_ID) value = e.text try:", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR", "tree.getroot() return(from_smdx(root)) def from_smdx(element): \"\"\" Sets the model type attributes based on an", "'symbol' SMDX_COMMENT = 'comment' SMDX_STRINGS = 'strings' SMDX_ATTR_LOCALE = 'locale' SMDX_LABEL = mdef.LABEL", "found') try: mid = mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID)) except ValueError: raise mdef.ModelDefinitionError('Invalid model id: %s' %", ": Element Tree point type element. strings : Indicates if *element* is a", "mdef SMDX_ROOT = 'sunSpecModels' SMDX_MODEL = mdef.MODEL SMDX_BLOCK = 'block' SMDX_POINT = 'point'", "= a.text point_def = fixed_points_map.get(pid) if point_def is not None: if label: point_def[mdef.LABEL]", "= 'point' SMDX_ATTR_VERS = 'v' SMDX_ATTR_ID = 'id' SMDX_ATTR_LEN = 'len' SMDX_ATTR_NAME =", "mdef.TYPE_SUNSSF SMDX_TYPE_EUI48 = mdef.TYPE_EUI48 SMDX_ACCESS_R = 'r' SMDX_ACCESS_RW = 'rw' SMDX_MANDATORY_FALSE = 'false'", "point_def[mdef.DETAIL] = notes model_def = {'id': mid, 'group': fixed_def} return model_def def from_smdx_point(element):", "SOFTWARE. \"\"\" import os import xml.etree.ElementTree as ET import sunspec2.mdef as mdef SMDX_ROOT", "mdef.TYPE: mdef.TYPE_UINT16} ] } repeating_def = None fixed = None repeating = None", "elem.text = i + \" \" if not elem.tail or not elem.tail.strip(): elem.tail", "= units # if scale factor is an number, convert to correct type", "SMDX_TYPE_EUI48 ] SMDX_PREFIX = 'smdx_' SMDX_EXT = '.xml' def to_smdx_filename(model_id): return '%s%05d%s' %", "repeating.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not in repeating_points_map: repeating_points_map[point_def[mdef.NAME]] = point_def points.append(point_def)", "is the model ID value as a number L point is created for", "group repeating block -> group with count = 0 (indicates model len shoud", "1)[1]) except ValueError: raise mdef.ModelDefinitionError('Error extracting model id from filename') return mid '''", "id attribute') point_def[mdef.NAME] = pid ptype = element.attrib.get(SMDX_ATTR_TYPE) if ptype is None: raise", "mdef.ModelDefinitionError('Unknown point type %s for point %s' % (ptype, pid)) point_def[mdef.TYPE] = ptype", "fixed is not None: raise mdef.ModelDefinitionError('Duplicate fixed block type definition') fixed = b", "sf = mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF)) if sf is not None: point_def[mdef.SF] = sf # if", "from filename') return mid ''' smdx to json mapping: fixed block -> top", "SMDX_TYPE_BITFIELD16, SMDX_TYPE_PAD, SMDX_TYPE_INT32, SMDX_TYPE_UINT32, SMDX_TYPE_ACC32, SMDX_TYPE_ENUM32, SMDX_TYPE_BITFIELD32, SMDX_TYPE_IPADDR, SMDX_TYPE_INT64, SMDX_TYPE_UINT64, SMDX_TYPE_ACC64, SMDX_TYPE_IPV6ADDR, SMDX_TYPE_FLOAT32,", "+ level*\" \" if len(elem): if not elem.text or not elem.text.strip(): elem.text =", "mdef.TYPE_INT32 SMDX_TYPE_UINT32 = mdef.TYPE_UINT32 SMDX_TYPE_ACC32 = mdef.TYPE_ACC32 SMDX_TYPE_ENUM32 = mdef.TYPE_ENUM32 SMDX_TYPE_BITFIELD32 = mdef.TYPE_BITFIELD32", "btype == SMDX_ATTR_TYPE_REPEATING: if repeating is not None: raise mdef.ModelDefinitionError('Duplicate repeating block type", "mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16}, {mdef.NAME: 'L', mdef.DESCRIPTION: 'Model length', mdef.LABEL: 'Model Length', mdef.SIZE:", "OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "point type element. strings : Indicates if *element* is a subelement of the", "all type, access, and mandatory attributes are preserved point symbol map to the", "strings 'label', 'description', 'notes' elements map to point attributes 'label', 'desc', 'detail' '''", "'group': fixed_def} return model_def def from_smdx_point(element): \"\"\" Sets the point attributes based on", "smdx_access_types: raise mdef.ModelDefinitionError('Unknown access type: %s' % access) if access == SMDX_ACCESS_RW: point_def[mdef.ACCESS]", "'notes' elements map to point attributes 'label', 'desc', 'detail' ''' def from_smdx_file(filename): tree", "point_def[mdef.NAME]) if points: fixed_def[mdef.POINTS].extend(points) repeating_points_map = {} if repeating is not None: name", "point symbol 'name' attribute -> symbol object 'name' symbol element content -> symbol", "points fixed_def[mdef.GROUPS] = [repeating_def] e = element.find(SMDX_STRINGS) if e.attrib.get(SMDX_ATTR_ID) == str(mid): m =", "return(from_smdx(root)) def from_smdx(element): \"\"\" Sets the model type attributes based on an element", "== SMDX_MANDATORY_TRUE: point_def[mdef.MANDATORY] = smdx_mandatory_types.get(mandatory) access = element.attrib.get(SMDX_ATTR_ACCESS, SMDX_ACCESS_R) if access not in", "1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16} ] } repeating_def = None fixed", "desc: point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL] = notes model_def = {'id': mid,", "'id' SMDX_ATTR_LEN = 'len' SMDX_ATTR_NAME = mdef.NAME SMDX_ATTR_TYPE = mdef.TYPE SMDX_ATTR_COUNT = mdef.COUNT", "%s' % mandatory) if mandatory == SMDX_MANDATORY_TRUE: point_def[mdef.MANDATORY] = smdx_mandatory_types.get(mandatory) access = element.attrib.get(SMDX_ATTR_ACCESS,", "point_def[mdef.NAME]) if points: repeating_def[mdef.POINTS] = points fixed_def[mdef.GROUPS] = [repeating_def] e = element.find(SMDX_STRINGS) if", "mdef.TYPE_BITFIELD32 SMDX_TYPE_IPADDR = mdef.TYPE_IPADDR SMDX_TYPE_INT64 = mdef.TYPE_INT64 SMDX_TYPE_UINT64 = mdef.TYPE_UINT64 SMDX_TYPE_ACC64 = mdef.TYPE_ACC64", "a.text: fixed_def[mdef.DETAIL] = a.text for p in e.findall(SMDX_POINT): pid = p.attrib.get(SMDX_ATTR_ID) label =", "SMDX_LABEL and a.text: label = a.text elif a.tag == SMDX_DESCRIPTION and a.text: desc", "if pid is None: raise mdef.ModelDefinitionError('Missing point id attribute') point_def[mdef.NAME] = pid ptype", "type value = mdef.to_number_type(element.attrib.get(SMDX_ATTR_VALUE)) if value is not None: point_def[mdef.VALUE] = value symbols", "p.findall('*'): if a.tag == SMDX_LABEL and a.text: label = a.text elif a.tag ==", "= pid ptype = element.attrib.get(SMDX_ATTR_TYPE) if ptype is None: raise mdef.ModelDefinitionError('Missing type attribute", "raise mdef.ModelDefinitionError('Missing len attribute for point: %s' % pid) point_def[mdef.SIZE] = plen else:", "if m is None: raise mdef.ModelDefinitionError('Model definition not found') try: mid = mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID))", "SMDX_ATTR_TYPE = mdef.TYPE SMDX_ATTR_COUNT = mdef.COUNT SMDX_ATTR_VALUE = mdef.VALUE SMDX_ATTR_TYPE_FIXED = 'fixed' SMDX_ATTR_TYPE_REPEATING", "for point: %s' % pid) elif ptype not in smdx_type_types: raise mdef.ModelDefinitionError('Unknown point", "os import xml.etree.ElementTree as ET import sunspec2.mdef as mdef SMDX_ROOT = 'sunSpecModels' SMDX_MODEL", "== SMDX_LABEL and a.text: fixed_def[mdef.LABEL] = a.text elif a.tag == SMDX_DESCRIPTION and a.text:", "fixed = b elif btype == SMDX_ATTR_TYPE_REPEATING: if repeating is not None: raise", "i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip():", "permission notice shall be included in all copies or substantial portions of the", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH", "from_smdx(element): \"\"\" Sets the model type attributes based on an element tree model", "smdx_mandatory_types: raise mdef.ModelDefinitionError('Unknown mandatory type: %s' % mandatory) if mandatory == SMDX_MANDATORY_TRUE: point_def[mdef.MANDATORY]", "= mdef.TYPE_COUNT SMDX_TYPE_ACC16 = mdef.TYPE_ACC16 SMDX_TYPE_ENUM16 = mdef.TYPE_ENUM16 SMDX_TYPE_BITFIELD16 = mdef.TYPE_BITFIELD16 SMDX_TYPE_PAD =", "= symbols return point_def def indent(elem, level=0): i = os.linesep + level*\" \"", "raise mdef.ModelDefinitionError('Duplicate fixed block type definition') fixed = b elif btype == SMDX_ATTR_TYPE_REPEATING:", "'name' ID point is created for model ID and 'value' is the model", "ptype is None: raise mdef.ModelDefinitionError('Missing type attribute for point: %s' % pid) elif", "for point: %s' % pid) point_def[mdef.SIZE] = plen else: point_def[mdef.SIZE] = mdef.point_type_info.get(ptype)['len'] mandatory", "strings : Indicates if *element* is a subelement of the 'strings' definintion within", "level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level", "fixed_points_map.get(pid) if point_def is not None: if label: point_def[mdef.LABEL] = label if desc:", "SMDX_TYPE_STRING, SMDX_TYPE_SUNSSF, SMDX_TYPE_EUI48 ] SMDX_PREFIX = 'smdx_' SMDX_EXT = '.xml' def to_smdx_filename(model_id): return", "repeating_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.COUNT: 0} points = [] for e", "# if scale factor is an number, convert to correct type sf =", "level group with ID and L points fixed_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP,", "a.text point_def = fixed_points_map.get(pid) if point_def is not None: if label: point_def[mdef.LABEL] =", "{mdef.NAME: 'L', mdef.DESCRIPTION: 'Model length', mdef.LABEL: 'Model Length', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC:", "is None: raise mdef.ModelDefinitionError('Missing len attribute for point: %s' % pid) point_def[mdef.SIZE] =", "point_def[mdef.SF] = sf # if scale factor is an number, convert to correct", "copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and", "= {SMDX_ACCESS_R: mdef.ACCESS_R, SMDX_ACCESS_RW: mdef.ACCESS_RW} smdx_mandatory_types = {SMDX_MANDATORY_FALSE: mdef.MANDATORY_FALSE, SMDX_MANDATORY_TRUE: mdef.MANDATORY_TRUE} smdx_type_types =", "'notes' SMDX_DETAIL = mdef.DETAIL SMDX_TYPE_INT16 = mdef.TYPE_INT16 SMDX_TYPE_UINT16 = mdef.TYPE_UINT16 SMDX_TYPE_COUNT = mdef.TYPE_COUNT", "the symbol object and placed in the symbols list for the point symbol", "len - model len has no value specified in the model definition fixed", "''' def from_smdx_file(filename): tree = ET.parse(filename) root = tree.getroot() return(from_smdx(root)) def from_smdx(element): \"\"\"", "'strings' SMDX_ATTR_LOCALE = 'locale' SMDX_LABEL = mdef.LABEL SMDX_DESCRIPTION = 'description' SMDX_NOTES = 'notes'", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN", "following conditions: The above copyright notice and this permission notice shall be included", "with ID and L points fixed_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.POINTS: [", "raise mdef.ModelDefinitionError('Unknown mandatory type: %s' % mandatory) if mandatory == SMDX_MANDATORY_TRUE: point_def[mdef.MANDATORY] =", "the point attributes based on an element tree point element contained in an", "The above copyright notice and this permission notice shall be included in all", "= label if desc: point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL] = notes point_def", "elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail", "length', mdef.LABEL: 'Model Length', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16} ]", "is not None: points = [] for e in fixed.findall(SMDX_POINT): point_def = from_smdx_point(e)", "= p.attrib.get(SMDX_ATTR_ID) label = desc = notes = None for a in p.findall('*'):", "model ID value as a number L point is created for model len", "granted, free of charge, to any person obtaining a copy of this software", "limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "and a.text: fixed_def[mdef.LABEL] = a.text elif a.tag == SMDX_DESCRIPTION and a.text: fixed_def[mdef.DESCRIPTION] =", "placed in the symbols list for the point symbol 'name' attribute -> symbol", "ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO", "SMDX_ATTR_SF = mdef.SF SMDX_ATTR_UNITS = mdef.UNITS SMDX_SYMBOL = 'symbol' SMDX_COMMENT = 'comment' SMDX_STRINGS", "SMDX_TYPE_ENUM32 = mdef.TYPE_ENUM32 SMDX_TYPE_BITFIELD32 = mdef.TYPE_BITFIELD32 SMDX_TYPE_IPADDR = mdef.TYPE_IPADDR SMDX_TYPE_INT64 = mdef.TYPE_INT64 SMDX_TYPE_UINT64", "mdef.TYPE: mdef.TYPE_GROUP, mdef.COUNT: 0} points = [] for e in repeating.findall(SMDX_POINT): point_def =", "for e in repeating.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not in repeating_points_map: repeating_points_map[point_def[mdef.NAME]]", "xml.etree.ElementTree as ET import sunspec2.mdef as mdef SMDX_ROOT = 'sunSpecModels' SMDX_MODEL = mdef.MODEL", "mdef.ModelDefinitionError('Missing point id attribute') point_def[mdef.NAME] = pid ptype = element.attrib.get(SMDX_ATTR_TYPE) if ptype is", "[] for e in fixed.findall(SMDX_POINT): point_def = from_smdx_point(e) if point_def[mdef.NAME] not in fixed_points_map:", "notes model_def = {'id': mid, 'group': fixed_def} return model_def def from_smdx_point(element): \"\"\" Sets", "sid, mdef.VALUE: value}) if symbols: point_def[mdef.SYMBOLS] = symbols return point_def def indent(elem, level=0):", "strings = element.find(SMDX_STRINGS) # create top level group with ID and L points", "= filename if '.' in f: f = os.path.splitext(f)[0] try: mid = int(f.rsplit('_',", "len has no value specified in the model definition fixed block points are", "= desc = notes = None for a in p.findall('*'): if a.tag ==", "% m.attrib.get(SMDX_ATTR_ID)) name = m.attrib.get(SMDX_ATTR_NAME) if name is None: name = 'model_' +", "mdef.LABEL SMDX_DESCRIPTION = 'description' SMDX_NOTES = 'notes' SMDX_DETAIL = mdef.DETAIL SMDX_TYPE_INT16 = mdef.TYPE_INT16", "import xml.etree.ElementTree as ET import sunspec2.mdef as mdef SMDX_ROOT = 'sunSpecModels' SMDX_MODEL =", "raise mdef.ModelDefinitionError('Duplicate point definition: %s' % point_def[mdef.NAME]) if points: fixed_def[mdef.POINTS].extend(points) repeating_points_map = {}", "identifier', mdef.LABEL: 'Model ID', mdef.SIZE: 1, mdef.MANDATORY: mdef.MANDATORY_TRUE, mdef.STATIC: mdef.STATIC_TRUE, mdef.TYPE: mdef.TYPE_UINT16}, {mdef.NAME:", "indent(elem, level=0): i = os.linesep + level*\" \" if len(elem): if not elem.text", "value is not None: point_def[mdef.VALUE] = value symbols = [] for e in", "mdef.SF SMDX_ATTR_UNITS = mdef.UNITS SMDX_SYMBOL = 'symbol' SMDX_COMMENT = 'comment' SMDX_STRINGS = 'strings'", "be used to determine number of groups) repeating block 'name' -> group 'name',", "SMDX_TYPE_BITFIELD32 = mdef.TYPE_BITFIELD32 SMDX_TYPE_IPADDR = mdef.TYPE_IPADDR SMDX_TYPE_INT64 = mdef.TYPE_INT64 SMDX_TYPE_UINT64 = mdef.TYPE_UINT64 SMDX_TYPE_ACC64", "and/or sell copies of the Software, and to permit persons to whom the", "= element.find(SMDX_MODEL) if m is None: raise mdef.ModelDefinitionError('Model definition not found') try: mid", "based on an element tree model type element contained in an SMDX model", "mdef.UNITS SMDX_SYMBOL = 'symbol' SMDX_COMMENT = 'comment' SMDX_STRINGS = 'strings' SMDX_ATTR_LOCALE = 'locale'", "if access not in smdx_access_types: raise mdef.ModelDefinitionError('Unknown access type: %s' % access) if", "mdef.COUNT SMDX_ATTR_VALUE = mdef.VALUE SMDX_ATTR_TYPE_FIXED = 'fixed' SMDX_ATTR_TYPE_REPEATING = 'repeating' SMDX_ATTR_OFFSET = 'offset'", "== SMDX_NOTES and a.text: notes = a.text point_def = fixed_points_map.get(pid) if point_def is", "map to the symbol object and placed in the symbols list for the", "of charge, to any person obtaining a copy of this software and associated", "in repeating_points_map: repeating_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' %", "= mdef.TYPE_BITFIELD32 SMDX_TYPE_IPADDR = mdef.TYPE_IPADDR SMDX_TYPE_INT64 = mdef.TYPE_INT64 SMDX_TYPE_UINT64 = mdef.TYPE_UINT64 SMDX_TYPE_ACC64 =", "None fixed = None repeating = None for b in m.findall(SMDX_BLOCK): btype =", "type: %s' % mandatory) if mandatory == SMDX_MANDATORY_TRUE: point_def[mdef.MANDATORY] = smdx_mandatory_types.get(mandatory) access =", "= a.text elif a.tag == SMDX_DESCRIPTION and a.text: fixed_def[mdef.DESCRIPTION] = a.text elif a.tag", "= i + \" \" if not elem.tail or not elem.tail.strip(): elem.tail =", "smdx_access_types = {SMDX_ACCESS_R: mdef.ACCESS_R, SMDX_ACCESS_RW: mdef.ACCESS_RW} smdx_mandatory_types = {SMDX_MANDATORY_FALSE: mdef.MANDATORY_FALSE, SMDX_MANDATORY_TRUE: mdef.MANDATORY_TRUE} smdx_type_types", "mdef.ACCESS_RW} smdx_mandatory_types = {SMDX_MANDATORY_FALSE: mdef.MANDATORY_FALSE, SMDX_MANDATORY_TRUE: mdef.MANDATORY_TRUE} smdx_type_types = [ SMDX_TYPE_INT16, SMDX_TYPE_UINT16, SMDX_TYPE_COUNT,", "points: repeating_def[mdef.POINTS] = points fixed_def[mdef.GROUPS] = [repeating_def] e = element.find(SMDX_STRINGS) if e.attrib.get(SMDX_ATTR_ID) ==", "= mdef.TYPE_ACC64 SMDX_TYPE_IPV6ADDR = mdef.TYPE_IPV6ADDR SMDX_TYPE_FLOAT32 = mdef.TYPE_FLOAT32 SMDX_TYPE_STRING = mdef.TYPE_STRING SMDX_TYPE_SUNSSF =", "element. strings : Indicates if *element* is a subelement of the 'strings' definintion", "convert to correct type sf = mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF)) if sf is not None: point_def[mdef.SF]", "mdef.TYPE_UINT32 SMDX_TYPE_ACC32 = mdef.TYPE_ACC32 SMDX_TYPE_ENUM32 = mdef.TYPE_ENUM32 SMDX_TYPE_BITFIELD32 = mdef.TYPE_BITFIELD32 SMDX_TYPE_IPADDR = mdef.TYPE_IPADDR", "mdef.POINTS: [ {mdef.NAME: 'ID', mdef.VALUE: mid, mdef.DESCRIPTION: 'Model identifier', mdef.LABEL: 'Model ID', mdef.SIZE:", "for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail", "repeating_def = None fixed = None repeating = None for b in m.findall(SMDX_BLOCK):", "try: value = int(value) except ValueError: pass symbols.append({mdef.NAME: sid, mdef.VALUE: value}) if symbols:", "access = element.attrib.get(SMDX_ATTR_ACCESS, SMDX_ACCESS_R) if access not in smdx_access_types: raise mdef.ModelDefinitionError('Unknown access type:", "map to point attributes 'label', 'desc', 'detail' ''' def from_smdx_file(filename): tree = ET.parse(filename)", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"", "the model definition. \"\"\" point_def = {} pid = element.attrib.get(SMDX_ATTR_ID) if pid is", "(C) 2020 SunSpec Alliance Permission is hereby granted, free of charge, to any", "= 'smdx_' SMDX_EXT = '.xml' def to_smdx_filename(model_id): return '%s%05d%s' % (SMDX_PREFIX, int(model_id), SMDX_EXT)", "SMDX model definition. Parameters: element : Element Tree point type element. strings :", "for a in p.findall('*'): if a.tag == SMDX_LABEL and a.text: label = a.text", "portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not", "= i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail =", "f = filename if '.' in f: f = os.path.splitext(f)[0] try: mid =", "fixed block -> top level group model 'name' attribute -> group 'name' ID", "m.attrib.get(SMDX_ATTR_ID)) name = m.attrib.get(SMDX_ATTR_NAME) if name is None: name = 'model_' + str(mid)", "Tree model type element. \"\"\" model_def = {} m = element.find(SMDX_MODEL) if m", "model_def = {} m = element.find(SMDX_MODEL) if m is None: raise mdef.ModelDefinitionError('Model definition", "== SMDX_DESCRIPTION and a.text: desc = a.text elif a.tag == SMDX_NOTES and a.text:", "OTHER DEALINGS IN THE SOFTWARE. \"\"\" import os import xml.etree.ElementTree as ET import", "mdef.point_type_info.get(ptype)['len'] mandatory = element.attrib.get(SMDX_ATTR_MANDATORY, SMDX_MANDATORY_FALSE) if mandatory not in smdx_mandatory_types: raise mdef.ModelDefinitionError('Unknown mandatory", "else: raise mdef.ModelDefinitionError('Invalid block type: %s' % btype) fixed_points_map = {} if fixed", "in fixed_points_map: fixed_points_map[point_def[mdef.NAME]] = point_def points.append(point_def) else: raise mdef.ModelDefinitionError('Duplicate point definition: %s' %", "SMDX_TYPE_INT64, SMDX_TYPE_UINT64, SMDX_TYPE_ACC64, SMDX_TYPE_IPV6ADDR, SMDX_TYPE_FLOAT32, SMDX_TYPE_STRING, SMDX_TYPE_SUNSSF, SMDX_TYPE_EUI48 ] SMDX_PREFIX = 'smdx_' SMDX_EXT", "= mdef.TYPE SMDX_ATTR_COUNT = mdef.COUNT SMDX_ATTR_VALUE = mdef.VALUE SMDX_ATTR_TYPE_FIXED = 'fixed' SMDX_ATTR_TYPE_REPEATING =", "element tree model type element contained in an SMDX model definition. Parameters: element", "if plen is None: raise mdef.ModelDefinitionError('Missing len attribute for point: %s' % pid)", "if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem:", "Sets the point attributes based on an element tree point element contained in", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i", "'offset' SMDX_ATTR_MANDATORY = mdef.MANDATORY SMDX_ATTR_ACCESS = mdef.ACCESS SMDX_ATTR_SF = mdef.SF SMDX_ATTR_UNITS = mdef.UNITS", "mdef.DETAIL SMDX_TYPE_INT16 = mdef.TYPE_INT16 SMDX_TYPE_UINT16 = mdef.TYPE_UINT16 SMDX_TYPE_COUNT = mdef.TYPE_COUNT SMDX_TYPE_ACC16 = mdef.TYPE_ACC16", "element.find(SMDX_STRINGS) if e.attrib.get(SMDX_ATTR_ID) == str(mid): m = e.find(SMDX_MODEL) if m is not None:", "mdef.TYPE_GROUP, mdef.POINTS: [ {mdef.NAME: 'ID', mdef.VALUE: mid, mdef.DESCRIPTION: 'Model identifier', mdef.LABEL: 'Model ID',", "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS", "subject to the following conditions: The above copyright notice and this permission notice", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE", "filename') return mid ''' smdx to json mapping: fixed block -> top level", "sid = e.attrib.get(SMDX_ATTR_ID) value = e.text try: value = int(value) except ValueError: pass", "object 'value' strings 'label', 'description', 'notes' elements map to point attributes 'label', 'desc',", "0 (indicates model len shoud be used to determine number of groups) repeating", "% pid) elif ptype not in smdx_type_types: raise mdef.ModelDefinitionError('Unknown point type %s for", "point_def[mdef.DESCRIPTION] = desc if notes: point_def[mdef.DETAIL] = notes model_def = {'id': mid, 'group':", "sunspec2.mdef as mdef SMDX_ROOT = 'sunSpecModels' SMDX_MODEL = mdef.MODEL SMDX_BLOCK = 'block' SMDX_POINT", "{} pid = element.attrib.get(SMDX_ATTR_ID) if pid is None: raise mdef.ModelDefinitionError('Missing point id attribute')", "%s for point %s' % (ptype, pid)) point_def[mdef.TYPE] = ptype plen = mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN))", "FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "= {SMDX_MANDATORY_FALSE: mdef.MANDATORY_FALSE, SMDX_MANDATORY_TRUE: mdef.MANDATORY_TRUE} smdx_type_types = [ SMDX_TYPE_INT16, SMDX_TYPE_UINT16, SMDX_TYPE_COUNT, SMDX_TYPE_ACC16, SMDX_TYPE_ENUM16,", "SMDX_TYPE_UINT32 = mdef.TYPE_UINT32 SMDX_TYPE_ACC32 = mdef.TYPE_ACC32 SMDX_TYPE_ENUM32 = mdef.TYPE_ENUM32 SMDX_TYPE_BITFIELD32 = mdef.TYPE_BITFIELD32 SMDX_TYPE_IPADDR", "if a.tag == SMDX_LABEL and a.text: fixed_def[mdef.LABEL] = a.text elif a.tag == SMDX_DESCRIPTION", "SMDX_TYPE_IPV6ADDR = mdef.TYPE_IPV6ADDR SMDX_TYPE_FLOAT32 = mdef.TYPE_FLOAT32 SMDX_TYPE_STRING = mdef.TYPE_STRING SMDX_TYPE_SUNSSF = mdef.TYPE_SUNSSF SMDX_TYPE_EUI48", "correct type sf = mdef.to_number_type(element.attrib.get(SMDX_ATTR_SF)) if sf is not None: point_def[mdef.SF] = sf", "try: mid = mdef.to_number_type(m.attrib.get(SMDX_ATTR_ID)) except ValueError: raise mdef.ModelDefinitionError('Invalid model id: %s' % m.attrib.get(SMDX_ATTR_ID))", "hereby granted, free of charge, to any person obtaining a copy of this", "SMDX_TYPE_STRING = mdef.TYPE_STRING SMDX_TYPE_SUNSSF = mdef.TYPE_SUNSSF SMDX_TYPE_EUI48 = mdef.TYPE_EUI48 SMDX_ACCESS_R = 'r' SMDX_ACCESS_RW", "ID point is created for model ID and 'value' is the model ID", "mdef.TYPE: mdef.TYPE_UINT16}, {mdef.NAME: 'L', mdef.DESCRIPTION: 'Model length', mdef.LABEL: 'Model Length', mdef.SIZE: 1, mdef.MANDATORY:", "restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,", "= ET.parse(filename) root = tree.getroot() return(from_smdx(root)) def from_smdx(element): \"\"\" Sets the model type", "= 'repeating' repeating_def = {mdef.NAME: name, mdef.TYPE: mdef.TYPE_GROUP, mdef.COUNT: 0} points = []", "is None: raise mdef.ModelDefinitionError('Missing type attribute for point: %s' % pid) elif ptype", "os.path.splitext(f)[0] try: mid = int(f.rsplit('_', 1)[1]) except ValueError: raise mdef.ModelDefinitionError('Error extracting model id", "point definition: %s' % point_def[mdef.NAME]) if points: repeating_def[mdef.POINTS] = points fixed_def[mdef.GROUPS] = [repeating_def]", "smdx to json mapping: fixed block -> top level group model 'name' attribute", "fixed_def[mdef.POINTS].extend(points) repeating_points_map = {} if repeating is not None: name = repeating.attrib.get(SMDX_ATTR_NAME) if", "used to determine number of groups) repeating block 'name' -> group 'name', if", "a.text: notes = a.text point_def = fixed_points_map.get(pid) if point_def is not None: if", "Indicates if *element* is a subelement of the 'strings' definintion within the model", "%s' % (ptype, pid)) point_def[mdef.TYPE] = ptype plen = mdef.to_number_type(element.attrib.get(SMDX_ATTR_LEN)) if ptype ==", "top level group repeating block -> group with count = 0 (indicates model", "% (SMDX_PREFIX, int(model_id), SMDX_EXT) def model_filename_to_id(filename): f = filename if '.' in f:" ]
[ "fields = ('url', 'username', 'email', 'is_staff') # ViewSets define the view behavior. class", "'is_staff') # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class", "print_function from __future__ import unicode_literals from __future__ import division from django.contrib.auth.models import User", "Meta: model = User fields = ('url', 'username', 'email', 'is_staff') # ViewSets define", "viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model =", "from __future__ import unicode_literals from __future__ import division from django.contrib.auth.models import User from", "utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import", "__future__ import print_function from __future__ import unicode_literals from __future__ import division from django.contrib.auth.models", "<gh_stars>1-10 # -*- coding: utf-8 -*- from __future__ import print_function from __future__ import", "csrf from rest_framework import serializers, viewsets # Serializers define the API representation. class", "import User from django.shortcuts import render_to_response from django.template.context_processors import csrf from rest_framework import", "import serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta:", "division from django.contrib.auth.models import User from django.shortcuts import render_to_response from django.template.context_processors import csrf", "import division from django.contrib.auth.models import User from django.shortcuts import render_to_response from django.template.context_processors import", "__future__ import unicode_literals from __future__ import division from django.contrib.auth.models import User from django.shortcuts", "UserSerializer def home_page(request): csrf_token = {} csrf_token.update(csrf(request)) return render_to_response('home/home.html', csrf_token) def compare(request): return", "view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def home_page(request): csrf_token", "__future__ import division from django.contrib.auth.models import User from django.shortcuts import render_to_response from django.template.context_processors", "django.shortcuts import render_to_response from django.template.context_processors import csrf from rest_framework import serializers, viewsets #", "define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields =", "ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer", "define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def", "= User.objects.all() serializer_class = UserSerializer def home_page(request): csrf_token = {} csrf_token.update(csrf(request)) return render_to_response('home/home.html',", "# ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class =", "User.objects.all() serializer_class = UserSerializer def home_page(request): csrf_token = {} csrf_token.update(csrf(request)) return render_to_response('home/home.html', csrf_token)", "User from django.shortcuts import render_to_response from django.template.context_processors import csrf from rest_framework import serializers,", "= User fields = ('url', 'username', 'email', 'is_staff') # ViewSets define the view", "behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def home_page(request): csrf_token =", "serializer_class = UserSerializer def home_page(request): csrf_token = {} csrf_token.update(csrf(request)) return render_to_response('home/home.html', csrf_token) def", "from __future__ import print_function from __future__ import unicode_literals from __future__ import division from", "model = User fields = ('url', 'username', 'email', 'is_staff') # ViewSets define the", "-*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division", "from django.template.context_processors import csrf from rest_framework import serializers, viewsets # Serializers define the", "Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields", "render_to_response from django.template.context_processors import csrf from rest_framework import serializers, viewsets # Serializers define", "django.contrib.auth.models import User from django.shortcuts import render_to_response from django.template.context_processors import csrf from rest_framework", "the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url',", "django.template.context_processors import csrf from rest_framework import serializers, viewsets # Serializers define the API", "('url', 'username', 'email', 'is_staff') # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset", "= ('url', 'username', 'email', 'is_staff') # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet):", "class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def home_page(request): csrf_token = {}", "-*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from", "rest_framework import serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class", "from django.contrib.auth.models import User from django.shortcuts import render_to_response from django.template.context_processors import csrf from", "from rest_framework import serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer):", "UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def home_page(request): csrf_token = {} csrf_token.update(csrf(request))", "queryset = User.objects.all() serializer_class = UserSerializer def home_page(request): csrf_token = {} csrf_token.update(csrf(request)) return", "from django.shortcuts import render_to_response from django.template.context_processors import csrf from rest_framework import serializers, viewsets", "import render_to_response from django.template.context_processors import csrf from rest_framework import serializers, viewsets # Serializers", "def home_page(request): csrf_token = {} csrf_token.update(csrf(request)) return render_to_response('home/home.html', csrf_token) def compare(request): return render_to_response('home/compare.html')", "'email', 'is_staff') # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all()", "User fields = ('url', 'username', 'email', 'is_staff') # ViewSets define the view behavior.", "unicode_literals from __future__ import division from django.contrib.auth.models import User from django.shortcuts import render_to_response", "class Meta: model = User fields = ('url', 'username', 'email', 'is_staff') # ViewSets", "coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__", "# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals", "= UserSerializer def home_page(request): csrf_token = {} csrf_token.update(csrf(request)) return render_to_response('home/home.html', csrf_token) def compare(request):", "the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def home_page(request):", "API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username',", "class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'is_staff')", "from __future__ import division from django.contrib.auth.models import User from django.shortcuts import render_to_response from", "serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model", "# Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User", "representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email',", "'username', 'email', 'is_staff') # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset =", "import print_function from __future__ import unicode_literals from __future__ import division from django.contrib.auth.models import", "import csrf from rest_framework import serializers, viewsets # Serializers define the API representation.", "import unicode_literals from __future__ import division from django.contrib.auth.models import User from django.shortcuts import", "UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'is_staff') #" ]
[ "lth * (lth + 1) / (2 * np.pi) return nl_th else: if", "* bin_size + 2 bin_hi = (bins + 1) * bin_size + 1", "not None: ps[f] = ps[f][:lmax] if output_type == \"Cl\": ps[f] /= scale if", "lmax: integer the maximum multipole to consider spectra: list of strings needed for", "integer the number of bins lmax: integer the maximum multipole to consider file_name:", "Parameters ---------- bin_size: float the size of the bins n_bins: integer the number", "(fl[loc]).mean() return bin_cent, fl_bin def beam_from_fwhm(fwhm_arcminute, lmax): \"\"\"Compute the harmonic transform of the", "= camb.set_params(**camb_cosmo) results = camb.get_results(pars) powers = results.get_cmb_power_spectra(pars, CMB_unit=\"muK\") l = np.arange(lmin, lmax)", "\"\"\"Create a directory Parameters ---------- name: string the name of the directory \"\"\"", "maximum multipole to consider spectra: list of strings needed for spin0 and spin2", "\"\"\"Compute the harmonic transform of the beam given the beam full width half", "= np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60 * 180)) ** 2 /", "np.arange(2, lmax + 2) nl_th = {} if spectra is None: nl_th[\"TT\"] =", "\"TE\" ])} ps[\"ET\"] = ps[\"TE\"] for spec in [\"TB\", \"BT\", \"EB\", \"BE\" ]:", "filename : string the name of the CAMB lensed power spectrum you want", "---------- fwhm_arcminute: float full width half maximum in arcminute lmax: integer the maximum", "nl_th else: if rms_uKarcmin_pol is None: rms_uKarcmin_pol = rms_uKarcmin_T * np.sqrt(2) for spec", "= bins * bin_size + 2 bin_hi = (bins + 1) * bin_size", "np def ps_lensed_theory_to_dict(filename, output_type, lmax=None, start_at_zero=False): \"\"\"Read a lensed power spectrum from CAMB", "bin_cent = (bin_low + bin_hi) / 2 if lmax is not None: id", "and normalize it Parameters __________ beamfile: string the name of the beam file", "/ 2 if lmax is not None: id = np.where(bin_hi < lmax) bin_low,", "v in cosmo_params.items() if k not in [\"logA\", \"As\"]} camb_cosmo.update({\"As\": 1e-10*np.exp(cosmo_params[\"logA\"]), \"lmax\": lmax,", "read_binning_file(binning_file, lmax) n_bins = len(bin_hi) fl_bin = np.zeros(len(bin_cent)) for ibin in range(n_bins): loc", "2 nl_th[\"BB\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi / (60 * 180)) **", "is bin_low, bin_high, bin_mean Parameters ---------- binningfile: string the name of the binning", "bl[2 : lmax + 2] ** 2 ) if type == \"Dl\": nl_th[\"TT\"]", "(2 * np.pi) return nl_th else: if rms_uKarcmin_pol is None: rms_uKarcmin_pol = rms_uKarcmin_T", "CAMB and return a dictionnary Parameters ---------- filename : string the name of", "* np.pi) return nl_th def read_beam_file(beamfile, lmax=None): \"\"\"Read beam file with formal, l,", "output_type, lmax=None, start_at_zero=False): \"\"\"Read a lensed power spectrum from CAMB and return a", "(bin_low[i], bin_hi[i], bin_cent[i])) f.close() def read_binning_file(file_name, lmax): \"\"\"Read a binningFile and truncate it", "a directory Parameters ---------- name: string the name of the directory \"\"\" os.makedirs(name,", "---------- name: string the name of the directory \"\"\" os.makedirs(name, exist_ok=True) def naive_binning(l,", "the directory \"\"\" os.makedirs(name, exist_ok=True) def naive_binning(l, fl, binning_file, lmax): \"\"\"Bin a function", ":lmax + 2] ** 2 nl_th[\"EE\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi /", ": string 'Cl' or 'Dl' lmax: integer the maximum multipole to consider start_at_zero", "Parameters ---------- fwhm_arcminute: float full width half maximum in arcminute lmax: integer the", "bl = np.exp(-ell * (ell + 1) * fac ** 2 / 2.0)", "np.zeros((4, len(l))) if lmax is not None: l = l[:lmax] scale = l", "rms_uKarcmin_pol=None, beamfile=None): \"\"\"Return the effective noise power spectrum Nl/bl^2 given a beam file", "ps[f]) if start_at_zero: l = np.append(np.array([0, 1]), l) return l, ps def ps_from_params(cosmo_params,", "bin_size: float the size of the bins n_bins: integer the number of bins", "in [\"TB\", \"BT\", \"EB\", \"BE\" ]: ps[spec] = ps[\"TT\"] * 0 scale =", "camb to use this function\") if start_at_zero: lmin = 0 else: lmin =", "consider \"\"\" beam_fwhm_rad = np.deg2rad(fwhm_arcminute) / 60 fac = beam_fwhm_rad / np.sqrt(8 *", "string 'Cl' or 'Dl' lmax: integer the maximum multipole to consider start_at_zero :", "spectra=None, rms_uKarcmin_pol=None, beamfile=None): \"\"\"Return the effective noise power spectrum Nl/bl^2 given a beam", "the size of the bins n_bins: integer the number of bins lmax: integer", "* (rms_uKarcmin_T * np.pi / (60 * 180)) ** 2 / bl[2 :lmax", "beam = np.loadtxt(beamfile) l, bl = beam[:, 0], beam[:, 1] if lmax is", "< 2: bin_low[0] = 2 bin_hi = bin_hi.astype(int) bin_low = bin_low.astype(int) bin_size =", "the name of the beam transfer function (assuming it's given as a two", "1) * bin_size + 1 bin_cent = (bin_low + bin_hi) / 2 if", "it to disk Parameters ---------- bin_size: float the size of the bins n_bins:", "and lmax Parameters ---------- l: 1d integer array the multipoles fl: 1d float", "to consider \"\"\" beam_fwhm_rad = np.deg2rad(fwhm_arcminute) / 60 fac = beam_fwhm_rad / np.sqrt(8", "return a dictionnary Parameters ---------- filename : string the name of the CAMB", "np.pi) for f in fields: if lmax is not None: ps[f] = ps[f][:lmax]", "3.044, \"ombh2\": 0.02237, \"omch2\": 0.1200, \"ns\": 0.9649, \"Alens\": 1.0, \"tau\": 0.0544} output_type :", "= np.loadtxt(filename, unpack=True) ps[\"ET\"] = ps[\"TE\"].copy() ps[\"TB\"], ps[\"BT\"], ps[\"EB\"], ps[\"BE\"] = np.zeros((4, len(l)))", "---------- cosmo_params: dict dictionnary of cosmological parameters # e.g cosmo_params = {\"cosmomc_theta\":0.0104085, \"logA\":", "given as a two column file l,bl) \"\"\" if beamfile is not None:", "file \"\"\" bins = np.arange(n_bins) bin_low = bins * bin_size + 2 bin_hi", "if file_name is None: return bin_low, bin_hi, bin_cent else: f = open(\"%s\" %", "if type == \"Dl\": for spec in spectra: nl_th[spec] *= lth * (lth", "ps[:] /= scale[:] return l, ps def get_nlth_dict(rms_uKarcmin_T, type, lmax, spectra=None, rms_uKarcmin_pol=None, beamfile=None):", "= np.append(np.array([0, 0]), ps[f]) if start_at_zero: l = np.append(np.array([0, 1]), l) return l,", "scale = l * (l + 1) / (2 * np.pi) for f", "output_type : string 'Cl' or 'Dl' lmax: integer the maximum multipole to consider", "parameters # e.g cosmo_params = {\"cosmomc_theta\":0.0104085, \"logA\": 3.044, \"ombh2\": 0.02237, \"omch2\": 0.1200, \"ns\":", "\"\"\"Read beam file with formal, l, bl, stuff and normalize it Parameters __________", "ps[\"BT\"], ps[\"EB\"], ps[\"BE\"] = np.zeros((4, len(l))) if lmax is not None: l =", "nl_th[\"TT\"] *= lth * (lth + 1) / (2 * np.pi) return nl_th", "if k not in [\"logA\", \"As\"]} camb_cosmo.update({\"As\": 1e-10*np.exp(cosmo_params[\"logA\"]), \"lmax\": lmax, \"lens_potential_accuracy\": 1}) pars", "function ---------- cosmo_params: dict dictionnary of cosmological parameters # e.g cosmo_params = {\"cosmomc_theta\":0.0104085,", "(60 * 180)) ** 2 / bl[2 : lmax + 2] ** 2", "file and a noise rms Parameters ---------- rms_uKarcmin_T: float the temperature noise rms", "at l=0 and cl(l=0) and cl(l=1) are set to 0 \"\"\" fields =", "l, ps[\"TT\"], ps[\"EE\"], ps[\"BB\"], ps[\"TE\"] = np.loadtxt(filename, unpack=True) ps[\"ET\"] = ps[\"TE\"].copy() ps[\"TB\"], ps[\"BT\"],", "ps[\"BE\"] = np.zeros((4, len(l))) if lmax is not None: l = l[:lmax] scale", "column file l,bl) \"\"\" if beamfile is not None: l, bl = np.loadtxt(beamfile,", "np.arange(lmin, lmax) ps = {spec: powers[\"total\"][l][:, count] for count, spec in enumerate([\"TT\", \"EE\",", "beamfile: string the name of the beam transfer function (assuming it's given as", "= np.ones(lmax) * (rms_uKarcmin_pol * np.pi / (60 * 180)) ** 2 /", "/ (2 * np.pi) if output_type == \"Cl\": if start_at_zero: ps[2:] /= scale[2:]", "the harmonic transform of the beam given the beam full width half maximum", "cross correlation, the arrangement of the spectra rms_uKarcmin_pol: float the polarisation noise rms", "0 else: lmin = 2 camb_cosmo = {k: v for k, v in", "1d integer array the multipoles fl: 1d float array the 1-dimensional function to", "cosmological parameters # e.g cosmo_params = {\"cosmomc_theta\":0.0104085, \"logA\": 3.044, \"ombh2\": 0.02237, \"omch2\": 0.1200,", "if start_at_zero: ps[2:] /= scale[2:] else: ps[:] /= scale[:] return l, ps def", "type: string 'Cl' or 'Dl' lmax: integer the maximum multipole to consider spectra:", "bin_low[0] < 2: bin_low[0] = 2 bin_hi = bin_hi.astype(int) bin_low = bin_low.astype(int) bin_size", "bin_hi) / 2 if lmax is not None: id = np.where(bin_hi < lmax)", "= bin_low.astype(int) bin_size = bin_hi - bin_low + 1 return bin_low, bin_hi, bin_cent,", "= np.zeros(lmax) nl_th[\"TT\"] = np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60 * 180))", "a beam file and a noise rms Parameters ---------- rms_uKarcmin_T: float the temperature", "bin_hi[id], bin_cent[id] if file_name is None: return bin_low, bin_hi, bin_cent else: f =", "power spectrum from CAMB and return a dictionnary Parameters ---------- filename : string", "ps = {} l, ps[\"TT\"], ps[\"EE\"], ps[\"BB\"], ps[\"TE\"] = np.loadtxt(filename, unpack=True) ps[\"ET\"] =", "full width half maximum in arcminute lmax: integer the maximum multipole to consider", "180)) ** 2 / bl[2 :lmax + 2] ** 2 if type ==", "2 nl_th[\"EE\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi / (60 * 180)) **", "for spec in spectra: nl_th[spec] = np.zeros(lmax) nl_th[\"TT\"] = np.ones(lmax) * (rms_uKarcmin_T *", "l = l[:lmax] scale = l * (l + 1) / (2 *", "\"Dl\": for spec in spectra: nl_th[spec] *= lth * (lth + 1) /", "directory \"\"\" os.makedirs(name, exist_ok=True) def naive_binning(l, fl, binning_file, lmax): \"\"\"Bin a function of", "= 0 else: lmin = 2 camb_cosmo = {k: v for k, v", "integer the maximum multipole to consider \"\"\" beam = np.loadtxt(beamfile) l, bl =", "unpack=True) ps[\"ET\"] = ps[\"TE\"].copy() ps[\"TB\"], ps[\"BT\"], ps[\"EB\"], ps[\"BE\"] = np.zeros((4, len(l))) if lmax", "for count, spec in enumerate([\"TT\", \"EE\", \"BB\", \"TE\" ])} ps[\"ET\"] = ps[\"TE\"] for", "to consider \"\"\" beam = np.loadtxt(beamfile) l, bl = beam[:, 0], beam[:, 1]", "= 2 bin_hi = bin_hi.astype(int) bin_low = bin_low.astype(int) bin_size = bin_hi - bin_low", "lmax): \"\"\"Bin a function of l given a binning file and lmax Parameters", "(60 * 180)) ** 2 / bl[2 :lmax + 2] ** 2 nl_th[\"EE\"]", "if lmax is not None: id = np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent", "import camb except ModuleNotFoundError: raise ModuleNotFoundError(\"you need to install camb to use this", "in uK.arcmin type: string 'Cl' or 'Dl' lmax: integer the maximum multipole to", "np.deg2rad(fwhm_arcminute) / 60 fac = beam_fwhm_rad / np.sqrt(8 * np.log(2)) ell = np.arange(2,", "noise rms Parameters ---------- rms_uKarcmin_T: float the temperature noise rms in uK.arcmin type:", "= np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if bin_low[0]", "(constant) binning file, and optionnaly write it to disk Parameters ---------- bin_size: float", "at l=0 and cl(l=0) and cl(l=1) are set to 0 else, start at", "lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if bin_low[0] < 2: bin_low[0]", "lmax, start_at_zero=False): \"\"\"Given a set of cosmological parameters compute the corresponding lensed power", "scale if start_at_zero: ps[f] = np.append(np.array([0, 0]), ps[f]) if start_at_zero: l = np.append(np.array([0,", "transform of the beam given the beam full width half maximum in arcminute", "\"BT\", \"EB\", \"BE\" ]: ps[spec] = ps[\"TT\"] * 0 scale = l *", "{} if spectra is None: nl_th[\"TT\"] = ( np.ones(lmax) * (rms_uKarcmin_T * np.pi", "it to lmax, if bin_low lower than 2, set it to 2. format", "= rms_uKarcmin_T * np.sqrt(2) for spec in spectra: nl_th[spec] = np.zeros(lmax) nl_th[\"TT\"] =", "180)) ** 2 / bl[2 : lmax + 2] ** 2 ) if", "and cl(l=0) and cl(l=1) are set to 0 else, start at l=2 \"\"\"", "have camb installed to use this function ---------- cosmo_params: dict dictionnary of cosmological", "2] ** 2 if type == \"Dl\": for spec in spectra: nl_th[spec] *=", "are set to 0 else, start at l=2 \"\"\" try: import camb except", "cosmo_params = {\"cosmomc_theta\":0.0104085, \"logA\": 3.044, \"ombh2\": 0.02237, \"omch2\": 0.1200, \"ns\": 0.9649, \"Alens\": 1.0,", "1) / (2 * np.pi) return nl_th else: if rms_uKarcmin_pol is None: rms_uKarcmin_pol", "lth * (lth + 1) / (2 * np.pi) return nl_th def read_beam_file(beamfile,", "binning_file, lmax): \"\"\"Bin a function of l given a binning file and lmax", "binning file and lmax Parameters ---------- l: 1d integer array the multipoles fl:", "set to 0 \"\"\" fields = [\"TT\", \"TE\", \"TB\", \"ET\", \"BT\", \"EE\", \"EB\",", "spectrum you want to read lmax : integer the maximum multipole (spectra will", "for i in range(len(bin_low)): f.write(\"%0.2f %0.2f %0.2f\\n\" % (bin_low[i], bin_hi[i], bin_cent[i])) f.close() def", "* 180)) ** 2 / bl[2 :lmax + 2] ** 2 if type", "or 'Dl' lmax: integer the maximum multipole to consider spectra: list of strings", "or 'Dl' lmax: integer the maximum multipole to consider start_at_zero : boolean if", "= np.deg2rad(fwhm_arcminute) / 60 fac = beam_fwhm_rad / np.sqrt(8 * np.log(2)) ell =", "def ps_lensed_theory_to_dict(filename, output_type, lmax=None, start_at_zero=False): \"\"\"Read a lensed power spectrum from CAMB and", "uK.arcmin beamfile: string the name of the beam transfer function (assuming it's given", "is not None: l, bl = np.loadtxt(beamfile, unpack=True) else: bl = np.ones(lmax +", "noise power spectrum Nl/bl^2 given a beam file and a noise rms Parameters", "= np.ones(lmax + 2) lth = np.arange(2, lmax + 2) nl_th = {}", "{} l, ps[\"TT\"], ps[\"EE\"], ps[\"BB\"], ps[\"TE\"] = np.loadtxt(filename, unpack=True) ps[\"ET\"] = ps[\"TE\"].copy() ps[\"TB\"],", "spin2 cross correlation, the arrangement of the spectra rms_uKarcmin_pol: float the polarisation noise", "is None: return bin_low, bin_hi, bin_cent else: f = open(\"%s\" % file_name, mode=\"w\")", "the number of bins lmax: integer the maximum multipole to consider file_name: string", "= bin_hi - bin_low + 1 return bin_low, bin_hi, bin_cent, bin_size def create_directory(name):", "compute the corresponding lensed power spectrum You need to have camb installed to", "def naive_binning(l, fl, binning_file, lmax): \"\"\"Bin a function of l given a binning", "in range(n_bins): loc = np.where((l >= bin_low[ibin]) & (l <= bin_hi[ibin])) fl_bin[ibin] =", "l) return l, ps def ps_from_params(cosmo_params, output_type, lmax, start_at_zero=False): \"\"\"Given a set of", "rms Parameters ---------- rms_uKarcmin_T: float the temperature noise rms in uK.arcmin type: string", "0.0544} output_type : string 'Cl' or 'Dl' lmax: integer the maximum multipole to", "lmax): \"\"\"Compute the harmonic transform of the beam given the beam full width", "ps def get_nlth_dict(rms_uKarcmin_T, type, lmax, spectra=None, rms_uKarcmin_pol=None, beamfile=None): \"\"\"Return the effective noise power", "'Cl' or 'Dl' lmax: integer the maximum multipole to consider start_at_zero : boolean", "return l, ps def get_nlth_dict(rms_uKarcmin_T, type, lmax, spectra=None, rms_uKarcmin_pol=None, beamfile=None): \"\"\"Return the effective", "be cut at) output_type : string 'Cl' or 'Dl' start_at_zero : boolean if", "(assuming it's given as a two column file l,bl) \"\"\" if beamfile is", "l, bl = np.loadtxt(beamfile, unpack=True) else: bl = np.ones(lmax + 2) lth =", "of the spectra rms_uKarcmin_pol: float the polarisation noise rms in uK.arcmin beamfile: string", "return nl_th def read_beam_file(beamfile, lmax=None): \"\"\"Read beam file with formal, l, bl, stuff", "** 2 ) if type == \"Dl\": nl_th[\"TT\"] *= lth * (lth +", "np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if bin_low[0] <", "np.pi / (60 * 180)) ** 2 / bl[2 :lmax + 2] **", "\"\"\"Create a (constant) binning file, and optionnaly write it to disk Parameters ----------", "the maximum multipole to consider start_at_zero : boolean if True, ps start at", "else: ps[:] /= scale[:] return l, ps def get_nlth_dict(rms_uKarcmin_T, type, lmax, spectra=None, rms_uKarcmin_pol=None,", "---------- filename : string the name of the CAMB lensed power spectrum you", "and cl(l=1) are set to 0 else, start at l=2 \"\"\" try: import", "np.pi) return nl_th else: if rms_uKarcmin_pol is None: rms_uKarcmin_pol = rms_uKarcmin_T * np.sqrt(2)", "get_nlth_dict(rms_uKarcmin_T, type, lmax, spectra=None, rms_uKarcmin_pol=None, beamfile=None): \"\"\"Return the effective noise power spectrum Nl/bl^2", "bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if file_name is None: return bin_low, bin_hi,", "\"EB\", \"BE\" ]: ps[spec] = ps[\"TT\"] * 0 scale = l * (l", "multipole to consider \"\"\" bin_low, bin_hi, bin_cent = np.loadtxt(file_name, unpack=True) id = np.where(bin_hi", "directory Parameters ---------- name: string the name of the directory \"\"\" os.makedirs(name, exist_ok=True)", "ps[2:] /= scale[2:] else: ps[:] /= scale[:] return l, ps def get_nlth_dict(rms_uKarcmin_T, type,", "np.exp(-ell * (ell + 1) * fac ** 2 / 2.0) return ell,", "spectra rms_uKarcmin_pol: float the polarisation noise rms in uK.arcmin beamfile: string the name", "np.arange(2, lmax) bl = np.exp(-ell * (ell + 1) * fac ** 2", "boolean if True, ps start at l=0 and cl(l=0) and cl(l=1) are set", "None: l, bl = l[:lmax], bl[:lmax] return l, bl / bl[0] def create_binning_file(bin_size,", "\"ombh2\": 0.02237, \"omch2\": 0.1200, \"ns\": 0.9649, \"Alens\": 1.0, \"tau\": 0.0544} output_type : string", "\"BE\", \"BB\"] ps = {} l, ps[\"TT\"], ps[\"EE\"], ps[\"BB\"], ps[\"TE\"] = np.loadtxt(filename, unpack=True)", "binning file, and optionnaly write it to disk Parameters ---------- bin_size: float the", "beam transfer function (assuming it's given as a two column file l,bl) \"\"\"", "= bin_hi.astype(int) bin_low = bin_low.astype(int) bin_size = bin_hi - bin_low + 1 return", "n_bins = len(bin_hi) fl_bin = np.zeros(len(bin_cent)) for ibin in range(n_bins): loc = np.where((l", "camb.set_params(**camb_cosmo) results = camb.get_results(pars) powers = results.get_cmb_power_spectra(pars, CMB_unit=\"muK\") l = np.arange(lmin, lmax) ps", "---------- bin_size: float the size of the bins n_bins: integer the number of", "\"BT\", \"EE\", \"EB\", \"BE\", \"BB\"] ps = {} l, ps[\"TT\"], ps[\"EE\"], ps[\"BB\"], ps[\"TE\"]", "type == \"Dl\": for spec in spectra: nl_th[spec] *= lth * (lth +", "exist_ok=True) def naive_binning(l, fl, binning_file, lmax): \"\"\"Bin a function of l given a", "in spectra: nl_th[spec] *= lth * (lth + 1) / (2 * np.pi)", "\"\"\" bin_low, bin_hi, bin_cent = np.loadtxt(file_name, unpack=True) id = np.where(bin_hi < lmax) bin_low,", "beam_fwhm_rad = np.deg2rad(fwhm_arcminute) / 60 fac = beam_fwhm_rad / np.sqrt(8 * np.log(2)) ell", "bin_size + 2 bin_hi = (bins + 1) * bin_size + 1 bin_cent", "+ 2 bin_hi = (bins + 1) * bin_size + 1 bin_cent =", "(lth + 1) / (2 * np.pi) return nl_th def read_beam_file(beamfile, lmax=None): \"\"\"Read", "0 \"\"\" fields = [\"TT\", \"TE\", \"TB\", \"ET\", \"BT\", \"EE\", \"EB\", \"BE\", \"BB\"]", "string the name of the beam file lmax: integer the maximum multipole to", "1.0, \"tau\": 0.0544} output_type : string 'Cl' or 'Dl' lmax: integer the maximum", "is None: nl_th[\"TT\"] = ( np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60 *", "correlation, the arrangement of the spectra rms_uKarcmin_pol: float the polarisation noise rms in", "2, set it to 2. format is bin_low, bin_high, bin_mean Parameters ---------- binningfile:", "if bin_low[0] < 2: bin_low[0] = 2 bin_hi = bin_hi.astype(int) bin_low = bin_low.astype(int)", "lmin = 0 else: lmin = 2 camb_cosmo = {k: v for k,", "{\"cosmomc_theta\":0.0104085, \"logA\": 3.044, \"ombh2\": 0.02237, \"omch2\": 0.1200, \"ns\": 0.9649, \"Alens\": 1.0, \"tau\": 0.0544}", "and return a dictionnary Parameters ---------- filename : string the name of the", "name of the binning file lmax: integer the maximum multipole to consider \"\"\"", "\"\"\"Bin a function of l given a binning file and lmax Parameters ----------", "if type == \"Dl\": nl_th[\"TT\"] *= lth * (lth + 1) / (2", "not None: id = np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id],", "the effective noise power spectrum Nl/bl^2 given a beam file and a noise", "consider file_name: string the name of the binning file \"\"\" bins = np.arange(n_bins)", "install camb to use this function\") if start_at_zero: lmin = 0 else: lmin", "* np.pi) for f in fields: if lmax is not None: ps[f] =", "spin0 and spin2 cross correlation, the arrangement of the spectra rms_uKarcmin_pol: float the", "float the polarisation noise rms in uK.arcmin beamfile: string the name of the", "l, ps def ps_from_params(cosmo_params, output_type, lmax, start_at_zero=False): \"\"\"Given a set of cosmological parameters", "the polarisation noise rms in uK.arcmin beamfile: string the name of the beam", "bl = np.ones(lmax + 2) lth = np.arange(2, lmax + 2) nl_th =", "= np.arange(n_bins) bin_low = bins * bin_size + 2 bin_hi = (bins +", "np.append(np.array([0, 0]), ps[f]) if start_at_zero: l = np.append(np.array([0, 1]), l) return l, ps", "+ bin_hi) / 2 if lmax is not None: id = np.where(bin_hi <", "to consider \"\"\" bin_low, bin_hi, bin_cent, bin_size = read_binning_file(binning_file, lmax) n_bins = len(bin_hi)", "= l * (l + 1) / (2 * np.pi) for f in", "lmax + 2) nl_th = {} if spectra is None: nl_th[\"TT\"] = (", ": string the name of the CAMB lensed power spectrum you want to", "f.write(\"%0.2f %0.2f %0.2f\\n\" % (bin_low[i], bin_hi[i], bin_cent[i])) f.close() def read_binning_file(file_name, lmax): \"\"\"Read a", "---------- l: 1d integer array the multipoles fl: 1d float array the 1-dimensional", "(spectra will be cut at) output_type : string 'Cl' or 'Dl' start_at_zero :", "to consider start_at_zero : boolean if True, ps start at l=0 and cl(l=0)", "k, v in cosmo_params.items() if k not in [\"logA\", \"As\"]} camb_cosmo.update({\"As\": 1e-10*np.exp(cosmo_params[\"logA\"]), \"lmax\":", "ibin in range(n_bins): loc = np.where((l >= bin_low[ibin]) & (l <= bin_hi[ibin])) fl_bin[ibin]", "* np.log(2)) ell = np.arange(2, lmax) bl = np.exp(-ell * (ell + 1)", "the beam full width half maximum in arcminute Parameters ---------- fwhm_arcminute: float full", "optionnaly write it to disk Parameters ---------- bin_size: float the size of the", "lmax, if bin_low lower than 2, set it to 2. format is bin_low,", "ps_lensed_theory_to_dict(filename, output_type, lmax=None, start_at_zero=False): \"\"\"Read a lensed power spectrum from CAMB and return", "{spec: powers[\"total\"][l][:, count] for count, spec in enumerate([\"TT\", \"EE\", \"BB\", \"TE\" ])} ps[\"ET\"]", "bin_low[id], bin_hi[id], bin_cent[id] if file_name is None: return bin_low, bin_hi, bin_cent else: f", "string the name of the directory \"\"\" os.makedirs(name, exist_ok=True) def naive_binning(l, fl, binning_file,", "bin_low, bin_hi, bin_cent, bin_size def create_directory(name): \"\"\"Create a directory Parameters ---------- name: string", "def read_binning_file(file_name, lmax): \"\"\"Read a binningFile and truncate it to lmax, if bin_low", "integer array the multipoles fl: 1d float array the 1-dimensional function to bin", "= np.zeros((4, len(l))) if lmax is not None: l = l[:lmax] scale =", "return l, ps def ps_from_params(cosmo_params, output_type, lmax, start_at_zero=False): \"\"\"Given a set of cosmological", ">= bin_low[ibin]) & (l <= bin_hi[ibin])) fl_bin[ibin] = (fl[loc]).mean() return bin_cent, fl_bin def", "+ 2] ** 2 ) if type == \"Dl\": nl_th[\"TT\"] *= lth *", "bin_size def create_directory(name): \"\"\"Create a directory Parameters ---------- name: string the name of", "camb installed to use this function ---------- cosmo_params: dict dictionnary of cosmological parameters", "l=2 \"\"\" try: import camb except ModuleNotFoundError: raise ModuleNotFoundError(\"you need to install camb", "0 scale = l * (l + 1) / (2 * np.pi) if", "string the name of the beam transfer function (assuming it's given as a", "*= lth * (lth + 1) / (2 * np.pi) return nl_th def", "the maximum multipole to consider \"\"\" bin_low, bin_hi, bin_cent = np.loadtxt(file_name, unpack=True) id", "(lth + 1) / (2 * np.pi) return nl_th else: if rms_uKarcmin_pol is", "id = np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if", "in [\"logA\", \"As\"]} camb_cosmo.update({\"As\": 1e-10*np.exp(cosmo_params[\"logA\"]), \"lmax\": lmax, \"lens_potential_accuracy\": 1}) pars = camb.set_params(**camb_cosmo) results", "\"BE\" ]: ps[spec] = ps[\"TT\"] * 0 scale = l * (l +", "integer the maximum multipole to consider start_at_zero : boolean if True, ps start", "l = np.arange(lmin, lmax) ps = {spec: powers[\"total\"][l][:, count] for count, spec in", "n_bins: integer the number of bins lmax: integer the maximum multipole to consider", "bin_low lower than 2, set it to 2. format is bin_low, bin_high, bin_mean", "float array the 1-dimensional function to bin binning_file: string the name of the", "the spectra rms_uKarcmin_pol: float the polarisation noise rms in uK.arcmin beamfile: string the", "return bin_low, bin_hi, bin_cent, bin_size def create_directory(name): \"\"\"Create a directory Parameters ---------- name:", "def read_beam_file(beamfile, lmax=None): \"\"\"Read beam file with formal, l, bl, stuff and normalize", "(2 * np.pi) return nl_th def read_beam_file(beamfile, lmax=None): \"\"\"Read beam file with formal,", "ps[\"BB\"], ps[\"TE\"] = np.loadtxt(filename, unpack=True) ps[\"ET\"] = ps[\"TE\"].copy() ps[\"TB\"], ps[\"BT\"], ps[\"EB\"], ps[\"BE\"] =", "if lmax is not None: l, bl = l[:lmax], bl[:lmax] return l, bl", "bin_cent else: f = open(\"%s\" % file_name, mode=\"w\") for i in range(len(bin_low)): f.write(\"%0.2f", "Nl/bl^2 given a beam file and a noise rms Parameters ---------- rms_uKarcmin_T: float", "1-dimensional function to bin binning_file: string the name of the binning file lmax:", "2 bin_hi = bin_hi.astype(int) bin_low = bin_low.astype(int) bin_size = bin_hi - bin_low +", "a lensed power spectrum from CAMB and return a dictionnary Parameters ---------- filename", "else: f = open(\"%s\" % file_name, mode=\"w\") for i in range(len(bin_low)): f.write(\"%0.2f %0.2f", "\"EB\", \"BE\", \"BB\"] ps = {} l, ps[\"TT\"], ps[\"EE\"], ps[\"BB\"], ps[\"TE\"] = np.loadtxt(filename,", "the name of the binning file \"\"\" bins = np.arange(n_bins) bin_low = bins", "= ( np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60 * 180)) ** 2", "< lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if bin_low[0] < 2:", "to disk Parameters ---------- bin_size: float the size of the bins n_bins: integer", "to use this function\") if start_at_zero: lmin = 0 else: lmin = 2", "binning file lmax: integer the maximum multipole to consider \"\"\" bin_low, bin_hi, bin_cent", "power spectrum Nl/bl^2 given a beam file and a noise rms Parameters ----------", "lensed power spectrum from CAMB and return a dictionnary Parameters ---------- filename :", "consider start_at_zero : boolean if True, ps start at l=0 and cl(l=0) and", "= ps[\"TT\"] * 0 scale = l * (l + 1) / (2", "+ 1) / (2 * np.pi) return nl_th else: if rms_uKarcmin_pol is None:", "count] for count, spec in enumerate([\"TT\", \"EE\", \"BB\", \"TE\" ])} ps[\"ET\"] = ps[\"TE\"]", "0.02237, \"omch2\": 0.1200, \"ns\": 0.9649, \"Alens\": 1.0, \"tau\": 0.0544} output_type : string 'Cl'", "set of cosmological parameters compute the corresponding lensed power spectrum You need to", "nl_th[\"TT\"] = np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60 * 180)) ** 2", "* 180)) ** 2 / bl[2 :lmax + 2] ** 2 nl_th[\"BB\"] =", "camb_cosmo = {k: v for k, v in cosmo_params.items() if k not in", "f.close() def read_binning_file(file_name, lmax): \"\"\"Read a binningFile and truncate it to lmax, if", "function (assuming it's given as a two column file l,bl) \"\"\" if beamfile", "= {\"cosmomc_theta\":0.0104085, \"logA\": 3.044, \"ombh2\": 0.02237, \"omch2\": 0.1200, \"ns\": 0.9649, \"Alens\": 1.0, \"tau\":", "% (bin_low[i], bin_hi[i], bin_cent[i])) f.close() def read_binning_file(file_name, lmax): \"\"\"Read a binningFile and truncate", "= results.get_cmb_power_spectra(pars, CMB_unit=\"muK\") l = np.arange(lmin, lmax) ps = {spec: powers[\"total\"][l][:, count] for", "]: ps[spec] = ps[\"TT\"] * 0 scale = l * (l + 1)", "in arcminute lmax: integer the maximum multipole to consider \"\"\" beam_fwhm_rad = np.deg2rad(fwhm_arcminute)", "to consider spectra: list of strings needed for spin0 and spin2 cross correlation,", "bl = np.loadtxt(beamfile, unpack=True) else: bl = np.ones(lmax + 2) lth = np.arange(2,", "lmax: integer the maximum multipole to consider start_at_zero : boolean if True, ps", "the maximum multipole (spectra will be cut at) output_type : string 'Cl' or", "raise ModuleNotFoundError(\"you need to install camb to use this function\") if start_at_zero: lmin", "= l[:lmax] scale = l * (l + 1) / (2 * np.pi)", "= ps[\"TE\"] for spec in [\"TB\", \"BT\", \"EB\", \"BE\" ]: ps[spec] = ps[\"TT\"]", "ps[\"TT\"] * 0 scale = l * (l + 1) / (2 *", "/= scale[:] return l, ps def get_nlth_dict(rms_uKarcmin_T, type, lmax, spectra=None, rms_uKarcmin_pol=None, beamfile=None): \"\"\"Return", "function to bin binning_file: string the name of the binning file lmax: integer", "bin_size = read_binning_file(binning_file, lmax) n_bins = len(bin_hi) fl_bin = np.zeros(len(bin_cent)) for ibin in", "of the CAMB lensed power spectrum you want to read lmax : integer", "2 bin_hi = (bins + 1) * bin_size + 1 bin_cent = (bin_low", "\"As\"]} camb_cosmo.update({\"As\": 1e-10*np.exp(cosmo_params[\"logA\"]), \"lmax\": lmax, \"lens_potential_accuracy\": 1}) pars = camb.set_params(**camb_cosmo) results = camb.get_results(pars)", "beam_from_fwhm(fwhm_arcminute, lmax): \"\"\"Compute the harmonic transform of the beam given the beam full", "a set of cosmological parameters compute the corresponding lensed power spectrum You need", "/ (60 * 180)) ** 2 / bl[2 : lmax + 2] **", "2 / bl[2 :lmax + 2] ** 2 nl_th[\"BB\"] = np.ones(lmax) * (rms_uKarcmin_pol", "if start_at_zero: ps[f] = np.append(np.array([0, 0]), ps[f]) if start_at_zero: l = np.append(np.array([0, 1]),", "maximum multipole (spectra will be cut at) output_type : string 'Cl' or 'Dl'", "CMB_unit=\"muK\") l = np.arange(lmin, lmax) ps = {spec: powers[\"total\"][l][:, count] for count, spec", "spectrum Nl/bl^2 given a beam file and a noise rms Parameters ---------- rms_uKarcmin_T:", "l, bl / bl[0] def create_binning_file(bin_size, n_bins, lmax=None, file_name=None): \"\"\"Create a (constant) binning", "scale = l * (l + 1) / (2 * np.pi) if output_type", "len(bin_hi) fl_bin = np.zeros(len(bin_cent)) for ibin in range(n_bins): loc = np.where((l >= bin_low[ibin])", "np.loadtxt(filename, unpack=True) ps[\"ET\"] = ps[\"TE\"].copy() ps[\"TB\"], ps[\"BT\"], ps[\"EB\"], ps[\"BE\"] = np.zeros((4, len(l))) if", "ps[\"ET\"] = ps[\"TE\"].copy() ps[\"TB\"], ps[\"BT\"], ps[\"EB\"], ps[\"BE\"] = np.zeros((4, len(l))) if lmax is", "spec in enumerate([\"TT\", \"EE\", \"BB\", \"TE\" ])} ps[\"ET\"] = ps[\"TE\"] for spec in", "for spec in [\"TB\", \"BT\", \"EB\", \"BE\" ]: ps[spec] = ps[\"TT\"] * 0", "bin binning_file: string the name of the binning file lmax: integer the maximum", "2 ) if type == \"Dl\": nl_th[\"TT\"] *= lth * (lth + 1)", "bl[2 :lmax + 2] ** 2 nl_th[\"BB\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi", "* (lth + 1) / (2 * np.pi) return nl_th else: if rms_uKarcmin_pol", "of the bins n_bins: integer the number of bins lmax: integer the maximum", "pars = camb.set_params(**camb_cosmo) results = camb.get_results(pars) powers = results.get_cmb_power_spectra(pars, CMB_unit=\"muK\") l = np.arange(lmin,", "= l[:lmax], bl[:lmax] return l, bl / bl[0] def create_binning_file(bin_size, n_bins, lmax=None, file_name=None):", "- bin_low + 1 return bin_low, bin_hi, bin_cent, bin_size def create_directory(name): \"\"\"Create a", "is not None: l = l[:lmax] scale = l * (l + 1)", "rms in uK.arcmin type: string 'Cl' or 'Dl' lmax: integer the maximum multipole", "lmax: integer the maximum multipole to consider \"\"\" beam_fwhm_rad = np.deg2rad(fwhm_arcminute) / 60", "binning_file: string the name of the binning file lmax: integer the maximum multipole", "beam[:, 1] if lmax is not None: l, bl = l[:lmax], bl[:lmax] return", "multipole to consider \"\"\" beam_fwhm_rad = np.deg2rad(fwhm_arcminute) / 60 fac = beam_fwhm_rad /", "2: bin_low[0] = 2 bin_hi = bin_hi.astype(int) bin_low = bin_low.astype(int) bin_size = bin_hi", "np.zeros(lmax) nl_th[\"TT\"] = np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60 * 180)) **", "\"\"\" Utils for pspy. \"\"\" import os import numpy as np def ps_lensed_theory_to_dict(filename,", "1] if lmax is not None: l, bl = l[:lmax], bl[:lmax] return l,", "a binningFile and truncate it to lmax, if bin_low lower than 2, set", "1}) pars = camb.set_params(**camb_cosmo) results = camb.get_results(pars) powers = results.get_cmb_power_spectra(pars, CMB_unit=\"muK\") l =", "= {k: v for k, v in cosmo_params.items() if k not in [\"logA\",", "the temperature noise rms in uK.arcmin type: string 'Cl' or 'Dl' lmax: integer", "'Dl' lmax: integer the maximum multipole to consider spectra: list of strings needed", "lower than 2, set it to 2. format is bin_low, bin_high, bin_mean Parameters", "spectra: list of strings needed for spin0 and spin2 cross correlation, the arrangement", "np.ones(lmax + 2) lth = np.arange(2, lmax + 2) nl_th = {} if", "need to have camb installed to use this function ---------- cosmo_params: dict dictionnary", "multipole to consider \"\"\" bin_low, bin_hi, bin_cent, bin_size = read_binning_file(binning_file, lmax) n_bins =", "dictionnary Parameters ---------- filename : string the name of the CAMB lensed power", "bin_hi, bin_cent else: f = open(\"%s\" % file_name, mode=\"w\") for i in range(len(bin_low)):", "bins n_bins: integer the number of bins lmax: integer the maximum multipole to", "= beam[:, 0], beam[:, 1] if lmax is not None: l, bl =", "arcminute Parameters ---------- fwhm_arcminute: float full width half maximum in arcminute lmax: integer", "this function\") if start_at_zero: lmin = 0 else: lmin = 2 camb_cosmo =", "spectra: nl_th[spec] *= lth * (lth + 1) / (2 * np.pi) return", "if start_at_zero: lmin = 0 else: lmin = 2 camb_cosmo = {k: v", "lmax) ps = {spec: powers[\"total\"][l][:, count] for count, spec in enumerate([\"TT\", \"EE\", \"BB\",", "l * (l + 1) / (2 * np.pi) for f in fields:", "ell = np.arange(2, lmax) bl = np.exp(-ell * (ell + 1) * fac", "to lmax, if bin_low lower than 2, set it to 2. format is", "start at l=2 \"\"\" try: import camb except ModuleNotFoundError: raise ModuleNotFoundError(\"you need to", "two column file l,bl) \"\"\" if beamfile is not None: l, bl =", ") if type == \"Dl\": nl_th[\"TT\"] *= lth * (lth + 1) /", "= np.arange(2, lmax) bl = np.exp(-ell * (ell + 1) * fac **", "= np.append(np.array([0, 1]), l) return l, ps def ps_from_params(cosmo_params, output_type, lmax, start_at_zero=False): \"\"\"Given", "start_at_zero=False): \"\"\"Given a set of cosmological parameters compute the corresponding lensed power spectrum", "ModuleNotFoundError(\"you need to install camb to use this function\") if start_at_zero: lmin =", "bin_low, bin_hi, bin_cent else: f = open(\"%s\" % file_name, mode=\"w\") for i in", "+ 1) / (2 * np.pi) for f in fields: if lmax is", "powers = results.get_cmb_power_spectra(pars, CMB_unit=\"muK\") l = np.arange(lmin, lmax) ps = {spec: powers[\"total\"][l][:, count]", "+ 2) lth = np.arange(2, lmax + 2) nl_th = {} if spectra", "if start_at_zero: l = np.append(np.array([0, 1]), l) return l, ps def ps_from_params(cosmo_params, output_type,", "type == \"Dl\": nl_th[\"TT\"] *= lth * (lth + 1) / (2 *", "60 fac = beam_fwhm_rad / np.sqrt(8 * np.log(2)) ell = np.arange(2, lmax) bl", "'Dl' lmax: integer the maximum multipole to consider start_at_zero : boolean if True,", "l, ps def get_nlth_dict(rms_uKarcmin_T, type, lmax, spectra=None, rms_uKarcmin_pol=None, beamfile=None): \"\"\"Return the effective noise", "bin_low = bins * bin_size + 2 bin_hi = (bins + 1) *", "maximum multipole to consider file_name: string the name of the binning file \"\"\"", "* (rms_uKarcmin_T * np.pi / (60 * 180)) ** 2 / bl[2 :", "\"Dl\": nl_th[\"TT\"] *= lth * (lth + 1) / (2 * np.pi) return", "= bin_low[id], bin_hi[id], bin_cent[id] if bin_low[0] < 2: bin_low[0] = 2 bin_hi =", "i in range(len(bin_low)): f.write(\"%0.2f %0.2f %0.2f\\n\" % (bin_low[i], bin_hi[i], bin_cent[i])) f.close() def read_binning_file(file_name,", "** 2 / bl[2 : lmax + 2] ** 2 ) if type", "(l + 1) / (2 * np.pi) for f in fields: if lmax", "lmax=None, file_name=None): \"\"\"Create a (constant) binning file, and optionnaly write it to disk", "if output_type == \"Cl\": ps[f] /= scale if start_at_zero: ps[f] = np.append(np.array([0, 0]),", "the beam transfer function (assuming it's given as a two column file l,bl)", "binning file \"\"\" bins = np.arange(n_bins) bin_low = bins * bin_size + 2", "read_binning_file(file_name, lmax): \"\"\"Read a binningFile and truncate it to lmax, if bin_low lower", "mode=\"w\") for i in range(len(bin_low)): f.write(\"%0.2f %0.2f %0.2f\\n\" % (bin_low[i], bin_hi[i], bin_cent[i])) f.close()", "a dictionnary Parameters ---------- filename : string the name of the CAMB lensed", "<= bin_hi[ibin])) fl_bin[ibin] = (fl[loc]).mean() return bin_cent, fl_bin def beam_from_fwhm(fwhm_arcminute, lmax): \"\"\"Compute the", "spectra: nl_th[spec] = np.zeros(lmax) nl_th[\"TT\"] = np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60", "name of the CAMB lensed power spectrum you want to read lmax :", "(l <= bin_hi[ibin])) fl_bin[ibin] = (fl[loc]).mean() return bin_cent, fl_bin def beam_from_fwhm(fwhm_arcminute, lmax): \"\"\"Compute", "== \"Cl\": if start_at_zero: ps[2:] /= scale[2:] else: ps[:] /= scale[:] return l,", "bin_hi = (bins + 1) * bin_size + 1 bin_cent = (bin_low +", "l, bl = l[:lmax], bl[:lmax] return l, bl / bl[0] def create_binning_file(bin_size, n_bins,", "ps[\"TE\"] = np.loadtxt(filename, unpack=True) ps[\"ET\"] = ps[\"TE\"].copy() ps[\"TB\"], ps[\"BT\"], ps[\"EB\"], ps[\"BE\"] = np.zeros((4,", "*= lth * (lth + 1) / (2 * np.pi) return nl_th else:", "cosmo_params.items() if k not in [\"logA\", \"As\"]} camb_cosmo.update({\"As\": 1e-10*np.exp(cosmo_params[\"logA\"]), \"lmax\": lmax, \"lens_potential_accuracy\": 1})", "** 2 / bl[2 :lmax + 2] ** 2 nl_th[\"EE\"] = np.ones(lmax) *", "** 2 / bl[2 :lmax + 2] ** 2 if type == \"Dl\":", "\"BB\", \"TE\" ])} ps[\"ET\"] = ps[\"TE\"] for spec in [\"TB\", \"BT\", \"EB\", \"BE\"", "/ bl[0] def create_binning_file(bin_size, n_bins, lmax=None, file_name=None): \"\"\"Create a (constant) binning file, and", "* np.sqrt(2) for spec in spectra: nl_th[spec] = np.zeros(lmax) nl_th[\"TT\"] = np.ones(lmax) *", "and optionnaly write it to disk Parameters ---------- bin_size: float the size of", "truncate it to lmax, if bin_low lower than 2, set it to 2.", "bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if bin_low[0] < 2: bin_low[0] = 2", "multipoles fl: 1d float array the 1-dimensional function to bin binning_file: string the", "is not None: id = np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent = bin_low[id],", "bin_cent, fl_bin def beam_from_fwhm(fwhm_arcminute, lmax): \"\"\"Compute the harmonic transform of the beam given", "\"ns\": 0.9649, \"Alens\": 1.0, \"tau\": 0.0544} output_type : string 'Cl' or 'Dl' lmax:", "= open(\"%s\" % file_name, mode=\"w\") for i in range(len(bin_low)): f.write(\"%0.2f %0.2f %0.2f\\n\" %", "string the name of the binning file lmax: integer the maximum multipole to", "integer the maximum multipole to consider \"\"\" bin_low, bin_hi, bin_cent, bin_size = read_binning_file(binning_file,", "integer the maximum multipole to consider spectra: list of strings needed for spin0", "start_at_zero: ps[f] = np.append(np.array([0, 0]), ps[f]) if start_at_zero: l = np.append(np.array([0, 1]), l)", "np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60 * 180)) ** 2 / bl[2", ": lmax + 2] ** 2 ) if type == \"Dl\": nl_th[\"TT\"] *=", "[\"TT\", \"TE\", \"TB\", \"ET\", \"BT\", \"EE\", \"EB\", \"BE\", \"BB\"] ps = {} l,", "(rms_uKarcmin_T * np.pi / (60 * 180)) ** 2 / bl[2 :lmax +", "file and lmax Parameters ---------- l: 1d integer array the multipoles fl: 1d", "unpack=True) id = np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id]", "== \"Cl\": ps[f] /= scale if start_at_zero: ps[f] = np.append(np.array([0, 0]), ps[f]) if", "powers[\"total\"][l][:, count] for count, spec in enumerate([\"TT\", \"EE\", \"BB\", \"TE\" ])} ps[\"ET\"] =", "nl_th[spec] *= lth * (lth + 1) / (2 * np.pi) return nl_th", "lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if file_name is None: return", "formal, l, bl, stuff and normalize it Parameters __________ beamfile: string the name", "binningfile: string the name of the binning file lmax: integer the maximum multipole", "np.sqrt(8 * np.log(2)) ell = np.arange(2, lmax) bl = np.exp(-ell * (ell +", "pspy. \"\"\" import os import numpy as np def ps_lensed_theory_to_dict(filename, output_type, lmax=None, start_at_zero=False):", "1 return bin_low, bin_hi, bin_cent, bin_size def create_directory(name): \"\"\"Create a directory Parameters ----------", "to consider file_name: string the name of the binning file \"\"\" bins =", "lmin = 2 camb_cosmo = {k: v for k, v in cosmo_params.items() if", "width half maximum in arcminute Parameters ---------- fwhm_arcminute: float full width half maximum", "* np.pi) if output_type == \"Cl\": if start_at_zero: ps[2:] /= scale[2:] else: ps[:]", "= 2 camb_cosmo = {k: v for k, v in cosmo_params.items() if k", "\"\"\"Read a binningFile and truncate it to lmax, if bin_low lower than 2,", "lmax is not None: l, bl = l[:lmax], bl[:lmax] return l, bl /", "lmax is not None: ps[f] = ps[f][:lmax] if output_type == \"Cl\": ps[f] /=", "results.get_cmb_power_spectra(pars, CMB_unit=\"muK\") l = np.arange(lmin, lmax) ps = {spec: powers[\"total\"][l][:, count] for count,", "the beam file lmax: integer the maximum multipole to consider \"\"\" beam =", "else: lmin = 2 camb_cosmo = {k: v for k, v in cosmo_params.items()", "multipole to consider start_at_zero : boolean if True, ps start at l=0 and", "= np.loadtxt(file_name, unpack=True) id = np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent = bin_low[id],", "None: id = np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id]", "bin_low, bin_high, bin_mean Parameters ---------- binningfile: string the name of the binning file", "cl(l=0) and cl(l=1) are set to 0 \"\"\" fields = [\"TT\", \"TE\", \"TB\",", "parameters compute the corresponding lensed power spectrum You need to have camb installed", "beam file lmax: integer the maximum multipole to consider \"\"\" beam = np.loadtxt(beamfile)", "def ps_from_params(cosmo_params, output_type, lmax, start_at_zero=False): \"\"\"Given a set of cosmological parameters compute the", "consider \"\"\" beam = np.loadtxt(beamfile) l, bl = beam[:, 0], beam[:, 1] if", ": integer the maximum multipole (spectra will be cut at) output_type : string", "as np def ps_lensed_theory_to_dict(filename, output_type, lmax=None, start_at_zero=False): \"\"\"Read a lensed power spectrum from", "Parameters ---------- binningfile: string the name of the binning file lmax: integer the", "beamfile=None): \"\"\"Return the effective noise power spectrum Nl/bl^2 given a beam file and", "** 2 nl_th[\"BB\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi / (60 * 180))", "(60 * 180)) ** 2 / bl[2 :lmax + 2] ** 2 if", "(bin_low + bin_hi) / 2 if lmax is not None: id = np.where(bin_hi", "beamfile is not None: l, bl = np.loadtxt(beamfile, unpack=True) else: bl = np.ones(lmax", "* np.pi / (60 * 180)) ** 2 / bl[2 :lmax + 2]", "Parameters ---------- l: 1d integer array the multipoles fl: 1d float array the", "cosmo_params: dict dictionnary of cosmological parameters # e.g cosmo_params = {\"cosmomc_theta\":0.0104085, \"logA\": 3.044,", "= len(bin_hi) fl_bin = np.zeros(len(bin_cent)) for ibin in range(n_bins): loc = np.where((l >=", "bins * bin_size + 2 bin_hi = (bins + 1) * bin_size +", "multipole (spectra will be cut at) output_type : string 'Cl' or 'Dl' start_at_zero", "ps[\"ET\"] = ps[\"TE\"] for spec in [\"TB\", \"BT\", \"EB\", \"BE\" ]: ps[spec] =", "\"Alens\": 1.0, \"tau\": 0.0544} output_type : string 'Cl' or 'Dl' lmax: integer the", "/ bl[2 :lmax + 2] ** 2 if type == \"Dl\": for spec", "2 if lmax is not None: id = np.where(bin_hi < lmax) bin_low, bin_hi,", "width half maximum in arcminute lmax: integer the maximum multipole to consider \"\"\"", "of the beam file lmax: integer the maximum multipole to consider \"\"\" beam", "binning file lmax: integer the maximum multipole to consider \"\"\" bin_low, bin_hi, bin_cent,", "spec in [\"TB\", \"BT\", \"EB\", \"BE\" ]: ps[spec] = ps[\"TT\"] * 0 scale", "if bin_low lower than 2, set it to 2. format is bin_low, bin_high,", "start at l=0 and cl(l=0) and cl(l=1) are set to 0 else, start", "= (bin_low + bin_hi) / 2 if lmax is not None: id =", "not None: l, bl = l[:lmax], bl[:lmax] return l, bl / bl[0] def", "bl[:lmax] return l, bl / bl[0] def create_binning_file(bin_size, n_bins, lmax=None, file_name=None): \"\"\"Create a", "lensed power spectrum you want to read lmax : integer the maximum multipole", "bin_low = bin_low.astype(int) bin_size = bin_hi - bin_low + 1 return bin_low, bin_hi,", "fl_bin[ibin] = (fl[loc]).mean() return bin_cent, fl_bin def beam_from_fwhm(fwhm_arcminute, lmax): \"\"\"Compute the harmonic transform", "for k, v in cosmo_params.items() if k not in [\"logA\", \"As\"]} camb_cosmo.update({\"As\": 1e-10*np.exp(cosmo_params[\"logA\"]),", "bin_low, bin_hi, bin_cent, bin_size = read_binning_file(binning_file, lmax) n_bins = len(bin_hi) fl_bin = np.zeros(len(bin_cent))", "size of the bins n_bins: integer the number of bins lmax: integer the", "bin_size = bin_hi - bin_low + 1 return bin_low, bin_hi, bin_cent, bin_size def", "range(len(bin_low)): f.write(\"%0.2f %0.2f %0.2f\\n\" % (bin_low[i], bin_hi[i], bin_cent[i])) f.close() def read_binning_file(file_name, lmax): \"\"\"Read", "%0.2f\\n\" % (bin_low[i], bin_hi[i], bin_cent[i])) f.close() def read_binning_file(file_name, lmax): \"\"\"Read a binningFile and", "use this function ---------- cosmo_params: dict dictionnary of cosmological parameters # e.g cosmo_params", "lensed power spectrum You need to have camb installed to use this function", "= l * (l + 1) / (2 * np.pi) if output_type ==", "in uK.arcmin beamfile: string the name of the beam transfer function (assuming it's", "harmonic transform of the beam given the beam full width half maximum in", "start at l=0 and cl(l=0) and cl(l=1) are set to 0 \"\"\" fields", "\"EE\", \"BB\", \"TE\" ])} ps[\"ET\"] = ps[\"TE\"] for spec in [\"TB\", \"BT\", \"EB\",", "bl[2 :lmax + 2] ** 2 if type == \"Dl\": for spec in", "of strings needed for spin0 and spin2 cross correlation, the arrangement of the", "enumerate([\"TT\", \"EE\", \"BB\", \"TE\" ])} ps[\"ET\"] = ps[\"TE\"] for spec in [\"TB\", \"BT\",", "you want to read lmax : integer the maximum multipole (spectra will be", ":lmax + 2] ** 2 nl_th[\"BB\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi /", "the arrangement of the spectra rms_uKarcmin_pol: float the polarisation noise rms in uK.arcmin", "in arcminute Parameters ---------- fwhm_arcminute: float full width half maximum in arcminute lmax:", "+ 2] ** 2 nl_th[\"EE\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi / (60", "\"\"\" fields = [\"TT\", \"TE\", \"TB\", \"ET\", \"BT\", \"EE\", \"EB\", \"BE\", \"BB\"] ps", "name: string the name of the directory \"\"\" os.makedirs(name, exist_ok=True) def naive_binning(l, fl,", "uK.arcmin type: string 'Cl' or 'Dl' lmax: integer the maximum multipole to consider", "will be cut at) output_type : string 'Cl' or 'Dl' start_at_zero : boolean", "# e.g cosmo_params = {\"cosmomc_theta\":0.0104085, \"logA\": 3.044, \"ombh2\": 0.02237, \"omch2\": 0.1200, \"ns\": 0.9649,", "lmax is not None: id = np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent =", "or 'Dl' start_at_zero : boolean if True, ps start at l=0 and cl(l=0)", "to 0 else, start at l=2 \"\"\" try: import camb except ModuleNotFoundError: raise", "lth = np.arange(2, lmax + 2) nl_th = {} if spectra is None:", "for ibin in range(n_bins): loc = np.where((l >= bin_low[ibin]) & (l <= bin_hi[ibin]))", "= {} if spectra is None: nl_th[\"TT\"] = ( np.ones(lmax) * (rms_uKarcmin_T *", "You need to have camb installed to use this function ---------- cosmo_params: dict", "multipole to consider spectra: list of strings needed for spin0 and spin2 cross", "is None: rms_uKarcmin_pol = rms_uKarcmin_T * np.sqrt(2) for spec in spectra: nl_th[spec] =", "ps[\"TE\"].copy() ps[\"TB\"], ps[\"BT\"], ps[\"EB\"], ps[\"BE\"] = np.zeros((4, len(l))) if lmax is not None:", "ps[f] = np.append(np.array([0, 0]), ps[f]) if start_at_zero: l = np.append(np.array([0, 1]), l) return", "= np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if file_name", "= [\"TT\", \"TE\", \"TB\", \"ET\", \"BT\", \"EE\", \"EB\", \"BE\", \"BB\"] ps = {}", "\"Cl\": ps[f] /= scale if start_at_zero: ps[f] = np.append(np.array([0, 0]), ps[f]) if start_at_zero:", "name of the directory \"\"\" os.makedirs(name, exist_ok=True) def naive_binning(l, fl, binning_file, lmax): \"\"\"Bin", "the maximum multipole to consider \"\"\" beam = np.loadtxt(beamfile) l, bl = beam[:,", "+ 1) * bin_size + 1 bin_cent = (bin_low + bin_hi) / 2", "float full width half maximum in arcminute lmax: integer the maximum multipole to", "* np.pi) return nl_th else: if rms_uKarcmin_pol is None: rms_uKarcmin_pol = rms_uKarcmin_T *", "file_name is None: return bin_low, bin_hi, bin_cent else: f = open(\"%s\" % file_name,", "bl = l[:lmax], bl[:lmax] return l, bl / bl[0] def create_binning_file(bin_size, n_bins, lmax=None,", "cosmological parameters compute the corresponding lensed power spectrum You need to have camb", "None: nl_th[\"TT\"] = ( np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60 * 180))", "lmax=None, start_at_zero=False): \"\"\"Read a lensed power spectrum from CAMB and return a dictionnary", "1) / (2 * np.pi) for f in fields: if lmax is not", "ps def ps_from_params(cosmo_params, output_type, lmax, start_at_zero=False): \"\"\"Given a set of cosmological parameters compute", "bin_low + 1 return bin_low, bin_hi, bin_cent, bin_size def create_directory(name): \"\"\"Create a directory", "fwhm_arcminute: float full width half maximum in arcminute lmax: integer the maximum multipole", "range(n_bins): loc = np.where((l >= bin_low[ibin]) & (l <= bin_hi[ibin])) fl_bin[ibin] = (fl[loc]).mean()", "\"\"\" import os import numpy as np def ps_lensed_theory_to_dict(filename, output_type, lmax=None, start_at_zero=False): \"\"\"Read", "np.pi) return nl_th def read_beam_file(beamfile, lmax=None): \"\"\"Read beam file with formal, l, bl,", "lmax) bl = np.exp(-ell * (ell + 1) * fac ** 2 /", "bin_high, bin_mean Parameters ---------- binningfile: string the name of the binning file lmax:", "np.loadtxt(file_name, unpack=True) id = np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id],", "write it to disk Parameters ---------- bin_size: float the size of the bins", "bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if bin_low[0] < 2: bin_low[0] =", "= (fl[loc]).mean() return bin_cent, fl_bin def beam_from_fwhm(fwhm_arcminute, lmax): \"\"\"Compute the harmonic transform of", "in range(len(bin_low)): f.write(\"%0.2f %0.2f %0.2f\\n\" % (bin_low[i], bin_hi[i], bin_cent[i])) f.close() def read_binning_file(file_name, lmax):", "nl_th def read_beam_file(beamfile, lmax=None): \"\"\"Read beam file with formal, l, bl, stuff and", "if beamfile is not None: l, bl = np.loadtxt(beamfile, unpack=True) else: bl =", "2] ** 2 nl_th[\"EE\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi / (60 *", "bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if file_name is None: return bin_low,", "the maximum multipole to consider \"\"\" bin_low, bin_hi, bin_cent, bin_size = read_binning_file(binning_file, lmax)", "from CAMB and return a dictionnary Parameters ---------- filename : string the name", "bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if bin_low[0] < 2: bin_low[0] = 2 bin_hi", "'Dl' start_at_zero : boolean if True, ps start at l=0 and cl(l=0) and", "0]), ps[f]) if start_at_zero: l = np.append(np.array([0, 1]), l) return l, ps def", "\"Cl\": if start_at_zero: ps[2:] /= scale[2:] else: ps[:] /= scale[:] return l, ps", "+ 1 return bin_low, bin_hi, bin_cent, bin_size def create_directory(name): \"\"\"Create a directory Parameters", "given the beam full width half maximum in arcminute Parameters ---------- fwhm_arcminute: float", "camb_cosmo.update({\"As\": 1e-10*np.exp(cosmo_params[\"logA\"]), \"lmax\": lmax, \"lens_potential_accuracy\": 1}) pars = camb.set_params(**camb_cosmo) results = camb.get_results(pars) powers", "file with formal, l, bl, stuff and normalize it Parameters __________ beamfile: string", "count, spec in enumerate([\"TT\", \"EE\", \"BB\", \"TE\" ])} ps[\"ET\"] = ps[\"TE\"] for spec", "* (l + 1) / (2 * np.pi) for f in fields: if", "os.makedirs(name, exist_ok=True) def naive_binning(l, fl, binning_file, lmax): \"\"\"Bin a function of l given", "\"BB\"] ps = {} l, ps[\"TT\"], ps[\"EE\"], ps[\"BB\"], ps[\"TE\"] = np.loadtxt(filename, unpack=True) ps[\"ET\"]", "lmax): \"\"\"Read a binningFile and truncate it to lmax, if bin_low lower than", "is not None: ps[f] = ps[f][:lmax] if output_type == \"Cl\": ps[f] /= scale", "ps = {spec: powers[\"total\"][l][:, count] for count, spec in enumerate([\"TT\", \"EE\", \"BB\", \"TE\"", "bin_hi = bin_hi.astype(int) bin_low = bin_low.astype(int) bin_size = bin_hi - bin_low + 1", ":lmax + 2] ** 2 if type == \"Dl\": for spec in spectra:", "ps start at l=0 and cl(l=0) and cl(l=1) are set to 0 \"\"\"", "consider \"\"\" bin_low, bin_hi, bin_cent = np.loadtxt(file_name, unpack=True) id = np.where(bin_hi < lmax)", "np.loadtxt(beamfile, unpack=True) else: bl = np.ones(lmax + 2) lth = np.arange(2, lmax +", "name of the beam file lmax: integer the maximum multipole to consider \"\"\"", "2 if type == \"Dl\": for spec in spectra: nl_th[spec] *= lth *", "lmax Parameters ---------- l: 1d integer array the multipoles fl: 1d float array", "* 0 scale = l * (l + 1) / (2 * np.pi)", "CAMB lensed power spectrum you want to read lmax : integer the maximum", "string the name of the CAMB lensed power spectrum you want to read", "start_at_zero : boolean if True, ps start at l=0 and cl(l=0) and cl(l=1)", "Parameters ---------- filename : string the name of the CAMB lensed power spectrum", "\"omch2\": 0.1200, \"ns\": 0.9649, \"Alens\": 1.0, \"tau\": 0.0544} output_type : string 'Cl' or", "** 2 if type == \"Dl\": for spec in spectra: nl_th[spec] *= lth", "the CAMB lensed power spectrum you want to read lmax : integer the", "lmax is not None: l = l[:lmax] scale = l * (l +", "\"\"\" try: import camb except ModuleNotFoundError: raise ModuleNotFoundError(\"you need to install camb to", "[\"TB\", \"BT\", \"EB\", \"BE\" ]: ps[spec] = ps[\"TT\"] * 0 scale = l", "= ps[\"TE\"].copy() ps[\"TB\"], ps[\"BT\"], ps[\"EB\"], ps[\"BE\"] = np.zeros((4, len(l))) if lmax is not", "set it to 2. format is bin_low, bin_high, bin_mean Parameters ---------- binningfile: string", "* 180)) ** 2 / bl[2 :lmax + 2] ** 2 nl_th[\"EE\"] =", "0.9649, \"Alens\": 1.0, \"tau\": 0.0544} output_type : string 'Cl' or 'Dl' lmax: integer", "\"\"\" beam_fwhm_rad = np.deg2rad(fwhm_arcminute) / 60 fac = beam_fwhm_rad / np.sqrt(8 * np.log(2))", "if lmax is not None: l = l[:lmax] scale = l * (l", "bin_hi[id], bin_cent[id] if bin_low[0] < 2: bin_low[0] = 2 bin_hi = bin_hi.astype(int) bin_low", "= camb.get_results(pars) powers = results.get_cmb_power_spectra(pars, CMB_unit=\"muK\") l = np.arange(lmin, lmax) ps = {spec:", "string 'Cl' or 'Dl' start_at_zero : boolean if True, ps start at l=0", "= read_binning_file(binning_file, lmax) n_bins = len(bin_hi) fl_bin = np.zeros(len(bin_cent)) for ibin in range(n_bins):", "of bins lmax: integer the maximum multipole to consider file_name: string the name", "and a noise rms Parameters ---------- rms_uKarcmin_T: float the temperature noise rms in", "string the name of the binning file \"\"\" bins = np.arange(n_bins) bin_low =", "bin_low[0] = 2 bin_hi = bin_hi.astype(int) bin_low = bin_low.astype(int) bin_size = bin_hi -", "open(\"%s\" % file_name, mode=\"w\") for i in range(len(bin_low)): f.write(\"%0.2f %0.2f %0.2f\\n\" % (bin_low[i],", "it to 2. format is bin_low, bin_high, bin_mean Parameters ---------- binningfile: string the", "(60 * 180)) ** 2 / bl[2 :lmax + 2] ** 2 nl_th[\"BB\"]", "lmax: integer the maximum multipole to consider \"\"\" beam = np.loadtxt(beamfile) l, bl", "bin_low.astype(int) bin_size = bin_hi - bin_low + 1 return bin_low, bin_hi, bin_cent, bin_size", "< lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if file_name is None:", "need to install camb to use this function\") if start_at_zero: lmin = 0", "half maximum in arcminute lmax: integer the maximum multipole to consider \"\"\" beam_fwhm_rad", "beam_fwhm_rad / np.sqrt(8 * np.log(2)) ell = np.arange(2, lmax) bl = np.exp(-ell *", "fields = [\"TT\", \"TE\", \"TB\", \"ET\", \"BT\", \"EE\", \"EB\", \"BE\", \"BB\"] ps =", "\"TB\", \"ET\", \"BT\", \"EE\", \"EB\", \"BE\", \"BB\"] ps = {} l, ps[\"TT\"], ps[\"EE\"],", "nl_th[\"EE\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi / (60 * 180)) ** 2", "\"\"\" beam = np.loadtxt(beamfile) l, bl = beam[:, 0], beam[:, 1] if lmax", "the name of the CAMB lensed power spectrum you want to read lmax", "for spec in spectra: nl_th[spec] *= lth * (lth + 1) / (2", "the corresponding lensed power spectrum You need to have camb installed to use", "if output_type == \"Cl\": if start_at_zero: ps[2:] /= scale[2:] else: ps[:] /= scale[:]", "ps[\"TB\"], ps[\"BT\"], ps[\"EB\"], ps[\"BE\"] = np.zeros((4, len(l))) if lmax is not None: l", "camb.get_results(pars) powers = results.get_cmb_power_spectra(pars, CMB_unit=\"muK\") l = np.arange(lmin, lmax) ps = {spec: powers[\"total\"][l][:,", "f in fields: if lmax is not None: ps[f] = ps[f][:lmax] if output_type", "read_beam_file(beamfile, lmax=None): \"\"\"Read beam file with formal, l, bl, stuff and normalize it", "\"lens_potential_accuracy\": 1}) pars = camb.set_params(**camb_cosmo) results = camb.get_results(pars) powers = results.get_cmb_power_spectra(pars, CMB_unit=\"muK\") l", "output_type : string 'Cl' or 'Dl' start_at_zero : boolean if True, ps start", "/ bl[2 :lmax + 2] ** 2 nl_th[\"BB\"] = np.ones(lmax) * (rms_uKarcmin_pol *", "the maximum multipole to consider file_name: string the name of the binning file", "multipole to consider file_name: string the name of the binning file \"\"\" bins", "2 / bl[2 :lmax + 2] ** 2 if type == \"Dl\": for", "None: l, bl = np.loadtxt(beamfile, unpack=True) else: bl = np.ones(lmax + 2) lth", "+ 2] ** 2 nl_th[\"BB\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi / (60", "+ 1 bin_cent = (bin_low + bin_hi) / 2 if lmax is not", "fl_bin = np.zeros(len(bin_cent)) for ibin in range(n_bins): loc = np.where((l >= bin_low[ibin]) &", "the maximum multipole to consider spectra: list of strings needed for spin0 and", "the multipoles fl: 1d float array the 1-dimensional function to bin binning_file: string", "half maximum in arcminute Parameters ---------- fwhm_arcminute: float full width half maximum in", "e.g cosmo_params = {\"cosmomc_theta\":0.0104085, \"logA\": 3.044, \"ombh2\": 0.02237, \"omch2\": 0.1200, \"ns\": 0.9649, \"Alens\":", "1d float array the 1-dimensional function to bin binning_file: string the name of", "2] ** 2 ) if type == \"Dl\": nl_th[\"TT\"] *= lth * (lth", "results = camb.get_results(pars) powers = results.get_cmb_power_spectra(pars, CMB_unit=\"muK\") l = np.arange(lmin, lmax) ps =", "camb except ModuleNotFoundError: raise ModuleNotFoundError(\"you need to install camb to use this function\")", "f = open(\"%s\" % file_name, mode=\"w\") for i in range(len(bin_low)): f.write(\"%0.2f %0.2f %0.2f\\n\"", "2) nl_th = {} if spectra is None: nl_th[\"TT\"] = ( np.ones(lmax) *", "fac = beam_fwhm_rad / np.sqrt(8 * np.log(2)) ell = np.arange(2, lmax) bl =", "numpy as np def ps_lensed_theory_to_dict(filename, output_type, lmax=None, start_at_zero=False): \"\"\"Read a lensed power spectrum", "given a binning file and lmax Parameters ---------- l: 1d integer array the", "np.pi) if output_type == \"Cl\": if start_at_zero: ps[2:] /= scale[2:] else: ps[:] /=", "a noise rms Parameters ---------- rms_uKarcmin_T: float the temperature noise rms in uK.arcmin", "l,bl) \"\"\" if beamfile is not None: l, bl = np.loadtxt(beamfile, unpack=True) else:", "the name of the binning file lmax: integer the maximum multipole to consider", "consider \"\"\" bin_low, bin_hi, bin_cent, bin_size = read_binning_file(binning_file, lmax) n_bins = len(bin_hi) fl_bin", "ps[f][:lmax] if output_type == \"Cl\": ps[f] /= scale if start_at_zero: ps[f] = np.append(np.array([0,", "of cosmological parameters # e.g cosmo_params = {\"cosmomc_theta\":0.0104085, \"logA\": 3.044, \"ombh2\": 0.02237, \"omch2\":", "l given a binning file and lmax Parameters ---------- l: 1d integer array", "integer the maximum multipole to consider \"\"\" beam_fwhm_rad = np.deg2rad(fwhm_arcminute) / 60 fac", "* (ell + 1) * fac ** 2 / 2.0) return ell, bl", "spectra is None: nl_th[\"TT\"] = ( np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60", "the binning file lmax: integer the maximum multipole to consider \"\"\" bin_low, bin_hi,", "'Cl' or 'Dl' start_at_zero : boolean if True, ps start at l=0 and", "% file_name, mode=\"w\") for i in range(len(bin_low)): f.write(\"%0.2f %0.2f %0.2f\\n\" % (bin_low[i], bin_hi[i],", "l = np.append(np.array([0, 1]), l) return l, ps def ps_from_params(cosmo_params, output_type, lmax, start_at_zero=False):", "dictionnary of cosmological parameters # e.g cosmo_params = {\"cosmomc_theta\":0.0104085, \"logA\": 3.044, \"ombh2\": 0.02237,", "* bin_size + 1 bin_cent = (bin_low + bin_hi) / 2 if lmax", "def beam_from_fwhm(fwhm_arcminute, lmax): \"\"\"Compute the harmonic transform of the beam given the beam", "noise rms in uK.arcmin beamfile: string the name of the beam transfer function", "arcminute lmax: integer the maximum multipole to consider \"\"\" beam_fwhm_rad = np.deg2rad(fwhm_arcminute) /", "full width half maximum in arcminute Parameters ---------- fwhm_arcminute: float full width half", "maximum multipole to consider \"\"\" bin_low, bin_hi, bin_cent, bin_size = read_binning_file(binning_file, lmax) n_bins", "\"\"\" bin_low, bin_hi, bin_cent, bin_size = read_binning_file(binning_file, lmax) n_bins = len(bin_hi) fl_bin =", "of the binning file \"\"\" bins = np.arange(n_bins) bin_low = bins * bin_size", "np.arange(n_bins) bin_low = bins * bin_size + 2 bin_hi = (bins + 1)", "not None: l = l[:lmax] scale = l * (l + 1) /", "maximum in arcminute lmax: integer the maximum multipole to consider \"\"\" beam_fwhm_rad =", "None: rms_uKarcmin_pol = rms_uKarcmin_T * np.sqrt(2) for spec in spectra: nl_th[spec] = np.zeros(lmax)", "180)) ** 2 / bl[2 :lmax + 2] ** 2 nl_th[\"BB\"] = np.ones(lmax)", "\"TE\", \"TB\", \"ET\", \"BT\", \"EE\", \"EB\", \"BE\", \"BB\"] ps = {} l, ps[\"TT\"],", "1) / (2 * np.pi) return nl_th def read_beam_file(beamfile, lmax=None): \"\"\"Read beam file", "spectrum from CAMB and return a dictionnary Parameters ---------- filename : string the", "nl_th[\"BB\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi / (60 * 180)) ** 2", "format is bin_low, bin_high, bin_mean Parameters ---------- binningfile: string the name of the", "unpack=True) else: bl = np.ones(lmax + 2) lth = np.arange(2, lmax + 2)", "if lmax is not None: ps[f] = ps[f][:lmax] if output_type == \"Cl\": ps[f]", "= np.zeros(len(bin_cent)) for ibin in range(n_bins): loc = np.where((l >= bin_low[ibin]) & (l", "def get_nlth_dict(rms_uKarcmin_T, type, lmax, spectra=None, rms_uKarcmin_pol=None, beamfile=None): \"\"\"Return the effective noise power spectrum", "list of strings needed for spin0 and spin2 cross correlation, the arrangement of", "ps[f] /= scale if start_at_zero: ps[f] = np.append(np.array([0, 0]), ps[f]) if start_at_zero: l", "np.append(np.array([0, 1]), l) return l, ps def ps_from_params(cosmo_params, output_type, lmax, start_at_zero=False): \"\"\"Given a", "beamfile: string the name of the beam file lmax: integer the maximum multipole", "/ (2 * np.pi) return nl_th else: if rms_uKarcmin_pol is None: rms_uKarcmin_pol =", "disk Parameters ---------- bin_size: float the size of the bins n_bins: integer the", "fl, binning_file, lmax): \"\"\"Bin a function of l given a binning file and", "bin_hi, bin_cent = np.loadtxt(file_name, unpack=True) id = np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent", "output_type == \"Cl\": ps[f] /= scale if start_at_zero: ps[f] = np.append(np.array([0, 0]), ps[f])", "strings needed for spin0 and spin2 cross correlation, the arrangement of the spectra", "for f in fields: if lmax is not None: ps[f] = ps[f][:lmax] if", "needed for spin0 and spin2 cross correlation, the arrangement of the spectra rms_uKarcmin_pol:", "power spectrum You need to have camb installed to use this function ----------", "not in [\"logA\", \"As\"]} camb_cosmo.update({\"As\": 1e-10*np.exp(cosmo_params[\"logA\"]), \"lmax\": lmax, \"lens_potential_accuracy\": 1}) pars = camb.set_params(**camb_cosmo)", "in spectra: nl_th[spec] = np.zeros(lmax) nl_th[\"TT\"] = np.ones(lmax) * (rms_uKarcmin_T * np.pi /", "with formal, l, bl, stuff and normalize it Parameters __________ beamfile: string the", "1 bin_cent = (bin_low + bin_hi) / 2 if lmax is not None:", "of l given a binning file and lmax Parameters ---------- l: 1d integer", "ps[\"TT\"], ps[\"EE\"], ps[\"BB\"], ps[\"TE\"] = np.loadtxt(filename, unpack=True) ps[\"ET\"] = ps[\"TE\"].copy() ps[\"TB\"], ps[\"BT\"], ps[\"EB\"],", "None: return bin_low, bin_hi, bin_cent else: f = open(\"%s\" % file_name, mode=\"w\") for", "* (lth + 1) / (2 * np.pi) return nl_th def read_beam_file(beamfile, lmax=None):", "bin_hi, bin_cent, bin_size = read_binning_file(binning_file, lmax) n_bins = len(bin_hi) fl_bin = np.zeros(len(bin_cent)) for", "2. format is bin_low, bin_high, bin_mean Parameters ---------- binningfile: string the name of", "\"\"\"Return the effective noise power spectrum Nl/bl^2 given a beam file and a", "and truncate it to lmax, if bin_low lower than 2, set it to", "np.where((l >= bin_low[ibin]) & (l <= bin_hi[ibin])) fl_bin[ibin] = (fl[loc]).mean() return bin_cent, fl_bin", "the maximum multipole to consider \"\"\" beam_fwhm_rad = np.deg2rad(fwhm_arcminute) / 60 fac =", "/= scale[2:] else: ps[:] /= scale[:] return l, ps def get_nlth_dict(rms_uKarcmin_T, type, lmax,", "temperature noise rms in uK.arcmin type: string 'Cl' or 'Dl' lmax: integer the", "2 / bl[2 :lmax + 2] ** 2 nl_th[\"EE\"] = np.ones(lmax) * (rms_uKarcmin_pol", "maximum in arcminute Parameters ---------- fwhm_arcminute: float full width half maximum in arcminute", "beam file with formal, l, bl, stuff and normalize it Parameters __________ beamfile:", "else: bl = np.ones(lmax + 2) lth = np.arange(2, lmax + 2) nl_th", "(l + 1) / (2 * np.pi) if output_type == \"Cl\": if start_at_zero:", "bin_cent = np.loadtxt(file_name, unpack=True) id = np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent =", "in cosmo_params.items() if k not in [\"logA\", \"As\"]} camb_cosmo.update({\"As\": 1e-10*np.exp(cosmo_params[\"logA\"]), \"lmax\": lmax, \"lens_potential_accuracy\":", "in enumerate([\"TT\", \"EE\", \"BB\", \"TE\" ])} ps[\"ET\"] = ps[\"TE\"] for spec in [\"TB\",", "0 else, start at l=2 \"\"\" try: import camb except ModuleNotFoundError: raise ModuleNotFoundError(\"you", "nl_th = {} if spectra is None: nl_th[\"TT\"] = ( np.ones(lmax) * (rms_uKarcmin_T", "of the beam transfer function (assuming it's given as a two column file", "None: l = l[:lmax] scale = l * (l + 1) / (2", "of cosmological parameters compute the corresponding lensed power spectrum You need to have", "naive_binning(l, fl, binning_file, lmax): \"\"\"Bin a function of l given a binning file", "cl(l=1) are set to 0 \"\"\" fields = [\"TT\", \"TE\", \"TB\", \"ET\", \"BT\",", "2 camb_cosmo = {k: v for k, v in cosmo_params.items() if k not", "file, and optionnaly write it to disk Parameters ---------- bin_size: float the size", "for spin0 and spin2 cross correlation, the arrangement of the spectra rms_uKarcmin_pol: float", "file lmax: integer the maximum multipole to consider \"\"\" beam = np.loadtxt(beamfile) l,", "= ps[f][:lmax] if output_type == \"Cl\": ps[f] /= scale if start_at_zero: ps[f] =", "bins = np.arange(n_bins) bin_low = bins * bin_size + 2 bin_hi = (bins", "l, bl = beam[:, 0], beam[:, 1] if lmax is not None: l,", "= (bins + 1) * bin_size + 1 bin_cent = (bin_low + bin_hi)", "file lmax: integer the maximum multipole to consider \"\"\" bin_low, bin_hi, bin_cent, bin_size", "def create_binning_file(bin_size, n_bins, lmax=None, file_name=None): \"\"\"Create a (constant) binning file, and optionnaly write", "create_directory(name): \"\"\"Create a directory Parameters ---------- name: string the name of the directory", "the name of the beam file lmax: integer the maximum multipole to consider", "of the beam given the beam full width half maximum in arcminute Parameters", "bin_cent, bin_size = read_binning_file(binning_file, lmax) n_bins = len(bin_hi) fl_bin = np.zeros(len(bin_cent)) for ibin", "])} ps[\"ET\"] = ps[\"TE\"] for spec in [\"TB\", \"BT\", \"EB\", \"BE\" ]: ps[spec]", "lmax : integer the maximum multipole (spectra will be cut at) output_type :", "polarisation noise rms in uK.arcmin beamfile: string the name of the beam transfer", "power spectrum you want to read lmax : integer the maximum multipole (spectra", "/ (2 * np.pi) for f in fields: if lmax is not None:", "+ 1) / (2 * np.pi) return nl_th def read_beam_file(beamfile, lmax=None): \"\"\"Read beam", "bin_mean Parameters ---------- binningfile: string the name of the binning file lmax: integer", "a binning file and lmax Parameters ---------- l: 1d integer array the multipoles", "at) output_type : string 'Cl' or 'Dl' start_at_zero : boolean if True, ps", "len(l))) if lmax is not None: l = l[:lmax] scale = l *", "* (rms_uKarcmin_pol * np.pi / (60 * 180)) ** 2 / bl[2 :lmax", "(rms_uKarcmin_T * np.pi / (60 * 180)) ** 2 / bl[2 : lmax", "__________ beamfile: string the name of the beam file lmax: integer the maximum", "bin_hi[ibin])) fl_bin[ibin] = (fl[loc]).mean() return bin_cent, fl_bin def beam_from_fwhm(fwhm_arcminute, lmax): \"\"\"Compute the harmonic", "\"\"\"Read a lensed power spectrum from CAMB and return a dictionnary Parameters ----------", "corresponding lensed power spectrum You need to have camb installed to use this", "{k: v for k, v in cosmo_params.items() if k not in [\"logA\", \"As\"]}", ": string 'Cl' or 'Dl' start_at_zero : boolean if True, ps start at", "is not None: l, bl = l[:lmax], bl[:lmax] return l, bl / bl[0]", "dict dictionnary of cosmological parameters # e.g cosmo_params = {\"cosmomc_theta\":0.0104085, \"logA\": 3.044, \"ombh2\":", "Parameters ---------- name: string the name of the directory \"\"\" os.makedirs(name, exist_ok=True) def", "nl_th[spec] = np.zeros(lmax) nl_th[\"TT\"] = np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60 *", "to 2. format is bin_low, bin_high, bin_mean Parameters ---------- binningfile: string the name", "multipole to consider \"\"\" beam = np.loadtxt(beamfile) l, bl = beam[:, 0], beam[:,", "np.log(2)) ell = np.arange(2, lmax) bl = np.exp(-ell * (ell + 1) *", "1e-10*np.exp(cosmo_params[\"logA\"]), \"lmax\": lmax, \"lens_potential_accuracy\": 1}) pars = camb.set_params(**camb_cosmo) results = camb.get_results(pars) powers =", "output_type == \"Cl\": if start_at_zero: ps[2:] /= scale[2:] else: ps[:] /= scale[:] return", "---------- rms_uKarcmin_T: float the temperature noise rms in uK.arcmin type: string 'Cl' or", "/ bl[2 : lmax + 2] ** 2 ) if type == \"Dl\":", "n_bins, lmax=None, file_name=None): \"\"\"Create a (constant) binning file, and optionnaly write it to", "None: ps[f] = ps[f][:lmax] if output_type == \"Cl\": ps[f] /= scale if start_at_zero:", "cl(l=1) are set to 0 else, start at l=2 \"\"\" try: import camb", "as a two column file l,bl) \"\"\" if beamfile is not None: l,", "= beam_fwhm_rad / np.sqrt(8 * np.log(2)) ell = np.arange(2, lmax) bl = np.exp(-ell", "start_at_zero: ps[2:] /= scale[2:] else: ps[:] /= scale[:] return l, ps def get_nlth_dict(rms_uKarcmin_T,", "fl: 1d float array the 1-dimensional function to bin binning_file: string the name", "start_at_zero: lmin = 0 else: lmin = 2 camb_cosmo = {k: v for", "bin_cent, bin_size def create_directory(name): \"\"\"Create a directory Parameters ---------- name: string the name", "output_type, lmax, start_at_zero=False): \"\"\"Given a set of cosmological parameters compute the corresponding lensed", "name of the beam transfer function (assuming it's given as a two column", "file lmax: integer the maximum multipole to consider \"\"\" bin_low, bin_hi, bin_cent =", "bin_low, bin_hi, bin_cent = np.loadtxt(file_name, unpack=True) id = np.where(bin_hi < lmax) bin_low, bin_hi,", "spec in spectra: nl_th[spec] = np.zeros(lmax) nl_th[\"TT\"] = np.ones(lmax) * (rms_uKarcmin_T * np.pi", "file_name, mode=\"w\") for i in range(len(bin_low)): f.write(\"%0.2f %0.2f %0.2f\\n\" % (bin_low[i], bin_hi[i], bin_cent[i]))", "* (l + 1) / (2 * np.pi) if output_type == \"Cl\": if", "/ (60 * 180)) ** 2 / bl[2 :lmax + 2] ** 2", "than 2, set it to 2. format is bin_low, bin_high, bin_mean Parameters ----------", "the beam given the beam full width half maximum in arcminute Parameters ----------", "maximum multipole to consider \"\"\" bin_low, bin_hi, bin_cent = np.loadtxt(file_name, unpack=True) id =", "<reponame>xgarrido/pspy \"\"\" Utils for pspy. \"\"\" import os import numpy as np def", "1]), l) return l, ps def ps_from_params(cosmo_params, output_type, lmax, start_at_zero=False): \"\"\"Given a set", "/ np.sqrt(8 * np.log(2)) ell = np.arange(2, lmax) bl = np.exp(-ell * (ell", "bin_hi[i], bin_cent[i])) f.close() def read_binning_file(file_name, lmax): \"\"\"Read a binningFile and truncate it to", "bin_cent[id] if bin_low[0] < 2: bin_low[0] = 2 bin_hi = bin_hi.astype(int) bin_low =", "= bin_low[id], bin_hi[id], bin_cent[id] if file_name is None: return bin_low, bin_hi, bin_cent else:", "maximum multipole to consider start_at_zero : boolean if True, ps start at l=0", "effective noise power spectrum Nl/bl^2 given a beam file and a noise rms", "l[:lmax] scale = l * (l + 1) / (2 * np.pi) for", "= np.arange(lmin, lmax) ps = {spec: powers[\"total\"][l][:, count] for count, spec in enumerate([\"TT\",", "integer the maximum multipole (spectra will be cut at) output_type : string 'Cl'", "return bin_low, bin_hi, bin_cent else: f = open(\"%s\" % file_name, mode=\"w\") for i", "rms_uKarcmin_T: float the temperature noise rms in uK.arcmin type: string 'Cl' or 'Dl'", "to have camb installed to use this function ---------- cosmo_params: dict dictionnary of", "= {spec: powers[\"total\"][l][:, count] for count, spec in enumerate([\"TT\", \"EE\", \"BB\", \"TE\" ])}", "beam[:, 0], beam[:, 1] if lmax is not None: l, bl = l[:lmax],", "want to read lmax : integer the maximum multipole (spectra will be cut", "to use this function ---------- cosmo_params: dict dictionnary of cosmological parameters # e.g", "scale[:] return l, ps def get_nlth_dict(rms_uKarcmin_T, type, lmax, spectra=None, rms_uKarcmin_pol=None, beamfile=None): \"\"\"Return the", "+ 2) nl_th = {} if spectra is None: nl_th[\"TT\"] = ( np.ones(lmax)", "bin_size + 1 bin_cent = (bin_low + bin_hi) / 2 if lmax is", "/ (2 * np.pi) return nl_th def read_beam_file(beamfile, lmax=None): \"\"\"Read beam file with", "True, ps start at l=0 and cl(l=0) and cl(l=1) are set to 0", "v for k, v in cosmo_params.items() if k not in [\"logA\", \"As\"]} camb_cosmo.update({\"As\":", "= np.arange(2, lmax + 2) nl_th = {} if spectra is None: nl_th[\"TT\"]", "of the directory \"\"\" os.makedirs(name, exist_ok=True) def naive_binning(l, fl, binning_file, lmax): \"\"\"Bin a", ": boolean if True, ps start at l=0 and cl(l=0) and cl(l=1) are", "ps start at l=0 and cl(l=0) and cl(l=1) are set to 0 else,", "maximum multipole to consider \"\"\" beam = np.loadtxt(beamfile) l, bl = beam[:, 0],", "bin_low[id], bin_hi[id], bin_cent[id] if bin_low[0] < 2: bin_low[0] = 2 bin_hi = bin_hi.astype(int)", "of the binning file lmax: integer the maximum multipole to consider \"\"\" bin_low,", "the name of the directory \"\"\" os.makedirs(name, exist_ok=True) def naive_binning(l, fl, binning_file, lmax):", "2] ** 2 nl_th[\"BB\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi / (60 *", "at l=2 \"\"\" try: import camb except ModuleNotFoundError: raise ModuleNotFoundError(\"you need to install", "normalize it Parameters __________ beamfile: string the name of the beam file lmax:", "number of bins lmax: integer the maximum multipole to consider file_name: string the", "\"\"\" os.makedirs(name, exist_ok=True) def naive_binning(l, fl, binning_file, lmax): \"\"\"Bin a function of l", "array the multipoles fl: 1d float array the 1-dimensional function to bin binning_file:", "l, bl, stuff and normalize it Parameters __________ beamfile: string the name of", "ps_from_params(cosmo_params, output_type, lmax, start_at_zero=False): \"\"\"Given a set of cosmological parameters compute the corresponding", "stuff and normalize it Parameters __________ beamfile: string the name of the beam", "loc = np.where((l >= bin_low[ibin]) & (l <= bin_hi[ibin])) fl_bin[ibin] = (fl[loc]).mean() return", "\"\"\" bins = np.arange(n_bins) bin_low = bins * bin_size + 2 bin_hi =", "bin_hi, bin_cent, bin_size def create_directory(name): \"\"\"Create a directory Parameters ---------- name: string the", "l: 1d integer array the multipoles fl: 1d float array the 1-dimensional function", "for pspy. \"\"\" import os import numpy as np def ps_lensed_theory_to_dict(filename, output_type, lmax=None,", "beam file and a noise rms Parameters ---------- rms_uKarcmin_T: float the temperature noise", "arrangement of the spectra rms_uKarcmin_pol: float the polarisation noise rms in uK.arcmin beamfile:", "start_at_zero: l = np.append(np.array([0, 1]), l) return l, ps def ps_from_params(cosmo_params, output_type, lmax,", "\"\"\" if beamfile is not None: l, bl = np.loadtxt(beamfile, unpack=True) else: bl", "l=0 and cl(l=0) and cl(l=1) are set to 0 else, start at l=2", "bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if file_name is None: return bin_low, bin_hi, bin_cent", "a two column file l,bl) \"\"\" if beamfile is not None: l, bl", "in fields: if lmax is not None: ps[f] = ps[f][:lmax] if output_type ==", "ps[f] = ps[f][:lmax] if output_type == \"Cl\": ps[f] /= scale if start_at_zero: ps[f]", "to read lmax : integer the maximum multipole (spectra will be cut at)", "except ModuleNotFoundError: raise ModuleNotFoundError(\"you need to install camb to use this function\") if", "it Parameters __________ beamfile: string the name of the beam file lmax: integer", "fl_bin def beam_from_fwhm(fwhm_arcminute, lmax): \"\"\"Compute the harmonic transform of the beam given the", "import numpy as np def ps_lensed_theory_to_dict(filename, output_type, lmax=None, start_at_zero=False): \"\"\"Read a lensed power", "rms_uKarcmin_pol: float the polarisation noise rms in uK.arcmin beamfile: string the name of", "l * (l + 1) / (2 * np.pi) if output_type == \"Cl\":", "cl(l=0) and cl(l=1) are set to 0 else, start at l=2 \"\"\" try:", "maximum multipole to consider \"\"\" beam_fwhm_rad = np.deg2rad(fwhm_arcminute) / 60 fac = beam_fwhm_rad", "spectrum You need to have camb installed to use this function ---------- cosmo_params:", "the bins n_bins: integer the number of bins lmax: integer the maximum multipole", "integer the maximum multipole to consider \"\"\" bin_low, bin_hi, bin_cent = np.loadtxt(file_name, unpack=True)", "bin_cent[id] if file_name is None: return bin_low, bin_hi, bin_cent else: f = open(\"%s\"", "it's given as a two column file l,bl) \"\"\" if beamfile is not", "%0.2f %0.2f\\n\" % (bin_low[i], bin_hi[i], bin_cent[i])) f.close() def read_binning_file(file_name, lmax): \"\"\"Read a binningFile", "to 0 \"\"\" fields = [\"TT\", \"TE\", \"TB\", \"ET\", \"BT\", \"EE\", \"EB\", \"BE\",", "ps[\"TE\"] for spec in [\"TB\", \"BT\", \"EB\", \"BE\" ]: ps[spec] = ps[\"TT\"] *", "import os import numpy as np def ps_lensed_theory_to_dict(filename, output_type, lmax=None, start_at_zero=False): \"\"\"Read a", "* 180)) ** 2 / bl[2 : lmax + 2] ** 2 )", "( np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60 * 180)) ** 2 /", "lmax: integer the maximum multipole to consider file_name: string the name of the", "\"\"\"Given a set of cosmological parameters compute the corresponding lensed power spectrum You", "\"tau\": 0.0544} output_type : string 'Cl' or 'Dl' lmax: integer the maximum multipole", "Parameters ---------- rms_uKarcmin_T: float the temperature noise rms in uK.arcmin type: string 'Cl'", "installed to use this function ---------- cosmo_params: dict dictionnary of cosmological parameters #", "file_name=None): \"\"\"Create a (constant) binning file, and optionnaly write it to disk Parameters", "---------- binningfile: string the name of the binning file lmax: integer the maximum", "spec in spectra: nl_th[spec] *= lth * (lth + 1) / (2 *", "\"lmax\": lmax, \"lens_potential_accuracy\": 1}) pars = camb.set_params(**camb_cosmo) results = camb.get_results(pars) powers = results.get_cmb_power_spectra(pars,", "ps[\"EB\"], ps[\"BE\"] = np.zeros((4, len(l))) if lmax is not None: l = l[:lmax]", "lmax, \"lens_potential_accuracy\": 1}) pars = camb.set_params(**camb_cosmo) results = camb.get_results(pars) powers = results.get_cmb_power_spectra(pars, CMB_unit=\"muK\")", "beam full width half maximum in arcminute Parameters ---------- fwhm_arcminute: float full width", "\"ET\", \"BT\", \"EE\", \"EB\", \"BE\", \"BB\"] ps = {} l, ps[\"TT\"], ps[\"EE\"], ps[\"BB\"],", "ps[\"EE\"], ps[\"BB\"], ps[\"TE\"] = np.loadtxt(filename, unpack=True) ps[\"ET\"] = ps[\"TE\"].copy() ps[\"TB\"], ps[\"BT\"], ps[\"EB\"], ps[\"BE\"]", "file l,bl) \"\"\" if beamfile is not None: l, bl = np.loadtxt(beamfile, unpack=True)", "if rms_uKarcmin_pol is None: rms_uKarcmin_pol = rms_uKarcmin_T * np.sqrt(2) for spec in spectra:", "bl[0] def create_binning_file(bin_size, n_bins, lmax=None, file_name=None): \"\"\"Create a (constant) binning file, and optionnaly", "file_name: string the name of the binning file \"\"\" bins = np.arange(n_bins) bin_low", "nl_th[\"TT\"] = ( np.ones(lmax) * (rms_uKarcmin_T * np.pi / (60 * 180)) **", "bin_hi.astype(int) bin_low = bin_low.astype(int) bin_size = bin_hi - bin_low + 1 return bin_low,", "2 / bl[2 : lmax + 2] ** 2 ) if type ==", "to consider \"\"\" bin_low, bin_hi, bin_cent = np.loadtxt(file_name, unpack=True) id = np.where(bin_hi <", "function of l given a binning file and lmax Parameters ---------- l: 1d", "np.ones(lmax) * (rms_uKarcmin_pol * np.pi / (60 * 180)) ** 2 / bl[2", "return nl_th else: if rms_uKarcmin_pol is None: rms_uKarcmin_pol = rms_uKarcmin_T * np.sqrt(2) for", "np.sqrt(2) for spec in spectra: nl_th[spec] = np.zeros(lmax) nl_th[\"TT\"] = np.ones(lmax) * (rms_uKarcmin_T", "if spectra is None: nl_th[\"TT\"] = ( np.ones(lmax) * (rms_uKarcmin_T * np.pi /", "a function of l given a binning file and lmax Parameters ---------- l:", "lmax) n_bins = len(bin_hi) fl_bin = np.zeros(len(bin_cent)) for ibin in range(n_bins): loc =", "else, start at l=2 \"\"\" try: import camb except ModuleNotFoundError: raise ModuleNotFoundError(\"you need", "bl, stuff and normalize it Parameters __________ beamfile: string the name of the", "l[:lmax], bl[:lmax] return l, bl / bl[0] def create_binning_file(bin_size, n_bins, lmax=None, file_name=None): \"\"\"Create", "bins lmax: integer the maximum multipole to consider file_name: string the name of", "and spin2 cross correlation, the arrangement of the spectra rms_uKarcmin_pol: float the polarisation", "Parameters __________ beamfile: string the name of the beam file lmax: integer the", "bl = beam[:, 0], beam[:, 1] if lmax is not None: l, bl", "l=0 and cl(l=0) and cl(l=1) are set to 0 \"\"\" fields = [\"TT\",", "binningFile and truncate it to lmax, if bin_low lower than 2, set it", "np.zeros(len(bin_cent)) for ibin in range(n_bins): loc = np.where((l >= bin_low[ibin]) & (l <=", "beam given the beam full width half maximum in arcminute Parameters ---------- fwhm_arcminute:", "0.1200, \"ns\": 0.9649, \"Alens\": 1.0, \"tau\": 0.0544} output_type : string 'Cl' or 'Dl'", "== \"Dl\": for spec in spectra: nl_th[spec] *= lth * (lth + 1)", "k not in [\"logA\", \"As\"]} camb_cosmo.update({\"As\": 1e-10*np.exp(cosmo_params[\"logA\"]), \"lmax\": lmax, \"lens_potential_accuracy\": 1}) pars =", "name of the binning file \"\"\" bins = np.arange(n_bins) bin_low = bins *", "lmax + 2] ** 2 ) if type == \"Dl\": nl_th[\"TT\"] *= lth", "180)) ** 2 / bl[2 :lmax + 2] ** 2 nl_th[\"EE\"] = np.ones(lmax)", "(rms_uKarcmin_pol * np.pi / (60 * 180)) ** 2 / bl[2 :lmax +", "and cl(l=0) and cl(l=1) are set to 0 \"\"\" fields = [\"TT\", \"TE\",", "not None: l, bl = np.loadtxt(beamfile, unpack=True) else: bl = np.ones(lmax + 2)", "= np.loadtxt(beamfile, unpack=True) else: bl = np.ones(lmax + 2) lth = np.arange(2, lmax", "noise rms in uK.arcmin type: string 'Cl' or 'Dl' lmax: integer the maximum", "* np.pi / (60 * 180)) ** 2 / bl[2 : lmax +", "bin_low[ibin]) & (l <= bin_hi[ibin])) fl_bin[ibin] = (fl[loc]).mean() return bin_cent, fl_bin def beam_from_fwhm(fwhm_arcminute,", "def create_directory(name): \"\"\"Create a directory Parameters ---------- name: string the name of the", "/ 60 fac = beam_fwhm_rad / np.sqrt(8 * np.log(2)) ell = np.arange(2, lmax)", "transfer function (assuming it's given as a two column file l,bl) \"\"\" if", "bin_hi - bin_low + 1 return bin_low, bin_hi, bin_cent, bin_size def create_directory(name): \"\"\"Create", "to bin binning_file: string the name of the binning file lmax: integer the", "try: import camb except ModuleNotFoundError: raise ModuleNotFoundError(\"you need to install camb to use", "& (l <= bin_hi[ibin])) fl_bin[ibin] = (fl[loc]).mean() return bin_cent, fl_bin def beam_from_fwhm(fwhm_arcminute, lmax):", "+ 1) / (2 * np.pi) if output_type == \"Cl\": if start_at_zero: ps[2:]", "os import numpy as np def ps_lensed_theory_to_dict(filename, output_type, lmax=None, start_at_zero=False): \"\"\"Read a lensed", "np.where(bin_hi < lmax) bin_low, bin_hi, bin_cent = bin_low[id], bin_hi[id], bin_cent[id] if file_name is", "= {} l, ps[\"TT\"], ps[\"EE\"], ps[\"BB\"], ps[\"TE\"] = np.loadtxt(filename, unpack=True) ps[\"ET\"] = ps[\"TE\"].copy()", "else: if rms_uKarcmin_pol is None: rms_uKarcmin_pol = rms_uKarcmin_T * np.sqrt(2) for spec in", "set to 0 else, start at l=2 \"\"\" try: import camb except ModuleNotFoundError:", "np.loadtxt(beamfile) l, bl = beam[:, 0], beam[:, 1] if lmax is not None:", "the 1-dimensional function to bin binning_file: string the name of the binning file", "create_binning_file(bin_size, n_bins, lmax=None, file_name=None): \"\"\"Create a (constant) binning file, and optionnaly write it", "lmax: integer the maximum multipole to consider \"\"\" bin_low, bin_hi, bin_cent, bin_size =", "= np.where((l >= bin_low[ibin]) & (l <= bin_hi[ibin])) fl_bin[ibin] = (fl[loc]).mean() return bin_cent,", "cut at) output_type : string 'Cl' or 'Dl' start_at_zero : boolean if True,", "1) / (2 * np.pi) if output_type == \"Cl\": if start_at_zero: ps[2:] /=", "fields: if lmax is not None: ps[f] = ps[f][:lmax] if output_type == \"Cl\":", "bl[2 :lmax + 2] ** 2 nl_th[\"EE\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi", "if True, ps start at l=0 and cl(l=0) and cl(l=1) are set to", "float the temperature noise rms in uK.arcmin type: string 'Cl' or 'Dl' lmax:", "/ bl[2 :lmax + 2] ** 2 nl_th[\"EE\"] = np.ones(lmax) * (rms_uKarcmin_pol *", "start_at_zero=False): \"\"\"Read a lensed power spectrum from CAMB and return a dictionnary Parameters", "are set to 0 \"\"\" fields = [\"TT\", \"TE\", \"TB\", \"ET\", \"BT\", \"EE\",", "function\") if start_at_zero: lmin = 0 else: lmin = 2 camb_cosmo = {k:", "2) lth = np.arange(2, lmax + 2) nl_th = {} if spectra is", "** 2 nl_th[\"EE\"] = np.ones(lmax) * (rms_uKarcmin_pol * np.pi / (60 * 180))", "/= scale if start_at_zero: ps[f] = np.append(np.array([0, 0]), ps[f]) if start_at_zero: l =", "ModuleNotFoundError: raise ModuleNotFoundError(\"you need to install camb to use this function\") if start_at_zero:", "rms_uKarcmin_pol is None: rms_uKarcmin_pol = rms_uKarcmin_T * np.sqrt(2) for spec in spectra: nl_th[spec]", "bin_cent[i])) f.close() def read_binning_file(file_name, lmax): \"\"\"Read a binningFile and truncate it to lmax,", "lmax: integer the maximum multipole to consider \"\"\" bin_low, bin_hi, bin_cent = np.loadtxt(file_name,", "\"EE\", \"EB\", \"BE\", \"BB\"] ps = {} l, ps[\"TT\"], ps[\"EE\"], ps[\"BB\"], ps[\"TE\"] =", "the binning file \"\"\" bins = np.arange(n_bins) bin_low = bins * bin_size +", "= np.loadtxt(beamfile) l, bl = beam[:, 0], beam[:, 1] if lmax is not", "rms in uK.arcmin beamfile: string the name of the beam transfer function (assuming", "given a beam file and a noise rms Parameters ---------- rms_uKarcmin_T: float the", "= np.exp(-ell * (ell + 1) * fac ** 2 / 2.0) return", "[\"logA\", \"As\"]} camb_cosmo.update({\"As\": 1e-10*np.exp(cosmo_params[\"logA\"]), \"lmax\": lmax, \"lens_potential_accuracy\": 1}) pars = camb.set_params(**camb_cosmo) results =", "0], beam[:, 1] if lmax is not None: l, bl = l[:lmax], bl[:lmax]", "return bin_cent, fl_bin def beam_from_fwhm(fwhm_arcminute, lmax): \"\"\"Compute the harmonic transform of the beam", "np.pi / (60 * 180)) ** 2 / bl[2 : lmax + 2]", "ps[spec] = ps[\"TT\"] * 0 scale = l * (l + 1) /", "integer the maximum multipole to consider file_name: string the name of the binning", "(2 * np.pi) for f in fields: if lmax is not None: ps[f]", "use this function\") if start_at_zero: lmin = 0 else: lmin = 2 camb_cosmo", "(2 * np.pi) if output_type == \"Cl\": if start_at_zero: ps[2:] /= scale[2:] else:", "lmax, spectra=None, rms_uKarcmin_pol=None, beamfile=None): \"\"\"Return the effective noise power spectrum Nl/bl^2 given a", "Utils for pspy. \"\"\" import os import numpy as np def ps_lensed_theory_to_dict(filename, output_type,", "string 'Cl' or 'Dl' lmax: integer the maximum multipole to consider spectra: list", "\"logA\": 3.044, \"ombh2\": 0.02237, \"omch2\": 0.1200, \"ns\": 0.9649, \"Alens\": 1.0, \"tau\": 0.0544} output_type", "return l, bl / bl[0] def create_binning_file(bin_size, n_bins, lmax=None, file_name=None): \"\"\"Create a (constant)", "'Cl' or 'Dl' lmax: integer the maximum multipole to consider spectra: list of", "== \"Dl\": nl_th[\"TT\"] *= lth * (lth + 1) / (2 * np.pi)", "(bins + 1) * bin_size + 1 bin_cent = (bin_low + bin_hi) /", "rms_uKarcmin_T * np.sqrt(2) for spec in spectra: nl_th[spec] = np.zeros(lmax) nl_th[\"TT\"] = np.ones(lmax)", "and cl(l=1) are set to 0 \"\"\" fields = [\"TT\", \"TE\", \"TB\", \"ET\",", "float the size of the bins n_bins: integer the number of bins lmax:", "to install camb to use this function\") if start_at_zero: lmin = 0 else:", "type, lmax, spectra=None, rms_uKarcmin_pol=None, beamfile=None): \"\"\"Return the effective noise power spectrum Nl/bl^2 given", "array the 1-dimensional function to bin binning_file: string the name of the binning", "bl / bl[0] def create_binning_file(bin_size, n_bins, lmax=None, file_name=None): \"\"\"Create a (constant) binning file,", "scale[2:] else: ps[:] /= scale[:] return l, ps def get_nlth_dict(rms_uKarcmin_T, type, lmax, spectra=None,", "consider spectra: list of strings needed for spin0 and spin2 cross correlation, the", "read lmax : integer the maximum multipole (spectra will be cut at) output_type", "** 2 / bl[2 :lmax + 2] ** 2 nl_th[\"BB\"] = np.ones(lmax) *", "lmax=None): \"\"\"Read beam file with formal, l, bl, stuff and normalize it Parameters", "+ 2] ** 2 if type == \"Dl\": for spec in spectra: nl_th[spec]", "this function ---------- cosmo_params: dict dictionnary of cosmological parameters # e.g cosmo_params =", "rms_uKarcmin_pol = rms_uKarcmin_T * np.sqrt(2) for spec in spectra: nl_th[spec] = np.zeros(lmax) nl_th[\"TT\"]", "a (constant) binning file, and optionnaly write it to disk Parameters ---------- bin_size:" ]
[ "1, 1), nn.ReLU(), nn.Conv2d(256, 512, 3, 1, 1), nn.ReLU(), nn.Conv2d(512, 256, 3, 1,", "= nn.Sequential( nn.Conv2d(n_state[0], 64, 3, 1, 1), nn.ReLU(), nn.Conv2d(64, 256, 3, 1, 1),", "256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, n_action, 4, 1, 0), nn.Flatten(), ) self.ConvNet.apply(init_weights)", "1, 1), nn.ReLU(), nn.Conv2d(256, n_action, 4, 1, 0), nn.Flatten(), ) self.ConvNet.apply(init_weights) self.cuda() def", "1), nn.ReLU(), nn.Conv2d(64, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, 512, 3, 1, 1),", "64, 3, 1, 1), nn.ReLU(), nn.Conv2d(64, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, 512,", "1, 1), nn.ReLU(), nn.Conv2d(512, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, n_action, 4, 1,", "nn.Flatten(), ) self.ConvNet.apply(init_weights) self.cuda() def forward(self, state): x = self.ConvNet(state) return x def", "nn.ReLU(), nn.Conv2d(512, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, n_action, 4, 1, 0), nn.Flatten(),", "0), nn.Flatten(), ) self.ConvNet.apply(init_weights) self.cuda() def forward(self, state): x = self.ConvNet(state) return x", "= self.ConvNet(state) return x def init_weights(m): if type(m) in (nn.Linear, nn.Conv2d): torch.nn.init.xavier_uniform_(m.weight) m.bias.data.fill_(0.01)", "def forward(self, state): x = self.ConvNet(state) return x def init_weights(m): if type(m) in", "torch import torch.nn as nn class DQNNetwork(nn.Module): def __init__(self, n_state, n_action): super(DQNNetwork, self).__init__()", "1), nn.ReLU(), nn.Conv2d(512, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, n_action, 4, 1, 0),", "1, 0), nn.Flatten(), ) self.ConvNet.apply(init_weights) self.cuda() def forward(self, state): x = self.ConvNet(state) return", ") self.ConvNet.apply(init_weights) self.cuda() def forward(self, state): x = self.ConvNet(state) return x def init_weights(m):", "as nn class DQNNetwork(nn.Module): def __init__(self, n_state, n_action): super(DQNNetwork, self).__init__() self.ConvNet = nn.Sequential(", "self.ConvNet = nn.Sequential( nn.Conv2d(n_state[0], 64, 3, 1, 1), nn.ReLU(), nn.Conv2d(64, 256, 3, 1,", "self.ConvNet.apply(init_weights) self.cuda() def forward(self, state): x = self.ConvNet(state) return x def init_weights(m): if", "n_state, n_action): super(DQNNetwork, self).__init__() self.ConvNet = nn.Sequential( nn.Conv2d(n_state[0], 64, 3, 1, 1), nn.ReLU(),", "3, 1, 1), nn.ReLU(), nn.Conv2d(256, 512, 3, 1, 1), nn.ReLU(), nn.Conv2d(512, 256, 3,", "nn.ReLU(), nn.Conv2d(256, n_action, 4, 1, 0), nn.Flatten(), ) self.ConvNet.apply(init_weights) self.cuda() def forward(self, state):", "self).__init__() self.ConvNet = nn.Sequential( nn.Conv2d(n_state[0], 64, 3, 1, 1), nn.ReLU(), nn.Conv2d(64, 256, 3,", "nn class DQNNetwork(nn.Module): def __init__(self, n_state, n_action): super(DQNNetwork, self).__init__() self.ConvNet = nn.Sequential( nn.Conv2d(n_state[0],", "class DQNNetwork(nn.Module): def __init__(self, n_state, n_action): super(DQNNetwork, self).__init__() self.ConvNet = nn.Sequential( nn.Conv2d(n_state[0], 64,", "super(DQNNetwork, self).__init__() self.ConvNet = nn.Sequential( nn.Conv2d(n_state[0], 64, 3, 1, 1), nn.ReLU(), nn.Conv2d(64, 256,", "import torch.nn as nn class DQNNetwork(nn.Module): def __init__(self, n_state, n_action): super(DQNNetwork, self).__init__() self.ConvNet", "1), nn.ReLU(), nn.Conv2d(256, n_action, 4, 1, 0), nn.Flatten(), ) self.ConvNet.apply(init_weights) self.cuda() def forward(self,", "state): x = self.ConvNet(state) return x def init_weights(m): if type(m) in (nn.Linear, nn.Conv2d):", "def __init__(self, n_state, n_action): super(DQNNetwork, self).__init__() self.ConvNet = nn.Sequential( nn.Conv2d(n_state[0], 64, 3, 1,", "nn.ReLU(), nn.Conv2d(256, 512, 3, 1, 1), nn.ReLU(), nn.Conv2d(512, 256, 3, 1, 1), nn.ReLU(),", "1), nn.ReLU(), nn.Conv2d(256, 512, 3, 1, 1), nn.ReLU(), nn.Conv2d(512, 256, 3, 1, 1),", "torch.nn as nn class DQNNetwork(nn.Module): def __init__(self, n_state, n_action): super(DQNNetwork, self).__init__() self.ConvNet =", "1, 1), nn.ReLU(), nn.Conv2d(64, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, 512, 3, 1,", "DQNNetwork(nn.Module): def __init__(self, n_state, n_action): super(DQNNetwork, self).__init__() self.ConvNet = nn.Sequential( nn.Conv2d(n_state[0], 64, 3,", "nn.Conv2d(256, 512, 3, 1, 1), nn.ReLU(), nn.Conv2d(512, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256,", "3, 1, 1), nn.ReLU(), nn.Conv2d(256, n_action, 4, 1, 0), nn.Flatten(), ) self.ConvNet.apply(init_weights) self.cuda()", "3, 1, 1), nn.ReLU(), nn.Conv2d(512, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, n_action, 4,", "3, 1, 1), nn.ReLU(), nn.Conv2d(64, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, 512, 3,", "nn.Conv2d(64, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, 512, 3, 1, 1), nn.ReLU(), nn.Conv2d(512,", "512, 3, 1, 1), nn.ReLU(), nn.Conv2d(512, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, n_action,", "256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, 512, 3, 1, 1), nn.ReLU(), nn.Conv2d(512, 256,", "4, 1, 0), nn.Flatten(), ) self.ConvNet.apply(init_weights) self.cuda() def forward(self, state): x = self.ConvNet(state)", "self.cuda() def forward(self, state): x = self.ConvNet(state) return x def init_weights(m): if type(m)", "nn.Sequential( nn.Conv2d(n_state[0], 64, 3, 1, 1), nn.ReLU(), nn.Conv2d(64, 256, 3, 1, 1), nn.ReLU(),", "import torch import torch.nn as nn class DQNNetwork(nn.Module): def __init__(self, n_state, n_action): super(DQNNetwork,", "__init__(self, n_state, n_action): super(DQNNetwork, self).__init__() self.ConvNet = nn.Sequential( nn.Conv2d(n_state[0], 64, 3, 1, 1),", "n_action): super(DQNNetwork, self).__init__() self.ConvNet = nn.Sequential( nn.Conv2d(n_state[0], 64, 3, 1, 1), nn.ReLU(), nn.Conv2d(64,", "nn.Conv2d(n_state[0], 64, 3, 1, 1), nn.ReLU(), nn.Conv2d(64, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256,", "n_action, 4, 1, 0), nn.Flatten(), ) self.ConvNet.apply(init_weights) self.cuda() def forward(self, state): x =", "nn.Conv2d(256, n_action, 4, 1, 0), nn.Flatten(), ) self.ConvNet.apply(init_weights) self.cuda() def forward(self, state): x", "forward(self, state): x = self.ConvNet(state) return x def init_weights(m): if type(m) in (nn.Linear,", "x = self.ConvNet(state) return x def init_weights(m): if type(m) in (nn.Linear, nn.Conv2d): torch.nn.init.xavier_uniform_(m.weight)", "nn.ReLU(), nn.Conv2d(64, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, 512, 3, 1, 1), nn.ReLU(),", "<gh_stars>0 import torch import torch.nn as nn class DQNNetwork(nn.Module): def __init__(self, n_state, n_action):", "nn.Conv2d(512, 256, 3, 1, 1), nn.ReLU(), nn.Conv2d(256, n_action, 4, 1, 0), nn.Flatten(), )" ]
[ "objects to simplify imports in clients: .. code-block:: python from dynamorm import DynaModel", "ProjectInclude, ) # noqa from .relationships import ManyToOne, OneToMany, OneToOne # noqa from", ".model import DynaModel # noqa from .indexes import ( GlobalIndex, LocalIndex, ProjectAll, ProjectKeys,", "import DynaModel \"\"\" from .model import DynaModel # noqa from .indexes import (", "namespace simply imports the most frequently used objects to simplify imports in clients:", "clients: .. code-block:: python from dynamorm import DynaModel \"\"\" from .model import DynaModel", "used objects to simplify imports in clients: .. code-block:: python from dynamorm import", "imports in clients: .. code-block:: python from dynamorm import DynaModel \"\"\" from .model", ") # noqa from .relationships import ManyToOne, OneToMany, OneToOne # noqa from .table", "# noqa from .relationships import ManyToOne, OneToMany, OneToOne # noqa from .table import", "in clients: .. code-block:: python from dynamorm import DynaModel \"\"\" from .model import", "ProjectAll, ProjectKeys, ProjectInclude, ) # noqa from .relationships import ManyToOne, OneToMany, OneToOne #", "from .relationships import ManyToOne, OneToMany, OneToOne # noqa from .table import Q #", "imports the most frequently used objects to simplify imports in clients: .. code-block::", "noqa from .indexes import ( GlobalIndex, LocalIndex, ProjectAll, ProjectKeys, ProjectInclude, ) # noqa", "import ( GlobalIndex, LocalIndex, ProjectAll, ProjectKeys, ProjectInclude, ) # noqa from .relationships import", "module namespace simply imports the most frequently used objects to simplify imports in", "from .indexes import ( GlobalIndex, LocalIndex, ProjectAll, ProjectKeys, ProjectInclude, ) # noqa from", "DynaModel # noqa from .indexes import ( GlobalIndex, LocalIndex, ProjectAll, ProjectKeys, ProjectInclude, )", ".. code-block:: python from dynamorm import DynaModel \"\"\" from .model import DynaModel #", ".relationships import ManyToOne, OneToMany, OneToOne # noqa from .table import Q # noqa", "\"\"\"The base module namespace simply imports the most frequently used objects to simplify", "simply imports the most frequently used objects to simplify imports in clients: ..", "\"\"\" from .model import DynaModel # noqa from .indexes import ( GlobalIndex, LocalIndex,", "frequently used objects to simplify imports in clients: .. code-block:: python from dynamorm", "from .model import DynaModel # noqa from .indexes import ( GlobalIndex, LocalIndex, ProjectAll,", "DynaModel \"\"\" from .model import DynaModel # noqa from .indexes import ( GlobalIndex,", "ProjectKeys, ProjectInclude, ) # noqa from .relationships import ManyToOne, OneToMany, OneToOne # noqa", "the most frequently used objects to simplify imports in clients: .. code-block:: python", "to simplify imports in clients: .. code-block:: python from dynamorm import DynaModel \"\"\"", "dynamorm import DynaModel \"\"\" from .model import DynaModel # noqa from .indexes import", "base module namespace simply imports the most frequently used objects to simplify imports", "import DynaModel # noqa from .indexes import ( GlobalIndex, LocalIndex, ProjectAll, ProjectKeys, ProjectInclude,", "code-block:: python from dynamorm import DynaModel \"\"\" from .model import DynaModel # noqa", "from dynamorm import DynaModel \"\"\" from .model import DynaModel # noqa from .indexes", "GlobalIndex, LocalIndex, ProjectAll, ProjectKeys, ProjectInclude, ) # noqa from .relationships import ManyToOne, OneToMany,", "simplify imports in clients: .. code-block:: python from dynamorm import DynaModel \"\"\" from", "# noqa from .indexes import ( GlobalIndex, LocalIndex, ProjectAll, ProjectKeys, ProjectInclude, ) #", ".indexes import ( GlobalIndex, LocalIndex, ProjectAll, ProjectKeys, ProjectInclude, ) # noqa from .relationships", "LocalIndex, ProjectAll, ProjectKeys, ProjectInclude, ) # noqa from .relationships import ManyToOne, OneToMany, OneToOne", "python from dynamorm import DynaModel \"\"\" from .model import DynaModel # noqa from", "noqa from .relationships import ManyToOne, OneToMany, OneToOne # noqa from .table import Q", "( GlobalIndex, LocalIndex, ProjectAll, ProjectKeys, ProjectInclude, ) # noqa from .relationships import ManyToOne,", "most frequently used objects to simplify imports in clients: .. code-block:: python from" ]
[ "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,", "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "self._r = val def level(self, val, brightness=255): self._begin() for i in range(9,-1,-1) if", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED", "machine import Pin class MY9221: def __init__(self, di, dcki, reverse=False): self._d = di", "License Copyright (c) 2018 <NAME> Permission is hereby granted, free of charge, to", "& 1) state = self._c() self._c(not state) def _begin(self): self._write16(0) # command: 8bit", "this software and associated documentation files (the \"Software\"), to deal in the Software", "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "else 0) self._end() def bytes(self, buf): self._begin() for i in range(9,-1,-1) if self._r", "the 208 bit shift register self._write16(0) self._write16(0) self._latch() def reverse(self, val=None): if val", "for i in range(4): self._d(1) self._d(0) sleep_ms(1) def _write16(self, data): for i in", "2 channels are required to fill the 208 bit shift register self._write16(0) self._write16(0)", "OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "the Software without restriction, including without limitation the rights to use, copy, modify,", "person obtaining a copy of this software and associated documentation files (the \"Software\"),", "the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies", "def reverse(self, val=None): if val is None: return self._r self._r = val def", "without restriction, including without limitation the rights to use, copy, modify, merge, publish,", "merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit", "_write16(self, data): for i in range(15,-1,-1): self._d((data >> i) & 1) state =", "MY9221 LED driver https://github.com/mcauser/micropython-my9221 MIT License Copyright (c) 2018 <NAME> Permission is hereby", "self._c(not state) def _begin(self): self._write16(0) # command: 8bit mode def _end(self): # unused", "in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED", "sublicense, and/or sell copies of the Software, and to permit persons to whom", "this permission notice shall be included in all copies or substantial portions of", "modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to", "ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "bytes(self, buf): self._begin() for i in range(9,-1,-1) if self._r else range(10): self._write16(buf[i]) self._end()", "WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A", "2018 <NAME> Permission is hereby granted, free of charge, to any person obtaining", "notice and this permission notice shall be included in all copies or substantial", "8bit mode def _end(self): # unused last 2 channels are required to fill", "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE", "charge, to any person obtaining a copy of this software and associated documentation", "OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" from time import", "KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", ">> i) & 1 else 0) self._end() def bytes(self, buf): self._begin() for i", "val is None: return self._r self._r = val def level(self, val, brightness=255): self._begin()", "is None: return self._r self._r = val def level(self, val, brightness=255): self._begin() for", "range(9,-1,-1) if self._r else range(10): self._write16(brightness if (val >> i) & 1 else", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION", "persons to whom the Software is furnished to do so, subject to the", "Software is furnished to do so, subject to the following conditions: The above", "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "from machine import Pin class MY9221: def __init__(self, di, dcki, reverse=False): self._d =", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND", "SOFTWARE. \"\"\" from time import sleep_ms from machine import Pin class MY9221: def", "bits(self, val, brightness=255): val &= 0x3FF self._begin() for i in range(9,-1,-1) if self._r", "range(10): self._write16(brightness if (val >> i) & 1 else 0) self._end() def bytes(self,", "def bytes(self, buf): self._begin() for i in range(9,-1,-1) if self._r else range(10): self._write16(buf[i])", "val=None): if val is None: return self._r self._r = val def level(self, val,", "to deal in the Software without restriction, including without limitation the rights to", "to whom the Software is furnished to do so, subject to the following", "documentation files (the \"Software\"), to deal in the Software without restriction, including without", "range(10): self._write16(brightness if val > i else 0) self._end() def bits(self, val, brightness=255):", "val, brightness=255): val &= 0x3FF self._begin() for i in range(9,-1,-1) if self._r else", "files (the \"Software\"), to deal in the Software without restriction, including without limitation", "Software without restriction, including without limitation the rights to use, copy, modify, merge,", "self._d(0) sleep_ms(1) def _write16(self, data): for i in range(15,-1,-1): self._d((data >> i) &", "1) state = self._c() self._c(not state) def _begin(self): self._write16(0) # command: 8bit mode", "to do so, subject to the following conditions: The above copyright notice and", "in the Software without restriction, including without limitation the rights to use, copy,", "class MY9221: def __init__(self, di, dcki, reverse=False): self._d = di self._c = dcki", "sleep_ms(1) def _write16(self, data): for i in range(15,-1,-1): self._d((data >> i) & 1)", "self._d(0) sleep_ms(1) for i in range(4): self._d(1) self._d(0) sleep_ms(1) def _write16(self, data): for", "the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "to any person obtaining a copy of this software and associated documentation files", "self._r = reverse self._d.init(Pin.OUT, value=0) self._c.init(Pin.OUT, value=0) def _latch(self): self._d(0) sleep_ms(1) for i", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN", "i else 0) self._end() def bits(self, val, brightness=255): val &= 0x3FF self._begin() for", "USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" from time import sleep_ms from", "_latch(self): self._d(0) sleep_ms(1) for i in range(4): self._d(1) self._d(0) sleep_ms(1) def _write16(self, data):", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" from", "self._d((data >> i) & 1) state = self._c() self._c(not state) def _begin(self): self._write16(0)", "a copy of this software and associated documentation files (the \"Software\"), to deal", "Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF", "in range(15,-1,-1): self._d((data >> i) & 1) state = self._c() self._c(not state) def", "self._begin() for i in range(9,-1,-1) if self._r else range(10): self._write16(brightness if (val >>", "value=0) def _latch(self): self._d(0) sleep_ms(1) for i in range(4): self._d(1) self._d(0) sleep_ms(1) def", "def _end(self): # unused last 2 channels are required to fill the 208", "> i else 0) self._end() def bits(self, val, brightness=255): val &= 0x3FF self._begin()", "THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" from time import sleep_ms", "free of charge, to any person obtaining a copy of this software and", "and this permission notice shall be included in all copies or substantial portions", "and to permit persons to whom the Software is furnished to do so,", "shift register self._write16(0) self._write16(0) self._latch() def reverse(self, val=None): if val is None: return", "level(self, val, brightness=255): self._begin() for i in range(9,-1,-1) if self._r else range(10): self._write16(brightness", "sleep_ms from machine import Pin class MY9221: def __init__(self, di, dcki, reverse=False): self._d", "rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of", "di, dcki, reverse=False): self._d = di self._c = dcki self._r = reverse self._d.init(Pin.OUT,", "EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "i) & 1) state = self._c() self._c(not state) def _begin(self): self._write16(0) # command:", "0x3FF self._begin() for i in range(9,-1,-1) if self._r else range(10): self._write16(brightness if (val", "self._d = di self._c = dcki self._r = reverse self._d.init(Pin.OUT, value=0) self._c.init(Pin.OUT, value=0)", "associated documentation files (the \"Software\"), to deal in the Software without restriction, including", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,", "self._write16(0) # command: 8bit mode def _end(self): # unused last 2 channels are", "notice shall be included in all copies or substantial portions of the Software.", "if val is None: return self._r self._r = val def level(self, val, brightness=255):", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT", "copy of this software and associated documentation files (the \"Software\"), to deal in", "substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "self._write16(brightness if (val >> i) & 1 else 0) self._end() def bytes(self, buf):", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION", "# unused last 2 channels are required to fill the 208 bit shift", "obtaining a copy of this software and associated documentation files (the \"Software\"), to", "self._end() def bits(self, val, brightness=255): val &= 0x3FF self._begin() for i in range(9,-1,-1)", "TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR", "import Pin class MY9221: def __init__(self, di, dcki, reverse=False): self._d = di self._c", "OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons", "i in range(9,-1,-1) if self._r else range(10): self._write16(brightness if (val >> i) &", "including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,", "or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "Pin class MY9221: def __init__(self, di, dcki, reverse=False): self._d = di self._c =", "None: return self._r self._r = val def level(self, val, brightness=255): self._begin() for i", "self._c() self._c(not state) def _begin(self): self._write16(0) # command: 8bit mode def _end(self): #", "else range(10): self._write16(brightness if val > i else 0) self._end() def bits(self, val,", "if self._r else range(10): self._write16(brightness if val > i else 0) self._end() def", "i in range(4): self._d(1) self._d(0) sleep_ms(1) def _write16(self, data): for i in range(15,-1,-1):", "all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS", "SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "else 0) self._end() def bits(self, val, brightness=255): val &= 0x3FF self._begin() for i", "from time import sleep_ms from machine import Pin class MY9221: def __init__(self, di,", "OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "i) & 1 else 0) self._end() def bytes(self, buf): self._begin() for i in", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the", "if (val >> i) & 1 else 0) self._end() def bytes(self, buf): self._begin()", "in range(9,-1,-1) if self._r else range(10): self._write16(brightness if (val >> i) & 1", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN", "self._end() def bytes(self, buf): self._begin() for i in range(9,-1,-1) if self._r else range(10):", "def _begin(self): self._write16(0) # command: 8bit mode def _end(self): # unused last 2", "ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "self._d.init(Pin.OUT, value=0) self._c.init(Pin.OUT, value=0) def _latch(self): self._d(0) sleep_ms(1) for i in range(4): self._d(1)", "IN THE SOFTWARE. \"\"\" from time import sleep_ms from machine import Pin class", "OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "https://github.com/mcauser/micropython-my9221 MIT License Copyright (c) 2018 <NAME> Permission is hereby granted, free of", "above copyright notice and this permission notice shall be included in all copies", "time import sleep_ms from machine import Pin class MY9221: def __init__(self, di, dcki,", "WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "mode def _end(self): # unused last 2 channels are required to fill the", "if self._r else range(10): self._write16(brightness if (val >> i) & 1 else 0)", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS", "permission notice shall be included in all copies or substantial portions of the", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS", "LED driver https://github.com/mcauser/micropython-my9221 MIT License Copyright (c) 2018 <NAME> Permission is hereby granted,", "Copyright (c) 2018 <NAME> Permission is hereby granted, free of charge, to any", "MIT License Copyright (c) 2018 <NAME> Permission is hereby granted, free of charge,", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH", "self._write16(0) self._write16(0) self._latch() def reverse(self, val=None): if val is None: return self._r self._r", "0) self._end() def bits(self, val, brightness=255): val &= 0x3FF self._begin() for i in", "dcki, reverse=False): self._d = di self._c = dcki self._r = reverse self._d.init(Pin.OUT, value=0)", "the following conditions: The above copyright notice and this permission notice shall be", "in range(9,-1,-1) if self._r else range(10): self._write16(brightness if val > i else 0)", "= reverse self._d.init(Pin.OUT, value=0) self._c.init(Pin.OUT, value=0) def _latch(self): self._d(0) sleep_ms(1) for i in", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT", "furnished to do so, subject to the following conditions: The above copyright notice", "range(4): self._d(1) self._d(0) sleep_ms(1) def _write16(self, data): for i in range(15,-1,-1): self._d((data >>", "unused last 2 channels are required to fill the 208 bit shift register", "permit persons to whom the Software is furnished to do so, subject to", "any person obtaining a copy of this software and associated documentation files (the", "copies of the Software, and to permit persons to whom the Software is", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", "driver https://github.com/mcauser/micropython-my9221 MIT License Copyright (c) 2018 <NAME> Permission is hereby granted, free", "MY9221: def __init__(self, di, dcki, reverse=False): self._d = di self._c = dcki self._r", "included in all copies or substantial portions of the Software. THE SOFTWARE IS", "copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and", "last 2 channels are required to fill the 208 bit shift register self._write16(0)", "for i in range(15,-1,-1): self._d((data >> i) & 1) state = self._c() self._c(not", "THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "to fill the 208 bit shift register self._write16(0) self._write16(0) self._latch() def reverse(self, val=None):", "reverse self._d.init(Pin.OUT, value=0) self._c.init(Pin.OUT, value=0) def _latch(self): self._d(0) sleep_ms(1) for i in range(4):", "val > i else 0) self._end() def bits(self, val, brightness=255): val &= 0x3FF", "the Software, and to permit persons to whom the Software is furnished to", "(val >> i) & 1 else 0) self._end() def bytes(self, buf): self._begin() for", "self._write16(brightness if val > i else 0) self._end() def bits(self, val, brightness=255): val", "0) self._end() def bytes(self, buf): self._begin() for i in range(9,-1,-1) if self._r else", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,", "val, brightness=255): self._begin() for i in range(9,-1,-1) if self._r else range(10): self._write16(brightness if", "following conditions: The above copyright notice and this permission notice shall be included", "brightness=255): self._begin() for i in range(9,-1,-1) if self._r else range(10): self._write16(brightness if val", "copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",", "val &= 0x3FF self._begin() for i in range(9,-1,-1) if self._r else range(10): self._write16(brightness", "NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "The above copyright notice and this permission notice shall be included in all", "_end(self): # unused last 2 channels are required to fill the 208 bit", "self._r else range(10): self._write16(brightness if val > i else 0) self._end() def bits(self,", ">> i) & 1) state = self._c() self._c(not state) def _begin(self): self._write16(0) #", "1 else 0) self._end() def bytes(self, buf): self._begin() for i in range(9,-1,-1) if", "(c) 2018 <NAME> Permission is hereby granted, free of charge, to any person", "\"\"\" MicroPython MY9221 LED driver https://github.com/mcauser/micropython-my9221 MIT License Copyright (c) 2018 <NAME> Permission", "\"Software\"), to deal in the Software without restriction, including without limitation the rights", "value=0) self._c.init(Pin.OUT, value=0) def _latch(self): self._d(0) sleep_ms(1) for i in range(4): self._d(1) self._d(0)", "deal in the Software without restriction, including without limitation the rights to use,", "granted, free of charge, to any person obtaining a copy of this software", "limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "for i in range(9,-1,-1) if self._r else range(10): self._write16(brightness if val > i", "self._latch() def reverse(self, val=None): if val is None: return self._r self._r = val", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "val def level(self, val, brightness=255): self._begin() for i in range(9,-1,-1) if self._r else", "ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "of this software and associated documentation files (the \"Software\"), to deal in the", "def _latch(self): self._d(0) sleep_ms(1) for i in range(4): self._d(1) self._d(0) sleep_ms(1) def _write16(self,", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO", "sell copies of the Software, and to permit persons to whom the Software", "OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" from time import sleep_ms from machine", "self._begin() for i in range(9,-1,-1) if self._r else range(10): self._write16(brightness if val >", "do so, subject to the following conditions: The above copyright notice and this", "reverse(self, val=None): if val is None: return self._r self._r = val def level(self,", "reverse=False): self._d = di self._c = dcki self._r = reverse self._d.init(Pin.OUT, value=0) self._c.init(Pin.OUT,", "def bits(self, val, brightness=255): val &= 0x3FF self._begin() for i in range(9,-1,-1) if", "state) def _begin(self): self._write16(0) # command: 8bit mode def _end(self): # unused last", "is furnished to do so, subject to the following conditions: The above copyright", "so, subject to the following conditions: The above copyright notice and this permission", "&= 0x3FF self._begin() for i in range(9,-1,-1) if self._r else range(10): self._write16(brightness if", "bit shift register self._write16(0) self._write16(0) self._latch() def reverse(self, val=None): if val is None:", "return self._r self._r = val def level(self, val, brightness=255): self._begin() for i in", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR", "if val > i else 0) self._end() def bits(self, val, brightness=255): val &=", "of the Software, and to permit persons to whom the Software is furnished", "self._c = dcki self._r = reverse self._d.init(Pin.OUT, value=0) self._c.init(Pin.OUT, value=0) def _latch(self): self._d(0)", "and/or sell copies of the Software, and to permit persons to whom the", "= dcki self._r = reverse self._d.init(Pin.OUT, value=0) self._c.init(Pin.OUT, value=0) def _latch(self): self._d(0) sleep_ms(1)", "of charge, to any person obtaining a copy of this software and associated", "(the \"Software\"), to deal in the Software without restriction, including without limitation the", "OTHER DEALINGS IN THE SOFTWARE. \"\"\" from time import sleep_ms from machine import", "copyright notice and this permission notice shall be included in all copies or", "to permit persons to whom the Software is furnished to do so, subject", "self._r self._r = val def level(self, val, brightness=255): self._begin() for i in range(9,-1,-1)", "conditions: The above copyright notice and this permission notice shall be included in", "DEALINGS IN THE SOFTWARE. \"\"\" from time import sleep_ms from machine import Pin", "THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER", "Permission is hereby granted, free of charge, to any person obtaining a copy", "brightness=255): val &= 0x3FF self._begin() for i in range(9,-1,-1) if self._r else range(10):", "be included in all copies or substantial portions of the Software. THE SOFTWARE", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "= self._c() self._c(not state) def _begin(self): self._write16(0) # command: 8bit mode def _end(self):", "whom the Software is furnished to do so, subject to the following conditions:", "in range(4): self._d(1) self._d(0) sleep_ms(1) def _write16(self, data): for i in range(15,-1,-1): self._d((data", "dcki self._r = reverse self._d.init(Pin.OUT, value=0) self._c.init(Pin.OUT, value=0) def _latch(self): self._d(0) sleep_ms(1) for", "208 bit shift register self._write16(0) self._write16(0) self._latch() def reverse(self, val=None): if val is", "register self._write16(0) self._write16(0) self._latch() def reverse(self, val=None): if val is None: return self._r", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"", "FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "fill the 208 bit shift register self._write16(0) self._write16(0) self._latch() def reverse(self, val=None): if", "\"\"\" from time import sleep_ms from machine import Pin class MY9221: def __init__(self,", "portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "data): for i in range(15,-1,-1): self._d((data >> i) & 1) state = self._c()", "DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "channels are required to fill the 208 bit shift register self._write16(0) self._write16(0) self._latch()", "distribute, sublicense, and/or sell copies of the Software, and to permit persons to", "of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "software and associated documentation files (the \"Software\"), to deal in the Software without", "self._write16(0) self._latch() def reverse(self, val=None): if val is None: return self._r self._r =", "# command: 8bit mode def _end(self): # unused last 2 channels are required", "i in range(9,-1,-1) if self._r else range(10): self._write16(brightness if val > i else", "di self._c = dcki self._r = reverse self._d.init(Pin.OUT, value=0) self._c.init(Pin.OUT, value=0) def _latch(self):", "shall be included in all copies or substantial portions of the Software. THE", "THE SOFTWARE. \"\"\" from time import sleep_ms from machine import Pin class MY9221:", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" from time", "NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "i in range(15,-1,-1): self._d((data >> i) & 1) state = self._c() self._c(not state)", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT", "the Software is furnished to do so, subject to the following conditions: The", "command: 8bit mode def _end(self): # unused last 2 channels are required to", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING", "self._c.init(Pin.OUT, value=0) def _latch(self): self._d(0) sleep_ms(1) for i in range(4): self._d(1) self._d(0) sleep_ms(1)", "else range(10): self._write16(brightness if (val >> i) & 1 else 0) self._end() def", "def level(self, val, brightness=255): self._begin() for i in range(9,-1,-1) if self._r else range(10):", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT", "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS", "subject to the following conditions: The above copyright notice and this permission notice", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE", "= di self._c = dcki self._r = reverse self._d.init(Pin.OUT, value=0) self._c.init(Pin.OUT, value=0) def", "range(15,-1,-1): self._d((data >> i) & 1) state = self._c() self._c(not state) def _begin(self):", "is hereby granted, free of charge, to any person obtaining a copy of", "self._d(1) self._d(0) sleep_ms(1) def _write16(self, data): for i in range(15,-1,-1): self._d((data >> i)", "and associated documentation files (the \"Software\"), to deal in the Software without restriction,", "FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "def __init__(self, di, dcki, reverse=False): self._d = di self._c = dcki self._r =", "& 1 else 0) self._end() def bytes(self, buf): self._begin() for i in range(9,-1,-1)", "_begin(self): self._write16(0) # command: 8bit mode def _end(self): # unused last 2 channels", "are required to fill the 208 bit shift register self._write16(0) self._write16(0) self._latch() def", "sleep_ms(1) for i in range(4): self._d(1) self._d(0) sleep_ms(1) def _write16(self, data): for i", "hereby granted, free of charge, to any person obtaining a copy of this", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE", "self._r else range(10): self._write16(brightness if (val >> i) & 1 else 0) self._end()", "def _write16(self, data): for i in range(15,-1,-1): self._d((data >> i) & 1) state", "import sleep_ms from machine import Pin class MY9221: def __init__(self, di, dcki, reverse=False):", "restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,", "MicroPython MY9221 LED driver https://github.com/mcauser/micropython-my9221 MIT License Copyright (c) 2018 <NAME> Permission is", "for i in range(9,-1,-1) if self._r else range(10): self._write16(brightness if (val >> i)", "OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR", "state = self._c() self._c(not state) def _begin(self): self._write16(0) # command: 8bit mode def", "to the following conditions: The above copyright notice and this permission notice shall", "range(9,-1,-1) if self._r else range(10): self._write16(brightness if val > i else 0) self._end()", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "Software, and to permit persons to whom the Software is furnished to do", "__init__(self, di, dcki, reverse=False): self._d = di self._c = dcki self._r = reverse", "<NAME> Permission is hereby granted, free of charge, to any person obtaining a", "required to fill the 208 bit shift register self._write16(0) self._write16(0) self._latch() def reverse(self,", "= val def level(self, val, brightness=255): self._begin() for i in range(9,-1,-1) if self._r" ]
[ "threshold_max data[data < threshold_min] = threshold_min img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _", "= nibabel.load(file1) shape1 = np.shape(img.get_data()) affine1 = img.get_affine() img = nibabel.load(file2) shape2 =", "def check_images(file1, file2): \"\"\"Check that 2 images have the same affines and data", "{3}'.format( file1, shape1, file2, shape2)) if np.any(affine1 != affine2): raise ValueError('affine for {0}:", "np.shape(img.get_data()) affine2 = img.get_affine() if shape1 != shape2: raise ValueError('{0} of shape {1},", "data = img.get_data() if np.any(np.isnan(data)): data[np.isnan(data)] = fill_value img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header())", "warnings import numpy as np import nibabel def _single_glob(pattern): filenames = glob.glob(pattern) if", "4D data from a list of 3d images. \"\"\" data = [] for", "import nibabel def _single_glob(pattern): filenames = glob.glob(pattern) if not filenames: print('Warning: non exitant", "if not filenames: print('Warning: non exitant file with pattern {}'.format(pattern)) return None if", "pattern {}'.format(pattern)) return None if len(filenames) > 1: raise ValueError('Non unique file with", "img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file += '_thresholded.nii' if", "data = [] for f in input_files: image = nibabel.load(f) data.append(image.get_data()) data =", "{2}: {3}' .format(file1, affine1, file2, affine2)) def get_vox_dims(in_file): if isinstance(in_file, list): in_file =", "shape2)) if np.any(affine1 != affine2): raise ValueError('affine for {0}: {1}, for {2}: {3}'", "affine1, file2, affine2)) def get_vox_dims(in_file): if isinstance(in_file, list): in_file = in_file[0] img =", "if len(filenames) > 1: raise ValueError('Non unique file with pattern {}'.format(pattern)) return filenames[0]", "{} exits, overwriting.'.format(out_file)) nibabel.save(img, out_file) return out_file def remove_nan(in_file, fill_value=0.): img = nibabel.load(in_file)", "ValueError('Non unique file with pattern {}'.format(pattern)) return filenames[0] def _list_to_4d(input_files): \"\"\"Form a 4D", "!= affine2): raise ValueError('affine for {0}: {1}, for {2}: {3}' .format(file1, affine1, file2,", "and data shapes. \"\"\" img = nibabel.load(file1) shape1 = np.shape(img.get_data()) affine1 = img.get_affine()", "0)) def check_images(file1, file2): \"\"\"Check that 2 images have the same affines and", "in_file[0] img = nibabel.load(in_file) header = img.get_header() voxdims = header.get_zooms() return [float(voxdims[0]), float(voxdims[1]),", "_ = os.path.splitext(in_file) out_file += '_thresholded.nii' if os.path.isfile(out_file): warnings.warn('File {} exits, overwriting.'.format(out_file)) nibabel.save(img,", "= threshold_max data[data < threshold_min] = threshold_min img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file,", "images have the same affines and data shapes. \"\"\" img = nibabel.load(file1) shape1", "file2, affine2)) def get_vox_dims(in_file): if isinstance(in_file, list): in_file = in_file[0] img = nibabel.load(in_file)", "input_files: image = nibabel.load(f) data.append(image.get_data()) data = np.array(data) data = np.transpose(data, (1, 2,", "out_file def remove_nan(in_file, fill_value=0.): img = nibabel.load(in_file) data = img.get_data() if np.any(np.isnan(data)): data[np.isnan(data)]", "= [] for f in input_files: image = nibabel.load(f) data.append(image.get_data()) data = np.array(data)", "affine2): raise ValueError('affine for {0}: {1}, for {2}: {3}' .format(file1, affine1, file2, affine2))", "np.any(affine1 != affine2): raise ValueError('affine for {0}: {1}, for {2}: {3}' .format(file1, affine1,", "[] for f in input_files: image = nibabel.load(f) data.append(image.get_data()) data = np.array(data) data", "img.get_data() data[data > threshold_max] = threshold_max data[data < threshold_min] = threshold_min img =", "filenames[0] def _list_to_4d(input_files): \"\"\"Form a 4D data from a list of 3d images.", "= nibabel.load(f) data.append(image.get_data()) data = np.array(data) data = np.transpose(data, (1, 2, 3, 0))", "raise ValueError('affine for {0}: {1}, for {2}: {3}' .format(file1, affine1, file2, affine2)) def", "def _list_to_4d(input_files): \"\"\"Form a 4D data from a list of 3d images. \"\"\"", "remove_nan(in_file, fill_value=0.): img = nibabel.load(in_file) data = img.get_data() if np.any(np.isnan(data)): data[np.isnan(data)] = fill_value", "= nibabel.load(in_file) data = img.get_data() data[data > threshold_max] = threshold_max data[data < threshold_min]", "img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file += '_no_nan.nii' nibabel.save(img, out_file) return out_file", "{1}, for {2}: {3}' .format(file1, affine1, file2, affine2)) def get_vox_dims(in_file): if isinstance(in_file, list):", "img = nibabel.load(file2) shape2 = np.shape(img.get_data()) affine2 = img.get_affine() if shape1 != shape2:", "import warnings import numpy as np import nibabel def _single_glob(pattern): filenames = glob.glob(pattern)", "unique file with pattern {}'.format(pattern)) return filenames[0] def _list_to_4d(input_files): \"\"\"Form a 4D data", "np import nibabel def _single_glob(pattern): filenames = glob.glob(pattern) if not filenames: print('Warning: non", "<reponame>salma1601/process-asl-old import os import glob import warnings import numpy as np import nibabel", "in input_files: image = nibabel.load(f) data.append(image.get_data()) data = np.array(data) data = np.transpose(data, (1,", "'_thresholded.nii' if os.path.isfile(out_file): warnings.warn('File {} exits, overwriting.'.format(out_file)) nibabel.save(img, out_file) return out_file def remove_nan(in_file,", "2, 3, 0)) def check_images(file1, file2): \"\"\"Check that 2 images have the same", ".format(file1, affine1, file2, affine2)) def get_vox_dims(in_file): if isinstance(in_file, list): in_file = in_file[0] img", "nibabel.load(f) data.append(image.get_data()) data = np.array(data) data = np.transpose(data, (1, 2, 3, 0)) def", "img.get_header() voxdims = header.get_zooms() return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] def threshold(in_file, threshold_min=-1e7, threshold_max=1e7): img", "\"\"\"Check that 2 images have the same affines and data shapes. \"\"\" img", "os.path.splitext(in_file) out_file += '_thresholded.nii' if os.path.isfile(out_file): warnings.warn('File {} exits, overwriting.'.format(out_file)) nibabel.save(img, out_file) return", "def remove_nan(in_file, fill_value=0.): img = nibabel.load(in_file) data = img.get_data() if np.any(np.isnan(data)): data[np.isnan(data)] =", "!= shape2: raise ValueError('{0} of shape {1}, {2} of shape {3}'.format( file1, shape1,", "not filenames: print('Warning: non exitant file with pattern {}'.format(pattern)) return None if len(filenames)", "check_images(file1, file2): \"\"\"Check that 2 images have the same affines and data shapes.", "data[np.isnan(data)] = fill_value img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file", "{2} of shape {3}'.format( file1, shape1, file2, shape2)) if np.any(affine1 != affine2): raise", "isinstance(in_file, list): in_file = in_file[0] img = nibabel.load(in_file) header = img.get_header() voxdims =", "threshold(in_file, threshold_min=-1e7, threshold_max=1e7): img = nibabel.load(in_file) data = img.get_data() data[data > threshold_max] =", "same affines and data shapes. \"\"\" img = nibabel.load(file1) shape1 = np.shape(img.get_data()) affine1", "shapes. \"\"\" img = nibabel.load(file1) shape1 = np.shape(img.get_data()) affine1 = img.get_affine() img =", "img = nibabel.load(file1) shape1 = np.shape(img.get_data()) affine1 = img.get_affine() img = nibabel.load(file2) shape2", "threshold_min img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file += '_thresholded.nii'", "for {0}: {1}, for {2}: {3}' .format(file1, affine1, file2, affine2)) def get_vox_dims(in_file): if", "affine2 = img.get_affine() if shape1 != shape2: raise ValueError('{0} of shape {1}, {2}", "> threshold_max] = threshold_max data[data < threshold_min] = threshold_min img = nibabel.Nifti1Image(data, img.get_affine(),", "nibabel def _single_glob(pattern): filenames = glob.glob(pattern) if not filenames: print('Warning: non exitant file", "data[data < threshold_min] = threshold_min img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ =", "return None if len(filenames) > 1: raise ValueError('Non unique file with pattern {}'.format(pattern))", "the same affines and data shapes. \"\"\" img = nibabel.load(file1) shape1 = np.shape(img.get_data())", "img.get_affine() if shape1 != shape2: raise ValueError('{0} of shape {1}, {2} of shape", "as np import nibabel def _single_glob(pattern): filenames = glob.glob(pattern) if not filenames: print('Warning:", "np.shape(img.get_data()) affine1 = img.get_affine() img = nibabel.load(file2) shape2 = np.shape(img.get_data()) affine2 = img.get_affine()", "threshold_max=1e7): img = nibabel.load(in_file) data = img.get_data() data[data > threshold_max] = threshold_max data[data", "float(voxdims[1]), float(voxdims[2])] def threshold(in_file, threshold_min=-1e7, threshold_max=1e7): img = nibabel.load(in_file) data = img.get_data() data[data", "warnings.warn('File {} exits, overwriting.'.format(out_file)) nibabel.save(img, out_file) return out_file def remove_nan(in_file, fill_value=0.): img =", "def get_vox_dims(in_file): if isinstance(in_file, list): in_file = in_file[0] img = nibabel.load(in_file) header =", "import numpy as np import nibabel def _single_glob(pattern): filenames = glob.glob(pattern) if not", "print('Warning: non exitant file with pattern {}'.format(pattern)) return None if len(filenames) > 1:", "f in input_files: image = nibabel.load(f) data.append(image.get_data()) data = np.array(data) data = np.transpose(data,", "= os.path.splitext(in_file) out_file += '_thresholded.nii' if os.path.isfile(out_file): warnings.warn('File {} exits, overwriting.'.format(out_file)) nibabel.save(img, out_file)", "img.get_data() if np.any(np.isnan(data)): data[np.isnan(data)] = fill_value img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _", "def _single_glob(pattern): filenames = glob.glob(pattern) if not filenames: print('Warning: non exitant file with", "np.any(np.isnan(data)): data[np.isnan(data)] = fill_value img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file)", "= threshold_min img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file +=", "{}'.format(pattern)) return filenames[0] def _list_to_4d(input_files): \"\"\"Form a 4D data from a list of", "with pattern {}'.format(pattern)) return None if len(filenames) > 1: raise ValueError('Non unique file", "img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file += '_thresholded.nii' if os.path.isfile(out_file): warnings.warn('File {}", "+= '_thresholded.nii' if os.path.isfile(out_file): warnings.warn('File {} exits, overwriting.'.format(out_file)) nibabel.save(img, out_file) return out_file def", "nibabel.load(in_file) data = img.get_data() data[data > threshold_max] = threshold_max data[data < threshold_min] =", "filenames = glob.glob(pattern) if not filenames: print('Warning: non exitant file with pattern {}'.format(pattern))", "= header.get_zooms() return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] def threshold(in_file, threshold_min=-1e7, threshold_max=1e7): img = nibabel.load(in_file)", "len(filenames) > 1: raise ValueError('Non unique file with pattern {}'.format(pattern)) return filenames[0] def", "data = np.array(data) data = np.transpose(data, (1, 2, 3, 0)) def check_images(file1, file2):", "shape2 = np.shape(img.get_data()) affine2 = img.get_affine() if shape1 != shape2: raise ValueError('{0} of", "a list of 3d images. \"\"\" data = [] for f in input_files:", "= nibabel.load(in_file) header = img.get_header() voxdims = header.get_zooms() return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] def", "= img.get_data() if np.any(np.isnan(data)): data[np.isnan(data)] = fill_value img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file,", "None if len(filenames) > 1: raise ValueError('Non unique file with pattern {}'.format(pattern)) return", "= nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file += '_no_nan.nii' nibabel.save(img, out_file)", "= fill_value img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file +=", "data = img.get_data() data[data > threshold_max] = threshold_max data[data < threshold_min] = threshold_min", "threshold_max] = threshold_max data[data < threshold_min] = threshold_min img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header())", "= glob.glob(pattern) if not filenames: print('Warning: non exitant file with pattern {}'.format(pattern)) return", "file with pattern {}'.format(pattern)) return filenames[0] def _list_to_4d(input_files): \"\"\"Form a 4D data from", "3, 0)) def check_images(file1, file2): \"\"\"Check that 2 images have the same affines", "if np.any(affine1 != affine2): raise ValueError('affine for {0}: {1}, for {2}: {3}' .format(file1,", "3d images. \"\"\" data = [] for f in input_files: image = nibabel.load(f)", "= img.get_data() data[data > threshold_max] = threshold_max data[data < threshold_min] = threshold_min img", "shape1, file2, shape2)) if np.any(affine1 != affine2): raise ValueError('affine for {0}: {1}, for", "img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file += '_no_nan.nii' nibabel.save(img,", "header.get_zooms() return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] def threshold(in_file, threshold_min=-1e7, threshold_max=1e7): img = nibabel.load(in_file) data", "file2, shape2)) if np.any(affine1 != affine2): raise ValueError('affine for {0}: {1}, for {2}:", "img.get_header()) out_file, _ = os.path.splitext(in_file) out_file += '_thresholded.nii' if os.path.isfile(out_file): warnings.warn('File {} exits,", "data shapes. \"\"\" img = nibabel.load(file1) shape1 = np.shape(img.get_data()) affine1 = img.get_affine() img", "{1}, {2} of shape {3}'.format( file1, shape1, file2, shape2)) if np.any(affine1 != affine2):", "out_file, _ = os.path.splitext(in_file) out_file += '_thresholded.nii' if os.path.isfile(out_file): warnings.warn('File {} exits, overwriting.'.format(out_file))", "2 images have the same affines and data shapes. \"\"\" img = nibabel.load(file1)", "_list_to_4d(input_files): \"\"\"Form a 4D data from a list of 3d images. \"\"\" data", "data from a list of 3d images. \"\"\" data = [] for f", "data = np.transpose(data, (1, 2, 3, 0)) def check_images(file1, file2): \"\"\"Check that 2", "= nibabel.load(in_file) data = img.get_data() if np.any(np.isnan(data)): data[np.isnan(data)] = fill_value img = nibabel.Nifti1Image(data,", "if os.path.isfile(out_file): warnings.warn('File {} exits, overwriting.'.format(out_file)) nibabel.save(img, out_file) return out_file def remove_nan(in_file, fill_value=0.):", "glob import warnings import numpy as np import nibabel def _single_glob(pattern): filenames =", "\"\"\"Form a 4D data from a list of 3d images. \"\"\" data =", "of shape {1}, {2} of shape {3}'.format( file1, shape1, file2, shape2)) if np.any(affine1", "img.get_affine() img = nibabel.load(file2) shape2 = np.shape(img.get_data()) affine2 = img.get_affine() if shape1 !=", "of shape {3}'.format( file1, shape1, file2, shape2)) if np.any(affine1 != affine2): raise ValueError('affine", "= in_file[0] img = nibabel.load(in_file) header = img.get_header() voxdims = header.get_zooms() return [float(voxdims[0]),", "list): in_file = in_file[0] img = nibabel.load(in_file) header = img.get_header() voxdims = header.get_zooms()", "voxdims = header.get_zooms() return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] def threshold(in_file, threshold_min=-1e7, threshold_max=1e7): img =", "if np.any(np.isnan(data)): data[np.isnan(data)] = fill_value img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ =", "images. \"\"\" data = [] for f in input_files: image = nibabel.load(f) data.append(image.get_data())", "1: raise ValueError('Non unique file with pattern {}'.format(pattern)) return filenames[0] def _list_to_4d(input_files): \"\"\"Form", "[float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] def threshold(in_file, threshold_min=-1e7, threshold_max=1e7): img = nibabel.load(in_file) data = img.get_data()", "with pattern {}'.format(pattern)) return filenames[0] def _list_to_4d(input_files): \"\"\"Form a 4D data from a", "nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file += '_thresholded.nii' if os.path.isfile(out_file): warnings.warn('File", "np.array(data) data = np.transpose(data, (1, 2, 3, 0)) def check_images(file1, file2): \"\"\"Check that", "{}'.format(pattern)) return None if len(filenames) > 1: raise ValueError('Non unique file with pattern", "nibabel.load(in_file) data = img.get_data() if np.any(np.isnan(data)): data[np.isnan(data)] = fill_value img = nibabel.Nifti1Image(data, img.get_affine(),", "file2): \"\"\"Check that 2 images have the same affines and data shapes. \"\"\"", "os.path.isfile(out_file): warnings.warn('File {} exits, overwriting.'.format(out_file)) nibabel.save(img, out_file) return out_file def remove_nan(in_file, fill_value=0.): img", "image = nibabel.load(f) data.append(image.get_data()) data = np.array(data) data = np.transpose(data, (1, 2, 3,", "_single_glob(pattern): filenames = glob.glob(pattern) if not filenames: print('Warning: non exitant file with pattern", "> 1: raise ValueError('Non unique file with pattern {}'.format(pattern)) return filenames[0] def _list_to_4d(input_files):", "that 2 images have the same affines and data shapes. \"\"\" img =", "exits, overwriting.'.format(out_file)) nibabel.save(img, out_file) return out_file def remove_nan(in_file, fill_value=0.): img = nibabel.load(in_file) data", "filenames: print('Warning: non exitant file with pattern {}'.format(pattern)) return None if len(filenames) >", "shape {3}'.format( file1, shape1, file2, shape2)) if np.any(affine1 != affine2): raise ValueError('affine for", "a 4D data from a list of 3d images. \"\"\" data = []", "file with pattern {}'.format(pattern)) return None if len(filenames) > 1: raise ValueError('Non unique", "= img.get_affine() if shape1 != shape2: raise ValueError('{0} of shape {1}, {2} of", "ValueError('affine for {0}: {1}, for {2}: {3}' .format(file1, affine1, file2, affine2)) def get_vox_dims(in_file):", "{3}' .format(file1, affine1, file2, affine2)) def get_vox_dims(in_file): if isinstance(in_file, list): in_file = in_file[0]", "glob.glob(pattern) if not filenames: print('Warning: non exitant file with pattern {}'.format(pattern)) return None", "raise ValueError('{0} of shape {1}, {2} of shape {3}'.format( file1, shape1, file2, shape2))", "data[data > threshold_max] = threshold_max data[data < threshold_min] = threshold_min img = nibabel.Nifti1Image(data,", "= img.get_affine() img = nibabel.load(file2) shape2 = np.shape(img.get_data()) affine2 = img.get_affine() if shape1", "affine1 = img.get_affine() img = nibabel.load(file2) shape2 = np.shape(img.get_data()) affine2 = img.get_affine() if", "import os import glob import warnings import numpy as np import nibabel def", "os import glob import warnings import numpy as np import nibabel def _single_glob(pattern):", "np.transpose(data, (1, 2, 3, 0)) def check_images(file1, file2): \"\"\"Check that 2 images have", "file1, shape1, file2, shape2)) if np.any(affine1 != affine2): raise ValueError('affine for {0}: {1},", "float(voxdims[2])] def threshold(in_file, threshold_min=-1e7, threshold_max=1e7): img = nibabel.load(in_file) data = img.get_data() data[data >", "return filenames[0] def _list_to_4d(input_files): \"\"\"Form a 4D data from a list of 3d", "= nibabel.load(file2) shape2 = np.shape(img.get_data()) affine2 = img.get_affine() if shape1 != shape2: raise", "= np.shape(img.get_data()) affine2 = img.get_affine() if shape1 != shape2: raise ValueError('{0} of shape", "fill_value=0.): img = nibabel.load(in_file) data = img.get_data() if np.any(np.isnan(data)): data[np.isnan(data)] = fill_value img", "if shape1 != shape2: raise ValueError('{0} of shape {1}, {2} of shape {3}'.format(", "import glob import warnings import numpy as np import nibabel def _single_glob(pattern): filenames", "\"\"\" img = nibabel.load(file1) shape1 = np.shape(img.get_data()) affine1 = img.get_affine() img = nibabel.load(file2)", "shape1 = np.shape(img.get_data()) affine1 = img.get_affine() img = nibabel.load(file2) shape2 = np.shape(img.get_data()) affine2", "threshold_min=-1e7, threshold_max=1e7): img = nibabel.load(in_file) data = img.get_data() data[data > threshold_max] = threshold_max", "out_file += '_thresholded.nii' if os.path.isfile(out_file): warnings.warn('File {} exits, overwriting.'.format(out_file)) nibabel.save(img, out_file) return out_file", "shape {1}, {2} of shape {3}'.format( file1, shape1, file2, shape2)) if np.any(affine1 !=", "list of 3d images. \"\"\" data = [] for f in input_files: image", "shape1 != shape2: raise ValueError('{0} of shape {1}, {2} of shape {3}'.format( file1,", "numpy as np import nibabel def _single_glob(pattern): filenames = glob.glob(pattern) if not filenames:", "of 3d images. \"\"\" data = [] for f in input_files: image =", "header = img.get_header() voxdims = header.get_zooms() return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] def threshold(in_file, threshold_min=-1e7,", "threshold_min] = threshold_min img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file", "\"\"\" data = [] for f in input_files: image = nibabel.load(f) data.append(image.get_data()) data", "return out_file def remove_nan(in_file, fill_value=0.): img = nibabel.load(in_file) data = img.get_data() if np.any(np.isnan(data)):", "img = nibabel.load(in_file) data = img.get_data() if np.any(np.isnan(data)): data[np.isnan(data)] = fill_value img =", "nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file += '_no_nan.nii' nibabel.save(img, out_file) return", "= nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file += '_thresholded.nii' if os.path.isfile(out_file):", "(1, 2, 3, 0)) def check_images(file1, file2): \"\"\"Check that 2 images have the", "exitant file with pattern {}'.format(pattern)) return None if len(filenames) > 1: raise ValueError('Non", "for {2}: {3}' .format(file1, affine1, file2, affine2)) def get_vox_dims(in_file): if isinstance(in_file, list): in_file", "img = nibabel.load(in_file) header = img.get_header() voxdims = header.get_zooms() return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])]", "from a list of 3d images. \"\"\" data = [] for f in", "overwriting.'.format(out_file)) nibabel.save(img, out_file) return out_file def remove_nan(in_file, fill_value=0.): img = nibabel.load(in_file) data =", "raise ValueError('Non unique file with pattern {}'.format(pattern)) return filenames[0] def _list_to_4d(input_files): \"\"\"Form a", "affine2)) def get_vox_dims(in_file): if isinstance(in_file, list): in_file = in_file[0] img = nibabel.load(in_file) header", "nibabel.save(img, out_file) return out_file def remove_nan(in_file, fill_value=0.): img = nibabel.load(in_file) data = img.get_data()", "if isinstance(in_file, list): in_file = in_file[0] img = nibabel.load(in_file) header = img.get_header() voxdims", "img = nibabel.load(in_file) data = img.get_data() data[data > threshold_max] = threshold_max data[data <", "nibabel.load(file1) shape1 = np.shape(img.get_data()) affine1 = img.get_affine() img = nibabel.load(file2) shape2 = np.shape(img.get_data())", "{0}: {1}, for {2}: {3}' .format(file1, affine1, file2, affine2)) def get_vox_dims(in_file): if isinstance(in_file,", "nibabel.load(in_file) header = img.get_header() voxdims = header.get_zooms() return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] def threshold(in_file,", "out_file) return out_file def remove_nan(in_file, fill_value=0.): img = nibabel.load(in_file) data = img.get_data() if", "affines and data shapes. \"\"\" img = nibabel.load(file1) shape1 = np.shape(img.get_data()) affine1 =", "non exitant file with pattern {}'.format(pattern)) return None if len(filenames) > 1: raise", "nibabel.load(file2) shape2 = np.shape(img.get_data()) affine2 = img.get_affine() if shape1 != shape2: raise ValueError('{0}", "= np.array(data) data = np.transpose(data, (1, 2, 3, 0)) def check_images(file1, file2): \"\"\"Check", "in_file = in_file[0] img = nibabel.load(in_file) header = img.get_header() voxdims = header.get_zooms() return", "< threshold_min] = threshold_min img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file)", "data.append(image.get_data()) data = np.array(data) data = np.transpose(data, (1, 2, 3, 0)) def check_images(file1,", "fill_value img = nibabel.Nifti1Image(data, img.get_affine(), img.get_header()) out_file, _ = os.path.splitext(in_file) out_file += '_no_nan.nii'", "def threshold(in_file, threshold_min=-1e7, threshold_max=1e7): img = nibabel.load(in_file) data = img.get_data() data[data > threshold_max]", "ValueError('{0} of shape {1}, {2} of shape {3}'.format( file1, shape1, file2, shape2)) if", "shape2: raise ValueError('{0} of shape {1}, {2} of shape {3}'.format( file1, shape1, file2,", "pattern {}'.format(pattern)) return filenames[0] def _list_to_4d(input_files): \"\"\"Form a 4D data from a list", "= img.get_header() voxdims = header.get_zooms() return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] def threshold(in_file, threshold_min=-1e7, threshold_max=1e7):", "have the same affines and data shapes. \"\"\" img = nibabel.load(file1) shape1 =", "get_vox_dims(in_file): if isinstance(in_file, list): in_file = in_file[0] img = nibabel.load(in_file) header = img.get_header()", "return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] def threshold(in_file, threshold_min=-1e7, threshold_max=1e7): img = nibabel.load(in_file) data =", "for f in input_files: image = nibabel.load(f) data.append(image.get_data()) data = np.array(data) data =", "= np.shape(img.get_data()) affine1 = img.get_affine() img = nibabel.load(file2) shape2 = np.shape(img.get_data()) affine2 =", "= np.transpose(data, (1, 2, 3, 0)) def check_images(file1, file2): \"\"\"Check that 2 images" ]
[ "= self.selected.values() for el in elements: current_classes = el.attrib.has_key(\"class\") and el.attrib[\"class\"].split() or []", "optionally removing the elements' styling. If inline styles are not removed, the css", "action=\"store\", type=\"string\", dest=\"name\", default=\"\", help=\"Name of css class to apply\") self.OptionParser.add_option(\"-c\", \"--clear_styles\", action=\"store\",", "inline styles are not removed, the css class might not have effect. Inspired", "elements: current_classes = el.attrib.has_key(\"class\") and el.attrib[\"class\"].split() or [] if newclass not in current_classes:", "(and best used together with it). \"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\"", "\"\" el.attrib[\"class\"] = \" \".join(current_classes) if __name__ == \"__main__\": e = SetCSSClass() e.affect()", "or [] if newclass not in current_classes: current_classes.append(newclass) if self.options.clear_styles: el.attrib[\"style\"] = \"\"", "class to apply\") def effect(self): newclass = self.options.name elements = self.selected.values() for el", "def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option(\"-n\", \"--name\", action=\"store\", type=\"string\", dest=\"name\", default=\"\", help=\"Name of css class", "If inline styles are not removed, the css class might not have effect.", "type=\"inkbool\", dest=\"clear_styles\", default=True, help=\"Name of css class to apply\") def effect(self): newclass =", "effect(self): newclass = self.options.name elements = self.selected.values() for el in elements: current_classes =", "css class on selected elements, while optionally removing the elements' styling. If inline", "the css class might not have effect. Inspired by MergeStyles (and best used", "import inkex import sys class SetCSSClass(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option(\"-n\", \"--name\", action=\"store\", type=\"string\",", "for el in elements: current_classes = el.attrib.has_key(\"class\") and el.attrib[\"class\"].split() or [] if newclass", "__copyright__ = \"Copyright (C) 2017 Mois Moshev\" __license__ = \"GPL\" import inkex import", "css class to apply\") self.OptionParser.add_option(\"-c\", \"--clear_styles\", action=\"store\", type=\"inkbool\", dest=\"clear_styles\", default=True, help=\"Name of css", "it). \"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"Copyright (C) 2017", "help=\"Name of css class to apply\") self.OptionParser.add_option(\"-c\", \"--clear_styles\", action=\"store\", type=\"inkbool\", dest=\"clear_styles\", default=True, help=\"Name", "if newclass not in current_classes: current_classes.append(newclass) if self.options.clear_styles: el.attrib[\"style\"] = \"\" el.attrib[\"class\"] =", "of css class to apply\") def effect(self): newclass = self.options.name elements = self.selected.values()", "to apply\") def effect(self): newclass = self.options.name elements = self.selected.values() for el in", "a css class on selected elements, while optionally removing the elements' styling. If", "current_classes.append(newclass) if self.options.clear_styles: el.attrib[\"style\"] = \"\" el.attrib[\"class\"] = \" \".join(current_classes) if __name__ ==", "current_classes = el.attrib.has_key(\"class\") and el.attrib[\"class\"].split() or [] if newclass not in current_classes: current_classes.append(newclass)", "= \"GPL\" import inkex import sys class SetCSSClass(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option(\"-n\", \"--name\",", "self.options.name elements = self.selected.values() for el in elements: current_classes = el.attrib.has_key(\"class\") and el.attrib[\"class\"].split()", "might not have effect. Inspired by MergeStyles (and best used together with it).", "\"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"Copyright (C) 2017 Mois", "\"--clear_styles\", action=\"store\", type=\"inkbool\", dest=\"clear_styles\", default=True, help=\"Name of css class to apply\") def effect(self):", "together with it). \"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"Copyright", "Moshev\" __license__ = \"GPL\" import inkex import sys class SetCSSClass(inkex.Effect): def __init__(self): inkex.Effect.__init__(self)", "def effect(self): newclass = self.options.name elements = self.selected.values() for el in elements: current_classes", "self.options.clear_styles: el.attrib[\"style\"] = \"\" el.attrib[\"class\"] = \" \".join(current_classes) if __name__ == \"__main__\": e", "newclass not in current_classes: current_classes.append(newclass) if self.options.clear_styles: el.attrib[\"style\"] = \"\" el.attrib[\"class\"] = \"", "removed, the css class might not have effect. Inspired by MergeStyles (and best", "with it). \"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"Copyright (C)", "newclass = self.options.name elements = self.selected.values() for el in elements: current_classes = el.attrib.has_key(\"class\")", "css class might not have effect. Inspired by MergeStyles (and best used together", "used together with it). \"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ =", "__author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"Copyright (C) 2017 Mois Moshev\"", "elements = self.selected.values() for el in elements: current_classes = el.attrib.has_key(\"class\") and el.attrib[\"class\"].split() or", "if self.options.clear_styles: el.attrib[\"style\"] = \"\" el.attrib[\"class\"] = \" \".join(current_classes) if __name__ == \"__main__\":", "#!/usr/bin/env python \"\"\" Sets a css class on selected elements, while optionally removing", "action=\"store\", type=\"inkbool\", dest=\"clear_styles\", default=True, help=\"Name of css class to apply\") def effect(self): newclass", "= \"Copyright (C) 2017 Mois Moshev\" __license__ = \"GPL\" import inkex import sys", "in elements: current_classes = el.attrib.has_key(\"class\") and el.attrib[\"class\"].split() or [] if newclass not in", "el.attrib.has_key(\"class\") and el.attrib[\"class\"].split() or [] if newclass not in current_classes: current_classes.append(newclass) if self.options.clear_styles:", "not have effect. Inspired by MergeStyles (and best used together with it). \"\"\"", "= self.options.name elements = self.selected.values() for el in elements: current_classes = el.attrib.has_key(\"class\") and", "in current_classes: current_classes.append(newclass) if self.options.clear_styles: el.attrib[\"style\"] = \"\" el.attrib[\"class\"] = \" \".join(current_classes) if", "best used together with it). \"\"\" __author__ = \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__", "self.OptionParser.add_option(\"-n\", \"--name\", action=\"store\", type=\"string\", dest=\"name\", default=\"\", help=\"Name of css class to apply\") self.OptionParser.add_option(\"-c\",", "inkex.Effect.__init__(self) self.OptionParser.add_option(\"-n\", \"--name\", action=\"store\", type=\"string\", dest=\"name\", default=\"\", help=\"Name of css class to apply\")", "<filename>inkscape-set-css-class-master/set_css_class.py #!/usr/bin/env python \"\"\" Sets a css class on selected elements, while optionally", "effect. Inspired by MergeStyles (and best used together with it). \"\"\" __author__ =", "\"--name\", action=\"store\", type=\"string\", dest=\"name\", default=\"\", help=\"Name of css class to apply\") self.OptionParser.add_option(\"-c\", \"--clear_styles\",", "styles are not removed, the css class might not have effect. Inspired by", "elements, while optionally removing the elements' styling. If inline styles are not removed,", "__init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option(\"-n\", \"--name\", action=\"store\", type=\"string\", dest=\"name\", default=\"\", help=\"Name of css class to", "help=\"Name of css class to apply\") def effect(self): newclass = self.options.name elements =", "class might not have effect. Inspired by MergeStyles (and best used together with", "= el.attrib.has_key(\"class\") and el.attrib[\"class\"].split() or [] if newclass not in current_classes: current_classes.append(newclass) if", "elements' styling. If inline styles are not removed, the css class might not", "selected elements, while optionally removing the elements' styling. If inline styles are not", "el.attrib[\"class\"].split() or [] if newclass not in current_classes: current_classes.append(newclass) if self.options.clear_styles: el.attrib[\"style\"] =", "\"GPL\" import inkex import sys class SetCSSClass(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option(\"-n\", \"--name\", action=\"store\",", "have effect. Inspired by MergeStyles (and best used together with it). \"\"\" __author__", "to apply\") self.OptionParser.add_option(\"-c\", \"--clear_styles\", action=\"store\", type=\"inkbool\", dest=\"clear_styles\", default=True, help=\"Name of css class to", "el.attrib[\"style\"] = \"\" el.attrib[\"class\"] = \" \".join(current_classes) if __name__ == \"__main__\": e =", "dest=\"name\", default=\"\", help=\"Name of css class to apply\") self.OptionParser.add_option(\"-c\", \"--clear_styles\", action=\"store\", type=\"inkbool\", dest=\"clear_styles\",", "SetCSSClass(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option(\"-n\", \"--name\", action=\"store\", type=\"string\", dest=\"name\", default=\"\", help=\"Name of css", "self.OptionParser.add_option(\"-c\", \"--clear_styles\", action=\"store\", type=\"inkbool\", dest=\"clear_styles\", default=True, help=\"Name of css class to apply\") def", "inkex import sys class SetCSSClass(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option(\"-n\", \"--name\", action=\"store\", type=\"string\", dest=\"name\",", "the elements' styling. If inline styles are not removed, the css class might", "self.selected.values() for el in elements: current_classes = el.attrib.has_key(\"class\") and el.attrib[\"class\"].split() or [] if", "are not removed, the css class might not have effect. Inspired by MergeStyles", "python \"\"\" Sets a css class on selected elements, while optionally removing the", "[] if newclass not in current_classes: current_classes.append(newclass) if self.options.clear_styles: el.attrib[\"style\"] = \"\" el.attrib[\"class\"]", "type=\"string\", dest=\"name\", default=\"\", help=\"Name of css class to apply\") self.OptionParser.add_option(\"-c\", \"--clear_styles\", action=\"store\", type=\"inkbool\",", "default=True, help=\"Name of css class to apply\") def effect(self): newclass = self.options.name elements", "= \"\" el.attrib[\"class\"] = \" \".join(current_classes) if __name__ == \"__main__\": e = SetCSSClass()", "= \"<EMAIL>\" __copyright__ = \"Copyright (C) 2017 Mois Moshev\" __license__ = \"GPL\" import", "import sys class SetCSSClass(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option(\"-n\", \"--name\", action=\"store\", type=\"string\", dest=\"name\", default=\"\",", "Sets a css class on selected elements, while optionally removing the elements' styling.", "class to apply\") self.OptionParser.add_option(\"-c\", \"--clear_styles\", action=\"store\", type=\"inkbool\", dest=\"clear_styles\", default=True, help=\"Name of css class", "MergeStyles (and best used together with it). \"\"\" __author__ = \"<NAME>\" __email__ =", "of css class to apply\") self.OptionParser.add_option(\"-c\", \"--clear_styles\", action=\"store\", type=\"inkbool\", dest=\"clear_styles\", default=True, help=\"Name of", "on selected elements, while optionally removing the elements' styling. If inline styles are", "\"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"Copyright (C) 2017 Mois Moshev\" __license__ =", "__email__ = \"<EMAIL>\" __copyright__ = \"Copyright (C) 2017 Mois Moshev\" __license__ = \"GPL\"", "not removed, the css class might not have effect. Inspired by MergeStyles (and", "Mois Moshev\" __license__ = \"GPL\" import inkex import sys class SetCSSClass(inkex.Effect): def __init__(self):", "styling. If inline styles are not removed, the css class might not have", "sys class SetCSSClass(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option(\"-n\", \"--name\", action=\"store\", type=\"string\", dest=\"name\", default=\"\", help=\"Name", "apply\") self.OptionParser.add_option(\"-c\", \"--clear_styles\", action=\"store\", type=\"inkbool\", dest=\"clear_styles\", default=True, help=\"Name of css class to apply\")", "css class to apply\") def effect(self): newclass = self.options.name elements = self.selected.values() for", "class SetCSSClass(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option(\"-n\", \"--name\", action=\"store\", type=\"string\", dest=\"name\", default=\"\", help=\"Name of", "Inspired by MergeStyles (and best used together with it). \"\"\" __author__ = \"<NAME>\"", "not in current_classes: current_classes.append(newclass) if self.options.clear_styles: el.attrib[\"style\"] = \"\" el.attrib[\"class\"] = \" \".join(current_classes)", "\"Copyright (C) 2017 Mois Moshev\" __license__ = \"GPL\" import inkex import sys class", "= \"<NAME>\" __email__ = \"<EMAIL>\" __copyright__ = \"Copyright (C) 2017 Mois Moshev\" __license__", "default=\"\", help=\"Name of css class to apply\") self.OptionParser.add_option(\"-c\", \"--clear_styles\", action=\"store\", type=\"inkbool\", dest=\"clear_styles\", default=True,", "while optionally removing the elements' styling. If inline styles are not removed, the", "removing the elements' styling. If inline styles are not removed, the css class", "current_classes: current_classes.append(newclass) if self.options.clear_styles: el.attrib[\"style\"] = \"\" el.attrib[\"class\"] = \" \".join(current_classes) if __name__", "\"\"\" Sets a css class on selected elements, while optionally removing the elements'", "dest=\"clear_styles\", default=True, help=\"Name of css class to apply\") def effect(self): newclass = self.options.name", "2017 Mois Moshev\" __license__ = \"GPL\" import inkex import sys class SetCSSClass(inkex.Effect): def", "__license__ = \"GPL\" import inkex import sys class SetCSSClass(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option(\"-n\",", "by MergeStyles (and best used together with it). \"\"\" __author__ = \"<NAME>\" __email__", "apply\") def effect(self): newclass = self.options.name elements = self.selected.values() for el in elements:", "\"<EMAIL>\" __copyright__ = \"Copyright (C) 2017 Mois Moshev\" __license__ = \"GPL\" import inkex", "(C) 2017 Mois Moshev\" __license__ = \"GPL\" import inkex import sys class SetCSSClass(inkex.Effect):", "el in elements: current_classes = el.attrib.has_key(\"class\") and el.attrib[\"class\"].split() or [] if newclass not", "class on selected elements, while optionally removing the elements' styling. If inline styles", "and el.attrib[\"class\"].split() or [] if newclass not in current_classes: current_classes.append(newclass) if self.options.clear_styles: el.attrib[\"style\"]" ]
[]
[ "= GenericForeignKey() grant = models.ForeignKey(Grant, models.PROTECT) class Meta: verbose_name = \"grant rekordu\" verbose_name_plural", "CASCADE class Grant(models.Model): nazwa_projektu = models.TextField(blank=True, null=True) zrodlo_finansowania = models.TextField(blank=True, null=True) numer_projektu =", "Meta: verbose_name = \"grant rekordu\" verbose_name_plural = \"granty rekordu\" unique_together = [(\"grant\", \"content_type\",", "Grant_Rekordu(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() rekord = GenericForeignKey() grant =", "GenericForeignKey() grant = models.ForeignKey(Grant, models.PROTECT) class Meta: verbose_name = \"grant rekordu\" verbose_name_plural =", "or ''}\".strip() class Grant_Rekordu(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() rekord =", "models.CharField(max_length=200, unique=True) rok = models.PositiveSmallIntegerField(null=True, blank=True) class Meta: verbose_name = \"grant\" verbose_name_plural =", "import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models import", "models.TextField(blank=True, null=True) numer_projektu = models.CharField(max_length=200, unique=True) rok = models.PositiveSmallIntegerField(null=True, blank=True) class Meta: verbose_name", "import ContentType from django.db import models from django.db.models import CASCADE class Grant(models.Model): nazwa_projektu", "GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models import CASCADE", "\"granty\" def __str__(self): return f\"{self.numer_projektu} {self.nazwa_projektu or ''}\".strip() class Grant_Rekordu(models.Model): content_type = models.ForeignKey(ContentType,", "f\"{self.numer_projektu} {self.nazwa_projektu or ''}\".strip() class Grant_Rekordu(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField()", "blank=True) class Meta: verbose_name = \"grant\" verbose_name_plural = \"granty\" def __str__(self): return f\"{self.numer_projektu}", "{self.nazwa_projektu or ''}\".strip() class Grant_Rekordu(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() rekord", "models.PositiveSmallIntegerField(null=True, blank=True) class Meta: verbose_name = \"grant\" verbose_name_plural = \"granty\" def __str__(self): return", "content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() rekord = GenericForeignKey() grant = models.ForeignKey(Grant,", "return f\"{self.numer_projektu} {self.nazwa_projektu or ''}\".strip() class Grant_Rekordu(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id =", "class Grant(models.Model): nazwa_projektu = models.TextField(blank=True, null=True) zrodlo_finansowania = models.TextField(blank=True, null=True) numer_projektu = models.CharField(max_length=200,", "models from django.db.models import CASCADE class Grant(models.Model): nazwa_projektu = models.TextField(blank=True, null=True) zrodlo_finansowania =", "models.CASCADE) object_id = models.PositiveIntegerField() rekord = GenericForeignKey() grant = models.ForeignKey(Grant, models.PROTECT) class Meta:", "verbose_name_plural = \"granty\" def __str__(self): return f\"{self.numer_projektu} {self.nazwa_projektu or ''}\".strip() class Grant_Rekordu(models.Model): content_type", "class Grant_Rekordu(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() rekord = GenericForeignKey() grant", "''}\".strip() class Grant_Rekordu(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() rekord = GenericForeignKey()", "django.db import models from django.db.models import CASCADE class Grant(models.Model): nazwa_projektu = models.TextField(blank=True, null=True)", "from django.db.models import CASCADE class Grant(models.Model): nazwa_projektu = models.TextField(blank=True, null=True) zrodlo_finansowania = models.TextField(blank=True,", "null=True) numer_projektu = models.CharField(max_length=200, unique=True) rok = models.PositiveSmallIntegerField(null=True, blank=True) class Meta: verbose_name =", "ContentType from django.db import models from django.db.models import CASCADE class Grant(models.Model): nazwa_projektu =", "import CASCADE class Grant(models.Model): nazwa_projektu = models.TextField(blank=True, null=True) zrodlo_finansowania = models.TextField(blank=True, null=True) numer_projektu", "rok = models.PositiveSmallIntegerField(null=True, blank=True) class Meta: verbose_name = \"grant\" verbose_name_plural = \"granty\" def", "from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models import CASCADE class", "unique=True) rok = models.PositiveSmallIntegerField(null=True, blank=True) class Meta: verbose_name = \"grant\" verbose_name_plural = \"granty\"", "= models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() rekord = GenericForeignKey() grant = models.ForeignKey(Grant, models.PROTECT)", "= models.PositiveIntegerField() rekord = GenericForeignKey() grant = models.ForeignKey(Grant, models.PROTECT) class Meta: verbose_name =", "verbose_name = \"grant rekordu\" verbose_name_plural = \"granty rekordu\" unique_together = [(\"grant\", \"content_type\", \"object_id\")]", "= models.ForeignKey(Grant, models.PROTECT) class Meta: verbose_name = \"grant rekordu\" verbose_name_plural = \"granty rekordu\"", "def __str__(self): return f\"{self.numer_projektu} {self.nazwa_projektu or ''}\".strip() class Grant_Rekordu(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE)", "Grant(models.Model): nazwa_projektu = models.TextField(blank=True, null=True) zrodlo_finansowania = models.TextField(blank=True, null=True) numer_projektu = models.CharField(max_length=200, unique=True)", "rekord = GenericForeignKey() grant = models.ForeignKey(Grant, models.PROTECT) class Meta: verbose_name = \"grant rekordu\"", "from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from", "null=True) zrodlo_finansowania = models.TextField(blank=True, null=True) numer_projektu = models.CharField(max_length=200, unique=True) rok = models.PositiveSmallIntegerField(null=True, blank=True)", "grant = models.ForeignKey(Grant, models.PROTECT) class Meta: verbose_name = \"grant rekordu\" verbose_name_plural = \"granty", "verbose_name = \"grant\" verbose_name_plural = \"granty\" def __str__(self): return f\"{self.numer_projektu} {self.nazwa_projektu or ''}\".strip()", "\"grant\" verbose_name_plural = \"granty\" def __str__(self): return f\"{self.numer_projektu} {self.nazwa_projektu or ''}\".strip() class Grant_Rekordu(models.Model):", "Meta: verbose_name = \"grant\" verbose_name_plural = \"granty\" def __str__(self): return f\"{self.numer_projektu} {self.nazwa_projektu or", "django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models", "numer_projektu = models.CharField(max_length=200, unique=True) rok = models.PositiveSmallIntegerField(null=True, blank=True) class Meta: verbose_name = \"grant\"", "models.PROTECT) class Meta: verbose_name = \"grant rekordu\" verbose_name_plural = \"granty rekordu\" unique_together =", "= \"grant\" verbose_name_plural = \"granty\" def __str__(self): return f\"{self.numer_projektu} {self.nazwa_projektu or ''}\".strip() class", "django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models import CASCADE class Grant(models.Model):", "models.PositiveIntegerField() rekord = GenericForeignKey() grant = models.ForeignKey(Grant, models.PROTECT) class Meta: verbose_name = \"grant", "= models.TextField(blank=True, null=True) zrodlo_finansowania = models.TextField(blank=True, null=True) numer_projektu = models.CharField(max_length=200, unique=True) rok =", "models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() rekord = GenericForeignKey() grant = models.ForeignKey(Grant, models.PROTECT) class", "= models.CharField(max_length=200, unique=True) rok = models.PositiveSmallIntegerField(null=True, blank=True) class Meta: verbose_name = \"grant\" verbose_name_plural", "__str__(self): return f\"{self.numer_projektu} {self.nazwa_projektu or ''}\".strip() class Grant_Rekordu(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id", "from django.db import models from django.db.models import CASCADE class Grant(models.Model): nazwa_projektu = models.TextField(blank=True,", "import models from django.db.models import CASCADE class Grant(models.Model): nazwa_projektu = models.TextField(blank=True, null=True) zrodlo_finansowania", "nazwa_projektu = models.TextField(blank=True, null=True) zrodlo_finansowania = models.TextField(blank=True, null=True) numer_projektu = models.CharField(max_length=200, unique=True) rok", "object_id = models.PositiveIntegerField() rekord = GenericForeignKey() grant = models.ForeignKey(Grant, models.PROTECT) class Meta: verbose_name", "class Meta: verbose_name = \"grant rekordu\" verbose_name_plural = \"granty rekordu\" unique_together = [(\"grant\",", "= models.PositiveSmallIntegerField(null=True, blank=True) class Meta: verbose_name = \"grant\" verbose_name_plural = \"granty\" def __str__(self):", "= \"granty\" def __str__(self): return f\"{self.numer_projektu} {self.nazwa_projektu or ''}\".strip() class Grant_Rekordu(models.Model): content_type =", "class Meta: verbose_name = \"grant\" verbose_name_plural = \"granty\" def __str__(self): return f\"{self.numer_projektu} {self.nazwa_projektu", "models.ForeignKey(Grant, models.PROTECT) class Meta: verbose_name = \"grant rekordu\" verbose_name_plural = \"granty rekordu\" unique_together", "zrodlo_finansowania = models.TextField(blank=True, null=True) numer_projektu = models.CharField(max_length=200, unique=True) rok = models.PositiveSmallIntegerField(null=True, blank=True) class", "= models.TextField(blank=True, null=True) numer_projektu = models.CharField(max_length=200, unique=True) rok = models.PositiveSmallIntegerField(null=True, blank=True) class Meta:", "models.TextField(blank=True, null=True) zrodlo_finansowania = models.TextField(blank=True, null=True) numer_projektu = models.CharField(max_length=200, unique=True) rok = models.PositiveSmallIntegerField(null=True,", "django.db.models import CASCADE class Grant(models.Model): nazwa_projektu = models.TextField(blank=True, null=True) zrodlo_finansowania = models.TextField(blank=True, null=True)" ]
[ "-*- coding: utf-8 -*- import jieba jieba.load_userdict(\"user_dict.txt\") line_list = [\"查询安顺站一号风机的电压曲线\", \"查询安各庄1母线的故障信息\", \"开始进行南京站设备状态核实\", \"看下安顺站3月1号的静态功率曲线\"]", "\"查询安各庄1母线的故障信息\", \"开始进行南京站设备状态核实\", \"看下安顺站3月1号的静态功率曲线\"] for cur_line in line_list: seg_list = jieba.cut(cur_line.strip()) print(\"jieba rst: \"", "jieba jieba.load_userdict(\"user_dict.txt\") line_list = [\"查询安顺站一号风机的电压曲线\", \"查询安各庄1母线的故障信息\", \"开始进行南京站设备状态核实\", \"看下安顺站3月1号的静态功率曲线\"] for cur_line in line_list: seg_list", "= [\"查询安顺站一号风机的电压曲线\", \"查询安各庄1母线的故障信息\", \"开始进行南京站设备状态核实\", \"看下安顺站3月1号的静态功率曲线\"] for cur_line in line_list: seg_list = jieba.cut(cur_line.strip()) print(\"jieba", "[\"查询安顺站一号风机的电压曲线\", \"查询安各庄1母线的故障信息\", \"开始进行南京站设备状态核实\", \"看下安顺站3月1号的静态功率曲线\"] for cur_line in line_list: seg_list = jieba.cut(cur_line.strip()) print(\"jieba rst:", "\"开始进行南京站设备状态核实\", \"看下安顺站3月1号的静态功率曲线\"] for cur_line in line_list: seg_list = jieba.cut(cur_line.strip()) print(\"jieba rst: \" +", "<gh_stars>0 # -*- coding: utf-8 -*- import jieba jieba.load_userdict(\"user_dict.txt\") line_list = [\"查询安顺站一号风机的电压曲线\", \"查询安各庄1母线的故障信息\",", "line_list = [\"查询安顺站一号风机的电压曲线\", \"查询安各庄1母线的故障信息\", \"开始进行南京站设备状态核实\", \"看下安顺站3月1号的静态功率曲线\"] for cur_line in line_list: seg_list = jieba.cut(cur_line.strip())", "utf-8 -*- import jieba jieba.load_userdict(\"user_dict.txt\") line_list = [\"查询安顺站一号风机的电压曲线\", \"查询安各庄1母线的故障信息\", \"开始进行南京站设备状态核实\", \"看下安顺站3月1号的静态功率曲线\"] for cur_line", "jieba.load_userdict(\"user_dict.txt\") line_list = [\"查询安顺站一号风机的电压曲线\", \"查询安各庄1母线的故障信息\", \"开始进行南京站设备状态核实\", \"看下安顺站3月1号的静态功率曲线\"] for cur_line in line_list: seg_list =", "\"看下安顺站3月1号的静态功率曲线\"] for cur_line in line_list: seg_list = jieba.cut(cur_line.strip()) print(\"jieba rst: \" + \"/", "for cur_line in line_list: seg_list = jieba.cut(cur_line.strip()) print(\"jieba rst: \" + \"/ \".join(seg_list))", "import jieba jieba.load_userdict(\"user_dict.txt\") line_list = [\"查询安顺站一号风机的电压曲线\", \"查询安各庄1母线的故障信息\", \"开始进行南京站设备状态核实\", \"看下安顺站3月1号的静态功率曲线\"] for cur_line in line_list:", "coding: utf-8 -*- import jieba jieba.load_userdict(\"user_dict.txt\") line_list = [\"查询安顺站一号风机的电压曲线\", \"查询安各庄1母线的故障信息\", \"开始进行南京站设备状态核实\", \"看下安顺站3月1号的静态功率曲线\"] for", "-*- import jieba jieba.load_userdict(\"user_dict.txt\") line_list = [\"查询安顺站一号风机的电压曲线\", \"查询安各庄1母线的故障信息\", \"开始进行南京站设备状态核实\", \"看下安顺站3月1号的静态功率曲线\"] for cur_line in", "# -*- coding: utf-8 -*- import jieba jieba.load_userdict(\"user_dict.txt\") line_list = [\"查询安顺站一号风机的电压曲线\", \"查询安各庄1母线的故障信息\", \"开始进行南京站设备状态核实\"," ]
[ "run_python(request): \"\"\" A page to allow testing the Python sandbox on a production", "def run_python(request): \"\"\" A page to allow testing the Python sandbox on a", "from django.utils.html import escape from django.views.decorators.csrf import ensure_csrf_cookie from common.djangoapps.edxmako.shortcuts import render_to_response from", "first from: CODE_JAIL['limit_overrides']['debug_run_python'] and then from: CODE_JAIL['limits'] \"\"\" if not request.user.is_staff: raise Http404", "Exception: # pylint: disable=broad-except c['results'] = traceback.format_exc() else: c['results'] = pprint.pformat(g) return render_to_response(\"debug/run_python_form.html\",", "escape from django.views.decorators.csrf import ensure_csrf_cookie from common.djangoapps.edxmako.shortcuts import render_to_response from openedx.core.djangolib.markup import HTML", "= traceback.format_exc() else: c['results'] = pprint.pformat(g) return render_to_response(\"debug/run_python_form.html\", c) @login_required def show_parameters(request): \"\"\"A", "= [] for name, value in sorted(request.GET.items()): html_list.append(escape(f\"GET {name}: {value!r}\")) for name, value", "and diagnostics\"\"\" import pprint import traceback from codejail.safe_exec import safe_exec from django.contrib.auth.decorators import", "A page to allow testing the Python sandbox on a production server. Runs", "on the URL and post.\"\"\" html_list = [] for name, value in sorted(request.GET.items()):", "import Http404, HttpResponse from django.utils.html import escape from django.views.decorators.csrf import ensure_csrf_cookie from common.djangoapps.edxmako.shortcuts", "from openedx.core.djangolib.markup import HTML @login_required @ensure_csrf_cookie def run_python(request): \"\"\" A page to allow", "and post.\"\"\" html_list = [] for name, value in sorted(request.GET.items()): html_list.append(escape(f\"GET {name}: {value!r}\"))", "c['results'] = pprint.pformat(g) return render_to_response(\"debug/run_python_form.html\", c) @login_required def show_parameters(request): \"\"\"A page that shows", "except Exception: # pylint: disable=broad-except c['results'] = traceback.format_exc() else: c['results'] = pprint.pformat(g) return", "the override context \"debug_run_python\", so resource limits with come first from: CODE_JAIL['limit_overrides']['debug_run_python'] and", "c['code'] = '' c['results'] = None if request.method == 'POST': py_code = c['code']", "= '' c['results'] = None if request.method == 'POST': py_code = c['code'] =", "so resource limits with come first from: CODE_JAIL['limit_overrides']['debug_run_python'] and then from: CODE_JAIL['limits'] \"\"\"", "URL and post.\"\"\" html_list = [] for name, value in sorted(request.GET.items()): html_list.append(escape(f\"GET {name}:", "pylint: disable=broad-except c['results'] = traceback.format_exc() else: c['results'] = pprint.pformat(g) return render_to_response(\"debug/run_python_form.html\", c) @login_required", "from django.views.decorators.csrf import ensure_csrf_cookie from common.djangoapps.edxmako.shortcuts import render_to_response from openedx.core.djangolib.markup import HTML @login_required", "from: CODE_JAIL['limits'] \"\"\" if not request.user.is_staff: raise Http404 c = {} c['code'] =", "CODE_JAIL['limit_overrides']['debug_run_python'] and then from: CODE_JAIL['limits'] \"\"\" if not request.user.is_staff: raise Http404 c =", "html_list.append(escape(f\"GET {name}: {value!r}\")) for name, value in sorted(request.POST.items()): html_list.append(escape(f\"POST {name}: {value!r}\")) return HttpResponse(\"\\n\".join(HTML(\"<p>{}</p>\").format(h)", "\"debug_run_python\", so resource limits with come first from: CODE_JAIL['limit_overrides']['debug_run_python'] and then from: CODE_JAIL['limits']", "pprint import traceback from codejail.safe_exec import safe_exec from django.contrib.auth.decorators import login_required from django.http", "c['results'] = traceback.format_exc() else: c['results'] = pprint.pformat(g) return render_to_response(\"debug/run_python_form.html\", c) @login_required def show_parameters(request):", "if not request.user.is_staff: raise Http404 c = {} c['code'] = '' c['results'] =", "= c['code'] = request.POST.get('code') g = {} try: safe_exec( code=py_code, globals_dict=g, slug=\"debug_run_python\", limit_overrides_context=\"debug_run_python\",", "that shows what parameters were on the URL and post.\"\"\" html_list = []", "post.\"\"\" html_list = [] for name, value in sorted(request.GET.items()): html_list.append(escape(f\"GET {name}: {value!r}\")) for", "on a production server. Runs in the override context \"debug_run_python\", so resource limits", "if request.method == 'POST': py_code = c['code'] = request.POST.get('code') g = {} try:", "name, value in sorted(request.POST.items()): html_list.append(escape(f\"POST {name}: {value!r}\")) return HttpResponse(\"\\n\".join(HTML(\"<p>{}</p>\").format(h) for h in html_list))", "safe_exec( code=py_code, globals_dict=g, slug=\"debug_run_python\", limit_overrides_context=\"debug_run_python\", ) except Exception: # pylint: disable=broad-except c['results'] =", "import traceback from codejail.safe_exec import safe_exec from django.contrib.auth.decorators import login_required from django.http import", "import ensure_csrf_cookie from common.djangoapps.edxmako.shortcuts import render_to_response from openedx.core.djangolib.markup import HTML @login_required @ensure_csrf_cookie def", "\"\"\"Views for debugging and diagnostics\"\"\" import pprint import traceback from codejail.safe_exec import safe_exec", "HTML @login_required @ensure_csrf_cookie def run_python(request): \"\"\" A page to allow testing the Python", "= {} try: safe_exec( code=py_code, globals_dict=g, slug=\"debug_run_python\", limit_overrides_context=\"debug_run_python\", ) except Exception: # pylint:", "c) @login_required def show_parameters(request): \"\"\"A page that shows what parameters were on the", "django.http import Http404, HttpResponse from django.utils.html import escape from django.views.decorators.csrf import ensure_csrf_cookie from", "page that shows what parameters were on the URL and post.\"\"\" html_list =", "login_required from django.http import Http404, HttpResponse from django.utils.html import escape from django.views.decorators.csrf import", "'POST': py_code = c['code'] = request.POST.get('code') g = {} try: safe_exec( code=py_code, globals_dict=g,", "common.djangoapps.edxmako.shortcuts import render_to_response from openedx.core.djangolib.markup import HTML @login_required @ensure_csrf_cookie def run_python(request): \"\"\" A", "c['code'] = request.POST.get('code') g = {} try: safe_exec( code=py_code, globals_dict=g, slug=\"debug_run_python\", limit_overrides_context=\"debug_run_python\", )", "value in sorted(request.GET.items()): html_list.append(escape(f\"GET {name}: {value!r}\")) for name, value in sorted(request.POST.items()): html_list.append(escape(f\"POST {name}:", "# pylint: disable=broad-except c['results'] = traceback.format_exc() else: c['results'] = pprint.pformat(g) return render_to_response(\"debug/run_python_form.html\", c)", "then from: CODE_JAIL['limits'] \"\"\" if not request.user.is_staff: raise Http404 c = {} c['code']", "c = {} c['code'] = '' c['results'] = None if request.method == 'POST':", "from django.http import Http404, HttpResponse from django.utils.html import escape from django.views.decorators.csrf import ensure_csrf_cookie", "codejail.safe_exec import safe_exec from django.contrib.auth.decorators import login_required from django.http import Http404, HttpResponse from", "raise Http404 c = {} c['code'] = '' c['results'] = None if request.method", "= pprint.pformat(g) return render_to_response(\"debug/run_python_form.html\", c) @login_required def show_parameters(request): \"\"\"A page that shows what", "from codejail.safe_exec import safe_exec from django.contrib.auth.decorators import login_required from django.http import Http404, HttpResponse", "import safe_exec from django.contrib.auth.decorators import login_required from django.http import Http404, HttpResponse from django.utils.html", "== 'POST': py_code = c['code'] = request.POST.get('code') g = {} try: safe_exec( code=py_code,", "sorted(request.GET.items()): html_list.append(escape(f\"GET {name}: {value!r}\")) for name, value in sorted(request.POST.items()): html_list.append(escape(f\"POST {name}: {value!r}\")) return", "debugging and diagnostics\"\"\" import pprint import traceback from codejail.safe_exec import safe_exec from django.contrib.auth.decorators", "return render_to_response(\"debug/run_python_form.html\", c) @login_required def show_parameters(request): \"\"\"A page that shows what parameters were", "ensure_csrf_cookie from common.djangoapps.edxmako.shortcuts import render_to_response from openedx.core.djangolib.markup import HTML @login_required @ensure_csrf_cookie def run_python(request):", "import render_to_response from openedx.core.djangolib.markup import HTML @login_required @ensure_csrf_cookie def run_python(request): \"\"\" A page", "= None if request.method == 'POST': py_code = c['code'] = request.POST.get('code') g =", "Runs in the override context \"debug_run_python\", so resource limits with come first from:", "were on the URL and post.\"\"\" html_list = [] for name, value in", "import HTML @login_required @ensure_csrf_cookie def run_python(request): \"\"\" A page to allow testing the", "slug=\"debug_run_python\", limit_overrides_context=\"debug_run_python\", ) except Exception: # pylint: disable=broad-except c['results'] = traceback.format_exc() else: c['results']", "from common.djangoapps.edxmako.shortcuts import render_to_response from openedx.core.djangolib.markup import HTML @login_required @ensure_csrf_cookie def run_python(request): \"\"\"", "= {} c['code'] = '' c['results'] = None if request.method == 'POST': py_code", "traceback.format_exc() else: c['results'] = pprint.pformat(g) return render_to_response(\"debug/run_python_form.html\", c) @login_required def show_parameters(request): \"\"\"A page", "server. Runs in the override context \"debug_run_python\", so resource limits with come first", "openedx.core.djangolib.markup import HTML @login_required @ensure_csrf_cookie def run_python(request): \"\"\" A page to allow testing", "Python sandbox on a production server. Runs in the override context \"debug_run_python\", so", "name, value in sorted(request.GET.items()): html_list.append(escape(f\"GET {name}: {value!r}\")) for name, value in sorted(request.POST.items()): html_list.append(escape(f\"POST", "sandbox on a production server. Runs in the override context \"debug_run_python\", so resource", "a production server. Runs in the override context \"debug_run_python\", so resource limits with", "Http404 c = {} c['code'] = '' c['results'] = None if request.method ==", "CODE_JAIL['limits'] \"\"\" if not request.user.is_staff: raise Http404 c = {} c['code'] = ''", "\"\"\"A page that shows what parameters were on the URL and post.\"\"\" html_list", "@login_required @ensure_csrf_cookie def run_python(request): \"\"\" A page to allow testing the Python sandbox", ") except Exception: # pylint: disable=broad-except c['results'] = traceback.format_exc() else: c['results'] = pprint.pformat(g)", "override context \"debug_run_python\", so resource limits with come first from: CODE_JAIL['limit_overrides']['debug_run_python'] and then", "in sorted(request.GET.items()): html_list.append(escape(f\"GET {name}: {value!r}\")) for name, value in sorted(request.POST.items()): html_list.append(escape(f\"POST {name}: {value!r}\"))", "{name}: {value!r}\")) for name, value in sorted(request.POST.items()): html_list.append(escape(f\"POST {name}: {value!r}\")) return HttpResponse(\"\\n\".join(HTML(\"<p>{}</p>\").format(h) for", "to allow testing the Python sandbox on a production server. Runs in the", "g = {} try: safe_exec( code=py_code, globals_dict=g, slug=\"debug_run_python\", limit_overrides_context=\"debug_run_python\", ) except Exception: #", "request.POST.get('code') g = {} try: safe_exec( code=py_code, globals_dict=g, slug=\"debug_run_python\", limit_overrides_context=\"debug_run_python\", ) except Exception:", "\"\"\" A page to allow testing the Python sandbox on a production server.", "allow testing the Python sandbox on a production server. Runs in the override", "the Python sandbox on a production server. Runs in the override context \"debug_run_python\",", "for debugging and diagnostics\"\"\" import pprint import traceback from codejail.safe_exec import safe_exec from", "django.utils.html import escape from django.views.decorators.csrf import ensure_csrf_cookie from common.djangoapps.edxmako.shortcuts import render_to_response from openedx.core.djangolib.markup", "{value!r}\")) for name, value in sorted(request.POST.items()): html_list.append(escape(f\"POST {name}: {value!r}\")) return HttpResponse(\"\\n\".join(HTML(\"<p>{}</p>\").format(h) for h", "disable=broad-except c['results'] = traceback.format_exc() else: c['results'] = pprint.pformat(g) return render_to_response(\"debug/run_python_form.html\", c) @login_required def", "from: CODE_JAIL['limit_overrides']['debug_run_python'] and then from: CODE_JAIL['limits'] \"\"\" if not request.user.is_staff: raise Http404 c", "in the override context \"debug_run_python\", so resource limits with come first from: CODE_JAIL['limit_overrides']['debug_run_python']", "{} c['code'] = '' c['results'] = None if request.method == 'POST': py_code =", "py_code = c['code'] = request.POST.get('code') g = {} try: safe_exec( code=py_code, globals_dict=g, slug=\"debug_run_python\",", "diagnostics\"\"\" import pprint import traceback from codejail.safe_exec import safe_exec from django.contrib.auth.decorators import login_required", "globals_dict=g, slug=\"debug_run_python\", limit_overrides_context=\"debug_run_python\", ) except Exception: # pylint: disable=broad-except c['results'] = traceback.format_exc() else:", "testing the Python sandbox on a production server. Runs in the override context", "context \"debug_run_python\", so resource limits with come first from: CODE_JAIL['limit_overrides']['debug_run_python'] and then from:", "limit_overrides_context=\"debug_run_python\", ) except Exception: # pylint: disable=broad-except c['results'] = traceback.format_exc() else: c['results'] =", "the URL and post.\"\"\" html_list = [] for name, value in sorted(request.GET.items()): html_list.append(escape(f\"GET", "def show_parameters(request): \"\"\"A page that shows what parameters were on the URL and", "not request.user.is_staff: raise Http404 c = {} c['code'] = '' c['results'] = None", "render_to_response from openedx.core.djangolib.markup import HTML @login_required @ensure_csrf_cookie def run_python(request): \"\"\" A page to", "django.views.decorators.csrf import ensure_csrf_cookie from common.djangoapps.edxmako.shortcuts import render_to_response from openedx.core.djangolib.markup import HTML @login_required @ensure_csrf_cookie", "else: c['results'] = pprint.pformat(g) return render_to_response(\"debug/run_python_form.html\", c) @login_required def show_parameters(request): \"\"\"A page that", "for name, value in sorted(request.GET.items()): html_list.append(escape(f\"GET {name}: {value!r}\")) for name, value in sorted(request.POST.items()):", "resource limits with come first from: CODE_JAIL['limit_overrides']['debug_run_python'] and then from: CODE_JAIL['limits'] \"\"\" if", "'' c['results'] = None if request.method == 'POST': py_code = c['code'] = request.POST.get('code')", "with come first from: CODE_JAIL['limit_overrides']['debug_run_python'] and then from: CODE_JAIL['limits'] \"\"\" if not request.user.is_staff:", "html_list = [] for name, value in sorted(request.GET.items()): html_list.append(escape(f\"GET {name}: {value!r}\")) for name,", "code=py_code, globals_dict=g, slug=\"debug_run_python\", limit_overrides_context=\"debug_run_python\", ) except Exception: # pylint: disable=broad-except c['results'] = traceback.format_exc()", "import pprint import traceback from codejail.safe_exec import safe_exec from django.contrib.auth.decorators import login_required from", "safe_exec from django.contrib.auth.decorators import login_required from django.http import Http404, HttpResponse from django.utils.html import", "{} try: safe_exec( code=py_code, globals_dict=g, slug=\"debug_run_python\", limit_overrides_context=\"debug_run_python\", ) except Exception: # pylint: disable=broad-except", "[] for name, value in sorted(request.GET.items()): html_list.append(escape(f\"GET {name}: {value!r}\")) for name, value in", "shows what parameters were on the URL and post.\"\"\" html_list = [] for", "what parameters were on the URL and post.\"\"\" html_list = [] for name,", "None if request.method == 'POST': py_code = c['code'] = request.POST.get('code') g = {}", "import escape from django.views.decorators.csrf import ensure_csrf_cookie from common.djangoapps.edxmako.shortcuts import render_to_response from openedx.core.djangolib.markup import", "HttpResponse from django.utils.html import escape from django.views.decorators.csrf import ensure_csrf_cookie from common.djangoapps.edxmako.shortcuts import render_to_response", "render_to_response(\"debug/run_python_form.html\", c) @login_required def show_parameters(request): \"\"\"A page that shows what parameters were on", "and then from: CODE_JAIL['limits'] \"\"\" if not request.user.is_staff: raise Http404 c = {}", "pprint.pformat(g) return render_to_response(\"debug/run_python_form.html\", c) @login_required def show_parameters(request): \"\"\"A page that shows what parameters", "@login_required def show_parameters(request): \"\"\"A page that shows what parameters were on the URL", "\"\"\" if not request.user.is_staff: raise Http404 c = {} c['code'] = '' c['results']", "for name, value in sorted(request.POST.items()): html_list.append(escape(f\"POST {name}: {value!r}\")) return HttpResponse(\"\\n\".join(HTML(\"<p>{}</p>\").format(h) for h in", "limits with come first from: CODE_JAIL['limit_overrides']['debug_run_python'] and then from: CODE_JAIL['limits'] \"\"\" if not", "@ensure_csrf_cookie def run_python(request): \"\"\" A page to allow testing the Python sandbox on", "Http404, HttpResponse from django.utils.html import escape from django.views.decorators.csrf import ensure_csrf_cookie from common.djangoapps.edxmako.shortcuts import", "come first from: CODE_JAIL['limit_overrides']['debug_run_python'] and then from: CODE_JAIL['limits'] \"\"\" if not request.user.is_staff: raise", "django.contrib.auth.decorators import login_required from django.http import Http404, HttpResponse from django.utils.html import escape from", "= request.POST.get('code') g = {} try: safe_exec( code=py_code, globals_dict=g, slug=\"debug_run_python\", limit_overrides_context=\"debug_run_python\", ) except", "traceback from codejail.safe_exec import safe_exec from django.contrib.auth.decorators import login_required from django.http import Http404,", "request.method == 'POST': py_code = c['code'] = request.POST.get('code') g = {} try: safe_exec(", "production server. Runs in the override context \"debug_run_python\", so resource limits with come", "show_parameters(request): \"\"\"A page that shows what parameters were on the URL and post.\"\"\"", "request.user.is_staff: raise Http404 c = {} c['code'] = '' c['results'] = None if", "try: safe_exec( code=py_code, globals_dict=g, slug=\"debug_run_python\", limit_overrides_context=\"debug_run_python\", ) except Exception: # pylint: disable=broad-except c['results']", "parameters were on the URL and post.\"\"\" html_list = [] for name, value", "import login_required from django.http import Http404, HttpResponse from django.utils.html import escape from django.views.decorators.csrf", "c['results'] = None if request.method == 'POST': py_code = c['code'] = request.POST.get('code') g", "from django.contrib.auth.decorators import login_required from django.http import Http404, HttpResponse from django.utils.html import escape", "page to allow testing the Python sandbox on a production server. Runs in" ]
[ "1, j), (i - 1, j), (i, j + 1), (i, j -", "0 <= ni < len(grid) and 0 <= nj < len(grid[0]) and grid[ni][nj]", "def closedIsland(self, grid: List[List[int]]) -> int: res = 0 for i in range(len(grid)):", "in [(i + 1, j), (i - 1, j), (i, j + 1),", "self._dfs(grid, i, j): res += 1 return res def _dfs(self, grid, i, j):", "range(len(grid[0])): if grid[i][j] == 0: grid[i][j] = 1 if self._dfs(grid, i, j): res", "-> int: res = 0 for i in range(len(grid)): for j in range(len(grid[0])):", "if 0 <= ni < len(grid) and 0 <= nj < len(grid[0]) and", "+ 1, j), (i - 1, j), (i, j + 1), (i, j", "ni, nj in [(i + 1, j), (i - 1, j), (i, j", "< len(grid) - 1 and 0 < j < len(grid[0]) - 1 for", "< len(grid) and 0 <= nj < len(grid[0]) and grid[ni][nj] == 0: grid[ni][nj]", "len(grid) - 1 and 0 < j < len(grid[0]) - 1 for ni,", "- 1)]: if 0 <= ni < len(grid) and 0 <= nj <", "0: grid[ni][nj] = 1 closed = self._dfs(grid, ni, nj) and closed return closed", "- 1 and 0 < j < len(grid[0]) - 1 for ni, nj", "ni < len(grid) and 0 <= nj < len(grid[0]) and grid[ni][nj] == 0:", "res += 1 return res def _dfs(self, grid, i, j): closed = 0", "- 1 for ni, nj in [(i + 1, j), (i - 1,", "for ni, nj in [(i + 1, j), (i - 1, j), (i,", "grid, i, j): closed = 0 < i < len(grid) - 1 and", "= 1 if self._dfs(grid, i, j): res += 1 return res def _dfs(self,", "nj in [(i + 1, j), (i - 1, j), (i, j +", "1, j), (i, j + 1), (i, j - 1)]: if 0 <=", "(i - 1, j), (i, j + 1), (i, j - 1)]: if", "j < len(grid[0]) - 1 for ni, nj in [(i + 1, j),", "if self._dfs(grid, i, j): res += 1 return res def _dfs(self, grid, i,", "Solution: def closedIsland(self, grid: List[List[int]]) -> int: res = 0 for i in", "0 < j < len(grid[0]) - 1 for ni, nj in [(i +", "j), (i - 1, j), (i, j + 1), (i, j - 1)]:", "res def _dfs(self, grid, i, j): closed = 0 < i < len(grid)", "<filename>solutions/1254_number_of_closed_islands.py<gh_stars>0 class Solution: def closedIsland(self, grid: List[List[int]]) -> int: res = 0 for", "i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 0: grid[i][j] =", "== 0: grid[ni][nj] = 1 closed = self._dfs(grid, ni, nj) and closed return", "grid[i][j] = 1 if self._dfs(grid, i, j): res += 1 return res def", "_dfs(self, grid, i, j): closed = 0 < i < len(grid) - 1", "range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 0: grid[i][j] = 1 if", "j): closed = 0 < i < len(grid) - 1 and 0 <", "int: res = 0 for i in range(len(grid)): for j in range(len(grid[0])): if", "return res def _dfs(self, grid, i, j): closed = 0 < i <", "[(i + 1, j), (i - 1, j), (i, j + 1), (i,", "len(grid[0]) - 1 for ni, nj in [(i + 1, j), (i -", "List[List[int]]) -> int: res = 0 for i in range(len(grid)): for j in", "and grid[ni][nj] == 0: grid[ni][nj] = 1 closed = self._dfs(grid, ni, nj) and", "closedIsland(self, grid: List[List[int]]) -> int: res = 0 for i in range(len(grid)): for", "and 0 < j < len(grid[0]) - 1 for ni, nj in [(i", "+ 1), (i, j - 1)]: if 0 <= ni < len(grid) and", "grid[i][j] == 0: grid[i][j] = 1 if self._dfs(grid, i, j): res += 1", "< j < len(grid[0]) - 1 for ni, nj in [(i + 1,", "if grid[i][j] == 0: grid[i][j] = 1 if self._dfs(grid, i, j): res +=", "1 and 0 < j < len(grid[0]) - 1 for ni, nj in", "< len(grid[0]) - 1 for ni, nj in [(i + 1, j), (i", "<= nj < len(grid[0]) and grid[ni][nj] == 0: grid[ni][nj] = 1 closed =", "< len(grid[0]) and grid[ni][nj] == 0: grid[ni][nj] = 1 closed = self._dfs(grid, ni,", "<= ni < len(grid) and 0 <= nj < len(grid[0]) and grid[ni][nj] ==", "def _dfs(self, grid, i, j): closed = 0 < i < len(grid) -", "< i < len(grid) - 1 and 0 < j < len(grid[0]) -", "for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 0: grid[i][j]", "j): res += 1 return res def _dfs(self, grid, i, j): closed =", "(i, j - 1)]: if 0 <= ni < len(grid) and 0 <=", "1), (i, j - 1)]: if 0 <= ni < len(grid) and 0", "1)]: if 0 <= ni < len(grid) and 0 <= nj < len(grid[0])", "len(grid[0]) and grid[ni][nj] == 0: grid[ni][nj] = 1 closed = self._dfs(grid, ni, nj)", "1 if self._dfs(grid, i, j): res += 1 return res def _dfs(self, grid,", "closed = 0 < i < len(grid) - 1 and 0 < j", "0 <= nj < len(grid[0]) and grid[ni][nj] == 0: grid[ni][nj] = 1 closed", "- 1, j), (i, j + 1), (i, j - 1)]: if 0", "len(grid) and 0 <= nj < len(grid[0]) and grid[ni][nj] == 0: grid[ni][nj] =", "== 0: grid[i][j] = 1 if self._dfs(grid, i, j): res += 1 return", "0 < i < len(grid) - 1 and 0 < j < len(grid[0])", "= 0 < i < len(grid) - 1 and 0 < j <", "= 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] ==", "and 0 <= nj < len(grid[0]) and grid[ni][nj] == 0: grid[ni][nj] = 1", "j), (i, j + 1), (i, j - 1)]: if 0 <= ni", "grid[ni][nj] == 0: grid[ni][nj] = 1 closed = self._dfs(grid, ni, nj) and closed", "j + 1), (i, j - 1)]: if 0 <= ni < len(grid)", "j in range(len(grid[0])): if grid[i][j] == 0: grid[i][j] = 1 if self._dfs(grid, i,", "nj < len(grid[0]) and grid[ni][nj] == 0: grid[ni][nj] = 1 closed = self._dfs(grid,", "0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 0:", "i, j): closed = 0 < i < len(grid) - 1 and 0", "j - 1)]: if 0 <= ni < len(grid) and 0 <= nj", "i < len(grid) - 1 and 0 < j < len(grid[0]) - 1", "for j in range(len(grid[0])): if grid[i][j] == 0: grid[i][j] = 1 if self._dfs(grid,", "1 for ni, nj in [(i + 1, j), (i - 1, j),", "grid: List[List[int]]) -> int: res = 0 for i in range(len(grid)): for j", "res = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j]", "in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 0: grid[i][j] = 1", "0: grid[i][j] = 1 if self._dfs(grid, i, j): res += 1 return res", "+= 1 return res def _dfs(self, grid, i, j): closed = 0 <", "class Solution: def closedIsland(self, grid: List[List[int]]) -> int: res = 0 for i", "i, j): res += 1 return res def _dfs(self, grid, i, j): closed", "in range(len(grid[0])): if grid[i][j] == 0: grid[i][j] = 1 if self._dfs(grid, i, j):", "(i, j + 1), (i, j - 1)]: if 0 <= ni <", "1 return res def _dfs(self, grid, i, j): closed = 0 < i" ]
[ "graph_largest_component(G: gt.Graph, directed: bool = False) -> NodeDataFrame: expect_nodes(G) largest_comp = gt.label_largest_component(G, directed=directed)", "gt from .nodedataframe import NodeDataFrame from .context import expect_nodes def graph_component_count(G: gt.Graph, directed:", "-> NodeDataFrame: expect_nodes(G) counted_comp, _ = gt.label_components(G, directed=directed) return NodeDataFrame({\"cc\": list(counted_comp)})[\"cc\"] def graph_largest_component(G:", "return NodeDataFrame({\"cc\": list(counted_comp)})[\"cc\"] def graph_largest_component(G: gt.Graph, directed: bool = False) -> NodeDataFrame: expect_nodes(G)", "bool = False) -> NodeDataFrame: expect_nodes(G) largest_comp = gt.label_largest_component(G, directed=directed) return NodeDataFrame({\"lc\": list(largest_comp)})[\"lc\"]", "counted_comp, _ = gt.label_components(G, directed=directed) return NodeDataFrame({\"cc\": list(counted_comp)})[\"cc\"] def graph_largest_component(G: gt.Graph, directed: bool", "from .nodedataframe import NodeDataFrame from .context import expect_nodes def graph_component_count(G: gt.Graph, directed: bool", "expect_nodes def graph_component_count(G: gt.Graph, directed: bool = False) -> NodeDataFrame: expect_nodes(G) counted_comp, _", "graph_component_count(G: gt.Graph, directed: bool = False) -> NodeDataFrame: expect_nodes(G) counted_comp, _ = gt.label_components(G,", "bool = False) -> NodeDataFrame: expect_nodes(G) counted_comp, _ = gt.label_components(G, directed=directed) return NodeDataFrame({\"cc\":", "expect_nodes(G) counted_comp, _ = gt.label_components(G, directed=directed) return NodeDataFrame({\"cc\": list(counted_comp)})[\"cc\"] def graph_largest_component(G: gt.Graph, directed:", "graph\"\"\" import graph_tool.all as gt from .nodedataframe import NodeDataFrame from .context import expect_nodes", ".nodedataframe import NodeDataFrame from .context import expect_nodes def graph_component_count(G: gt.Graph, directed: bool =", "import NodeDataFrame from .context import expect_nodes def graph_component_count(G: gt.Graph, directed: bool = False)", "def graph_component_count(G: gt.Graph, directed: bool = False) -> NodeDataFrame: expect_nodes(G) counted_comp, _ =", "directed=directed) return NodeDataFrame({\"cc\": list(counted_comp)})[\"cc\"] def graph_largest_component(G: gt.Graph, directed: bool = False) -> NodeDataFrame:", "= False) -> NodeDataFrame: expect_nodes(G) counted_comp, _ = gt.label_components(G, directed=directed) return NodeDataFrame({\"cc\": list(counted_comp)})[\"cc\"]", ".context import expect_nodes def graph_component_count(G: gt.Graph, directed: bool = False) -> NodeDataFrame: expect_nodes(G)", "gt.Graph, directed: bool = False) -> NodeDataFrame: expect_nodes(G) largest_comp = gt.label_largest_component(G, directed=directed) return", "on graph\"\"\" import graph_tool.all as gt from .nodedataframe import NodeDataFrame from .context import", "gt.Graph, directed: bool = False) -> NodeDataFrame: expect_nodes(G) counted_comp, _ = gt.label_components(G, directed=directed)", "= gt.label_components(G, directed=directed) return NodeDataFrame({\"cc\": list(counted_comp)})[\"cc\"] def graph_largest_component(G: gt.Graph, directed: bool = False)", "\"\"\"Calculate metrics on graph\"\"\" import graph_tool.all as gt from .nodedataframe import NodeDataFrame from", "def graph_largest_component(G: gt.Graph, directed: bool = False) -> NodeDataFrame: expect_nodes(G) largest_comp = gt.label_largest_component(G,", "list(counted_comp)})[\"cc\"] def graph_largest_component(G: gt.Graph, directed: bool = False) -> NodeDataFrame: expect_nodes(G) largest_comp =", "NodeDataFrame({\"cc\": list(counted_comp)})[\"cc\"] def graph_largest_component(G: gt.Graph, directed: bool = False) -> NodeDataFrame: expect_nodes(G) largest_comp", "NodeDataFrame: expect_nodes(G) counted_comp, _ = gt.label_components(G, directed=directed) return NodeDataFrame({\"cc\": list(counted_comp)})[\"cc\"] def graph_largest_component(G: gt.Graph,", "from .context import expect_nodes def graph_component_count(G: gt.Graph, directed: bool = False) -> NodeDataFrame:", "False) -> NodeDataFrame: expect_nodes(G) counted_comp, _ = gt.label_components(G, directed=directed) return NodeDataFrame({\"cc\": list(counted_comp)})[\"cc\"] def", "gt.label_components(G, directed=directed) return NodeDataFrame({\"cc\": list(counted_comp)})[\"cc\"] def graph_largest_component(G: gt.Graph, directed: bool = False) ->", "NodeDataFrame from .context import expect_nodes def graph_component_count(G: gt.Graph, directed: bool = False) ->", "import graph_tool.all as gt from .nodedataframe import NodeDataFrame from .context import expect_nodes def", "as gt from .nodedataframe import NodeDataFrame from .context import expect_nodes def graph_component_count(G: gt.Graph,", "directed: bool = False) -> NodeDataFrame: expect_nodes(G) counted_comp, _ = gt.label_components(G, directed=directed) return", "import expect_nodes def graph_component_count(G: gt.Graph, directed: bool = False) -> NodeDataFrame: expect_nodes(G) counted_comp,", "metrics on graph\"\"\" import graph_tool.all as gt from .nodedataframe import NodeDataFrame from .context", "graph_tool.all as gt from .nodedataframe import NodeDataFrame from .context import expect_nodes def graph_component_count(G:", "directed: bool = False) -> NodeDataFrame: expect_nodes(G) largest_comp = gt.label_largest_component(G, directed=directed) return NodeDataFrame({\"lc\":", "_ = gt.label_components(G, directed=directed) return NodeDataFrame({\"cc\": list(counted_comp)})[\"cc\"] def graph_largest_component(G: gt.Graph, directed: bool =" ]
[ "argument will always be the right operand. .. caution:: Since the rhs is", "and delegate to it if it has defined the proper protocol: - ``__lazyboolnot__(self)``", "logical operators aware of laziness. \"\"\" def visit_BoolOp(self, node: BoolOp) -> Union[UnaryOp, Call]:", "typing import Union __all__ = ['__lazybooland__', '__lazyboolor__', '__lazyboolnot__'] class LazyBoolsTransformer(NodeTransformer): \"\"\" Make logical", "= Call( func=Name(id='__lazyboolnot__', ctx=Load()), args=[node.operand], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def __lazybooland__(expr,", "Union __all__ = ['__lazybooland__', '__lazyboolor__', '__lazyboolnot__'] class LazyBoolsTransformer(NodeTransformer): \"\"\" Make logical operators aware", "to overload the boolean operators (``not``, ``and``, ``or``) since they have short-circuiting semantics", "if not isinstance(node.op, Not): return node delegate = Call( func=Name(id='__lazyboolnot__', ctx=Load()), args=[node.operand], keywords=[])", "result return expr or deferred() def __lazyboolnot__(expr): if hasattr(expr, '__lazyboolnot__'): result = expr.__lazynot__()", "fix_missing_locations(delegate) return delegate def visit_UnaryOp(self, node: UnaryOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if not", "def __lazyboolor__(expr, deferred): if hasattr(expr, '__lazyboolor__'): result = expr.__lazyor__(deferred) if result is not", "is not NotImplemented: return result return expr or deferred() def __lazyboolnot__(expr): if hasattr(expr,", "protocol: - ``__lazyboolnot__(self)`` - ``__lazybooland__(self, rhs_callable)`` - ``__lazyboolor__(self, rhs_callable)`` .. note:: These operators", "= expr.__lazyor__(deferred) if result is not NotImplemented: return result return expr or deferred()", "converts the above example to: >>> OR(AND(cmd, lambda: ok), lambda: fail) Where ``OR``", "opaque inside the lambda, we can't check it until it resolves. \"\"\" from", "result = expr.__lazynot__() if result is not NotImplemented: return result return not expr", "OR(AND(cmd, lambda: ok), lambda: fail) Where ``OR`` and ``AND`` are runtime helpers that", "we can't check it until it resolves. \"\"\" from ast import NodeTransformer, copy_location,", "delegate def __lazybooland__(expr, deferred): if hasattr(expr, '__lazybooland__'): result = expr.__lazyand__(deferred) if result is", ") ''') node = parser(node) print(dump(node)) co_code = compile(node, '<string>', 'exec') eval(co_code, globals())", "self.generic_visit(node) if not isinstance(node.op, Not): return node delegate = Call( func=Name(id='__lazyboolnot__', ctx=Load()), args=[node.operand],", "it resolves. \"\"\" from ast import NodeTransformer, copy_location, fix_missing_locations, AST, \\ BoolOp, UnaryOp,", "the rhs is opaque inside the lambda, we can't check it until it", "delegate = Call( func=Name(id=runtime, ctx=Load()), args=[ lhs, # Make the rhs a deferred", "scripts. We would like to keep that expression lazily evaluated but is not", "fix_missing_locations, AST, \\ BoolOp, UnaryOp, And, Or, Not, Call, Lambda, arguments, Name, Load", "ctx=Load()), args=[node.operand], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def __lazybooland__(expr, deferred): if hasattr(expr,", "cmd and ok or not fail ) ''') node = parser(node) print(dump(node)) co_code", "like to keep that expression lazily evaluated but is not possible since the", "func=Name(id=runtime, ctx=Load()), args=[ lhs, # Make the rhs a deferred computation by wrapping", "similar constructs, which are quite common in shell scripts. We would like to", "wrapping with a lambda Lambda( args=arguments(args=[], kwonlyargs=[], kw_defaults=[], defaults=[]), body=rhs) ], keywords=[]) copy_location(delegate,", "Union[UnaryOp, Call]: self.generic_visit(node) if isinstance(node.op, And): runtime = '__lazybooland__' elif isinstance(node.op, Or): runtime", "Call]: self.generic_visit(node) if isinstance(node.op, And): runtime = '__lazybooland__' elif isinstance(node.op, Or): runtime =", "lambda: ok), lambda: fail) Where ``OR`` and ``AND`` are runtime helpers that will", "it's not possible to overload the boolean operators (``not``, ``and``, ``or``) since they", "proper protocol: - ``__lazyboolnot__(self)`` - ``__lazybooland__(self, rhs_callable)`` - ``__lazyboolor__(self, rhs_callable)`` .. note:: These", "Call]: self.generic_visit(node) if not isinstance(node.op, Not): return node delegate = Call( func=Name(id='__lazyboolnot__', ctx=Load()),", "AST) -> AST: return LazyBoolsTransformer().visit(node) from ast import parse, dump # print(dump(parse('lambda: 10')))", "parse, dump # print(dump(parse('lambda: 10'))) cmd = 0 ok = 'ok' fail =", "``__lazybooland__(self, rhs_callable)`` - ``__lazyboolor__(self, rhs_callable)`` .. note:: These operators do not have a", "``AND`` are runtime helpers that will inspect the value and delegate to it", "hasattr(expr, '__lazyboolor__'): result = expr.__lazyor__(deferred) if result is not NotImplemented: return result return", "fail ) ''') node = parser(node) print(dump(node)) co_code = compile(node, '<string>', 'exec') eval(co_code,", "it should go with the ``and`` or the ``or`` branch. This tranformation converts", "``__lazyboolnot__(self)`` - ``__lazybooland__(self, rhs_callable)`` - ``__lazyboolor__(self, rhs_callable)`` .. note:: These operators do not", "not expr def parser(node: AST) -> AST: return LazyBoolsTransformer().visit(node) from ast import parse,", "The problem manifests when trying to use a ``cmd and ok or fail``", "Call( func=Name(id='__lazyboolnot__', ctx=Load()), args=[node.operand], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def __lazybooland__(expr, deferred):", "body=rhs) ], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def visit_UnaryOp(self, node: UnaryOp) ->", "= '__lazyboolor__' else: return node lhs, rhs = node.values delegate = Call( func=Name(id=runtime,", "return delegate def visit_UnaryOp(self, node: UnaryOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if not isinstance(node.op,", "def visit_UnaryOp(self, node: UnaryOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if not isinstance(node.op, Not): return", "ok), lambda: fail) Where ``OR`` and ``AND`` are runtime helpers that will inspect", "and ok or fail`` or similar constructs, which are quite common in shell", "``or`` branch. This tranformation converts the above example to: >>> OR(AND(cmd, lambda: ok),", "to keep that expression lazily evaluated but is not possible since the Python", "if hasattr(expr, '__lazybooland__'): result = expr.__lazyand__(deferred) if result is not NotImplemented: return result", "Name, Load from typing import Union __all__ = ['__lazybooland__', '__lazyboolor__', '__lazyboolnot__'] class LazyBoolsTransformer(NodeTransformer):", ".. note:: These operators do not have a reverse, the argument will always", "return node lhs, rhs = node.values delegate = Call( func=Name(id=runtime, ctx=Load()), args=[ lhs,", "'__lazybooland__' elif isinstance(node.op, Or): runtime = '__lazyboolor__' else: return node lhs, rhs =", "but is not possible since the Python interpreter will try to resolve it", "Or): runtime = '__lazyboolor__' else: return node lhs, rhs = node.values delegate =", "deferred computation by wrapping with a lambda Lambda( args=arguments(args=[], kwonlyargs=[], kw_defaults=[], defaults=[]), body=rhs)", "NotImplemented: return result return not expr def parser(node: AST) -> AST: return LazyBoolsTransformer().visit(node)", "Python it's not possible to overload the boolean operators (``not``, ``and``, ``or``) since", "resolve it immediately, trigering the evaluation of ``cmd`` to know if it should", "possible since the Python interpreter will try to resolve it immediately, trigering the", "runtime = '__lazyboolor__' else: return node lhs, rhs = node.values delegate = Call(", "import NodeTransformer, copy_location, fix_missing_locations, AST, \\ BoolOp, UnaryOp, And, Or, Not, Call, Lambda,", "kw_defaults=[], defaults=[]), body=rhs) ], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def visit_UnaryOp(self, node:", "parser(node: AST) -> AST: return LazyBoolsTransformer().visit(node) from ast import parse, dump # print(dump(parse('lambda:", "have short-circuiting semantics (PEP-532 is deferred right now). The problem manifests when trying", "right operand. .. caution:: Since the rhs is opaque inside the lambda, we", "branch. This tranformation converts the above example to: >>> OR(AND(cmd, lambda: ok), lambda:", "boolean operators (``not``, ``and``, ``or``) since they have short-circuiting semantics (PEP-532 is deferred", "cmd = 0 ok = 'ok' fail = 'fail' node = parse(r''' print(", "__lazyboolor__(expr, deferred): if hasattr(expr, '__lazyboolor__'): result = expr.__lazyor__(deferred) if result is not NotImplemented:", "= 'fail' node = parse(r''' print( cmd and ok or not fail )", "problem manifests when trying to use a ``cmd and ok or fail`` or", "BoolOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if isinstance(node.op, And): runtime = '__lazybooland__' elif isinstance(node.op,", "UnaryOp, And, Or, Not, Call, Lambda, arguments, Name, Load from typing import Union", "elif isinstance(node.op, Or): runtime = '__lazyboolor__' else: return node lhs, rhs = node.values", "go with the ``and`` or the ``or`` branch. This tranformation converts the above", "evaluated but is not possible since the Python interpreter will try to resolve", "return node delegate = Call( func=Name(id='__lazyboolnot__', ctx=Load()), args=[node.operand], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return", "if hasattr(expr, '__lazyboolor__'): result = expr.__lazyor__(deferred) if result is not NotImplemented: return result", "is not possible since the Python interpreter will try to resolve it immediately,", "Make the rhs a deferred computation by wrapping with a lambda Lambda( args=arguments(args=[],", "10'))) cmd = 0 ok = 'ok' fail = 'fail' node = parse(r'''", "since they have short-circuiting semantics (PEP-532 is deferred right now). The problem manifests", "return not expr def parser(node: AST) -> AST: return LazyBoolsTransformer().visit(node) from ast import", "copy_location(delegate, node) fix_missing_locations(delegate) return delegate def visit_UnaryOp(self, node: UnaryOp) -> Union[UnaryOp, Call]: self.generic_visit(node)", "return expr or deferred() def __lazyboolnot__(expr): if hasattr(expr, '__lazyboolnot__'): result = expr.__lazynot__() if", "it until it resolves. \"\"\" from ast import NodeTransformer, copy_location, fix_missing_locations, AST, \\", "'fail' node = parse(r''' print( cmd and ok or not fail ) ''')", "LazyBoolsTransformer(NodeTransformer): \"\"\" Make logical operators aware of laziness. \"\"\" def visit_BoolOp(self, node: BoolOp)", "quite common in shell scripts. We would like to keep that expression lazily", "when trying to use a ``cmd and ok or fail`` or similar constructs,", "will try to resolve it immediately, trigering the evaluation of ``cmd`` to know", "can't check it until it resolves. \"\"\" from ast import NodeTransformer, copy_location, fix_missing_locations,", "isinstance(node.op, Or): runtime = '__lazyboolor__' else: return node lhs, rhs = node.values delegate", "We would like to keep that expression lazily evaluated but is not possible", "class LazyBoolsTransformer(NodeTransformer): \"\"\" Make logical operators aware of laziness. \"\"\" def visit_BoolOp(self, node:", "def __lazyboolnot__(expr): if hasattr(expr, '__lazyboolnot__'): result = expr.__lazynot__() if result is not NotImplemented:", "result return expr and deferred() def __lazyboolor__(expr, deferred): if hasattr(expr, '__lazyboolor__'): result =", "value and delegate to it if it has defined the proper protocol: -", "or fail`` or similar constructs, which are quite common in shell scripts. We", "ast import NodeTransformer, copy_location, fix_missing_locations, AST, \\ BoolOp, UnaryOp, And, Or, Not, Call,", "kwonlyargs=[], kw_defaults=[], defaults=[]), body=rhs) ], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def visit_UnaryOp(self,", "'__lazybooland__'): result = expr.__lazyand__(deferred) if result is not NotImplemented: return result return expr", "-> Union[UnaryOp, Call]: self.generic_visit(node) if isinstance(node.op, And): runtime = '__lazybooland__' elif isinstance(node.op, Or):", "computation by wrapping with a lambda Lambda( args=arguments(args=[], kwonlyargs=[], kw_defaults=[], defaults=[]), body=rhs) ],", "that will inspect the value and delegate to it if it has defined", "expr def parser(node: AST) -> AST: return LazyBoolsTransformer().visit(node) from ast import parse, dump", "``and``, ``or``) since they have short-circuiting semantics (PEP-532 is deferred right now). The", "not possible since the Python interpreter will try to resolve it immediately, trigering", "from typing import Union __all__ = ['__lazybooland__', '__lazyboolor__', '__lazyboolnot__'] class LazyBoolsTransformer(NodeTransformer): \"\"\" Make", "node = parse(r''' print( cmd and ok or not fail ) ''') node", "to it if it has defined the proper protocol: - ``__lazyboolnot__(self)`` - ``__lazybooland__(self,", "expression lazily evaluated but is not possible since the Python interpreter will try", "Not): return node delegate = Call( func=Name(id='__lazyboolnot__', ctx=Load()), args=[node.operand], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate)", "return result return not expr def parser(node: AST) -> AST: return LazyBoolsTransformer().visit(node) from", "of ``cmd`` to know if it should go with the ``and`` or the", "of laziness. \"\"\" def visit_BoolOp(self, node: BoolOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if isinstance(node.op,", "args=[ lhs, # Make the rhs a deferred computation by wrapping with a", "__lazybooland__(expr, deferred): if hasattr(expr, '__lazybooland__'): result = expr.__lazyand__(deferred) if result is not NotImplemented:", "or deferred() def __lazyboolnot__(expr): if hasattr(expr, '__lazyboolnot__'): result = expr.__lazynot__() if result is", "- ``__lazyboolor__(self, rhs_callable)`` .. note:: These operators do not have a reverse, the", "'__lazyboolor__'): result = expr.__lazyor__(deferred) if result is not NotImplemented: return result return expr", "rhs a deferred computation by wrapping with a lambda Lambda( args=arguments(args=[], kwonlyargs=[], kw_defaults=[],", "args=[node.operand], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def __lazybooland__(expr, deferred): if hasattr(expr, '__lazybooland__'):", "constructs, which are quite common in shell scripts. We would like to keep", "return expr and deferred() def __lazyboolor__(expr, deferred): if hasattr(expr, '__lazyboolor__'): result = expr.__lazyor__(deferred)", "is not NotImplemented: return result return expr and deferred() def __lazyboolor__(expr, deferred): if", "if it should go with the ``and`` or the ``or`` branch. This tranformation", "'__lazyboolnot__'): result = expr.__lazynot__() if result is not NotImplemented: return result return not", "they have short-circuiting semantics (PEP-532 is deferred right now). The problem manifests when", "rhs = node.values delegate = Call( func=Name(id=runtime, ctx=Load()), args=[ lhs, # Make the", "node: UnaryOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if not isinstance(node.op, Not): return node delegate", "not isinstance(node.op, Not): return node delegate = Call( func=Name(id='__lazyboolnot__', ctx=Load()), args=[node.operand], keywords=[]) copy_location(delegate,", "deferred() def __lazyboolor__(expr, deferred): if hasattr(expr, '__lazyboolor__'): result = expr.__lazyor__(deferred) if result is", "reverse, the argument will always be the right operand. .. caution:: Since the", "ast import parse, dump # print(dump(parse('lambda: 10'))) cmd = 0 ok = 'ok'", "\\ BoolOp, UnaryOp, And, Or, Not, Call, Lambda, arguments, Name, Load from typing", "ok or not fail ) ''') node = parser(node) print(dump(node)) co_code = compile(node,", "fail) Where ``OR`` and ``AND`` are runtime helpers that will inspect the value", "visit_BoolOp(self, node: BoolOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if isinstance(node.op, And): runtime = '__lazybooland__'", "hasattr(expr, '__lazybooland__'): result = expr.__lazyand__(deferred) if result is not NotImplemented: return result return", "right now). The problem manifests when trying to use a ``cmd and ok", "evaluation of ``cmd`` to know if it should go with the ``and`` or", "__lazyboolnot__(expr): if hasattr(expr, '__lazyboolnot__'): result = expr.__lazynot__() if result is not NotImplemented: return", "since the Python interpreter will try to resolve it immediately, trigering the evaluation", "- ``__lazyboolnot__(self)`` - ``__lazybooland__(self, rhs_callable)`` - ``__lazyboolor__(self, rhs_callable)`` .. note:: These operators do", "inspect the value and delegate to it if it has defined the proper", "Call( func=Name(id=runtime, ctx=Load()), args=[ lhs, # Make the rhs a deferred computation by", "deferred): if hasattr(expr, '__lazyboolor__'): result = expr.__lazyor__(deferred) if result is not NotImplemented: return", "node lhs, rhs = node.values delegate = Call( func=Name(id=runtime, ctx=Load()), args=[ lhs, #", "node delegate = Call( func=Name(id='__lazyboolnot__', ctx=Load()), args=[node.operand], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate", "hasattr(expr, '__lazyboolnot__'): result = expr.__lazynot__() if result is not NotImplemented: return result return", "not fail ) ''') node = parser(node) print(dump(node)) co_code = compile(node, '<string>', 'exec')", "lambda, we can't check it until it resolves. \"\"\" from ast import NodeTransformer,", "not NotImplemented: return result return not expr def parser(node: AST) -> AST: return", "node.values delegate = Call( func=Name(id=runtime, ctx=Load()), args=[ lhs, # Make the rhs a", "check it until it resolves. \"\"\" from ast import NodeTransformer, copy_location, fix_missing_locations, AST,", "tranformation converts the above example to: >>> OR(AND(cmd, lambda: ok), lambda: fail) Where", "= expr.__lazynot__() if result is not NotImplemented: return result return not expr def", "expr.__lazynot__() if result is not NotImplemented: return result return not expr def parser(node:", "parse(r''' print( cmd and ok or not fail ) ''') node = parser(node)", "\"\"\" from ast import NodeTransformer, copy_location, fix_missing_locations, AST, \\ BoolOp, UnaryOp, And, Or,", "Not, Call, Lambda, arguments, Name, Load from typing import Union __all__ = ['__lazybooland__',", "be the right operand. .. caution:: Since the rhs is opaque inside the", "will inspect the value and delegate to it if it has defined the", "lhs, # Make the rhs a deferred computation by wrapping with a lambda", "if result is not NotImplemented: return result return not expr def parser(node: AST)", "short-circuiting semantics (PEP-532 is deferred right now). The problem manifests when trying to", "node) fix_missing_locations(delegate) return delegate def __lazybooland__(expr, deferred): if hasattr(expr, '__lazybooland__'): result = expr.__lazyand__(deferred)", "= 'ok' fail = 'fail' node = parse(r''' print( cmd and ok or", "0 ok = 'ok' fail = 'fail' node = parse(r''' print( cmd and", "from ast import NodeTransformer, copy_location, fix_missing_locations, AST, \\ BoolOp, UnaryOp, And, Or, Not,", "shell scripts. We would like to keep that expression lazily evaluated but is", "AST: return LazyBoolsTransformer().visit(node) from ast import parse, dump # print(dump(parse('lambda: 10'))) cmd =", "overload the boolean operators (``not``, ``and``, ``or``) since they have short-circuiting semantics (PEP-532", "are quite common in shell scripts. We would like to keep that expression", "operators (``not``, ``and``, ``or``) since they have short-circuiting semantics (PEP-532 is deferred right", "keep that expression lazily evaluated but is not possible since the Python interpreter", "print(dump(parse('lambda: 10'))) cmd = 0 ok = 'ok' fail = 'fail' node =", "above example to: >>> OR(AND(cmd, lambda: ok), lambda: fail) Where ``OR`` and ``AND``", "and ``AND`` are runtime helpers that will inspect the value and delegate to", "result = expr.__lazyand__(deferred) if result is not NotImplemented: return result return expr and", "func=Name(id='__lazyboolnot__', ctx=Load()), args=[node.operand], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def __lazybooland__(expr, deferred): if", "until it resolves. \"\"\" from ast import NodeTransformer, copy_location, fix_missing_locations, AST, \\ BoolOp,", "\"\"\" def visit_BoolOp(self, node: BoolOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if isinstance(node.op, And): runtime", "= '__lazybooland__' elif isinstance(node.op, Or): runtime = '__lazyboolor__' else: return node lhs, rhs", "def parser(node: AST) -> AST: return LazyBoolsTransformer().visit(node) from ast import parse, dump #", "semantics (PEP-532 is deferred right now). The problem manifests when trying to use", "\"\"\" In Python it's not possible to overload the boolean operators (``not``, ``and``,", "interpreter will try to resolve it immediately, trigering the evaluation of ``cmd`` to", "expr.__lazyand__(deferred) if result is not NotImplemented: return result return expr and deferred() def", "Where ``OR`` and ``AND`` are runtime helpers that will inspect the value and", "isinstance(node.op, Not): return node delegate = Call( func=Name(id='__lazyboolnot__', ctx=Load()), args=[node.operand], keywords=[]) copy_location(delegate, node)", "aware of laziness. \"\"\" def visit_BoolOp(self, node: BoolOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if", "or the ``or`` branch. This tranformation converts the above example to: >>> OR(AND(cmd,", "This tranformation converts the above example to: >>> OR(AND(cmd, lambda: ok), lambda: fail)", "copy_location, fix_missing_locations, AST, \\ BoolOp, UnaryOp, And, Or, Not, Call, Lambda, arguments, Name,", "return delegate def __lazybooland__(expr, deferred): if hasattr(expr, '__lazybooland__'): result = expr.__lazyand__(deferred) if result", "lhs, rhs = node.values delegate = Call( func=Name(id=runtime, ctx=Load()), args=[ lhs, # Make", "if it has defined the proper protocol: - ``__lazyboolnot__(self)`` - ``__lazybooland__(self, rhs_callable)`` -", "to know if it should go with the ``and`` or the ``or`` branch.", "laziness. \"\"\" def visit_BoolOp(self, node: BoolOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if isinstance(node.op, And):", "delegate def visit_UnaryOp(self, node: UnaryOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if not isinstance(node.op, Not):", "], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def visit_UnaryOp(self, node: UnaryOp) -> Union[UnaryOp,", "expr and deferred() def __lazyboolor__(expr, deferred): if hasattr(expr, '__lazyboolor__'): result = expr.__lazyor__(deferred) if", "return LazyBoolsTransformer().visit(node) from ast import parse, dump # print(dump(parse('lambda: 10'))) cmd = 0", "operators do not have a reverse, the argument will always be the right", "<reponame>drslump/pysh \"\"\" In Python it's not possible to overload the boolean operators (``not``,", "rhs is opaque inside the lambda, we can't check it until it resolves.", "``cmd and ok or fail`` or similar constructs, which are quite common in", "the ``and`` or the ``or`` branch. This tranformation converts the above example to:", "Lambda, arguments, Name, Load from typing import Union __all__ = ['__lazybooland__', '__lazyboolor__', '__lazyboolnot__']", "= 0 ok = 'ok' fail = 'fail' node = parse(r''' print( cmd", "with a lambda Lambda( args=arguments(args=[], kwonlyargs=[], kw_defaults=[], defaults=[]), body=rhs) ], keywords=[]) copy_location(delegate, node)", "__all__ = ['__lazybooland__', '__lazyboolor__', '__lazyboolnot__'] class LazyBoolsTransformer(NodeTransformer): \"\"\" Make logical operators aware of", "a reverse, the argument will always be the right operand. .. caution:: Since", "``and`` or the ``or`` branch. This tranformation converts the above example to: >>>", "ok or fail`` or similar constructs, which are quite common in shell scripts.", "rhs_callable)`` .. note:: These operators do not have a reverse, the argument will", "resolves. \"\"\" from ast import NodeTransformer, copy_location, fix_missing_locations, AST, \\ BoolOp, UnaryOp, And,", "BoolOp, UnaryOp, And, Or, Not, Call, Lambda, arguments, Name, Load from typing import", "- ``__lazybooland__(self, rhs_callable)`` - ``__lazyboolor__(self, rhs_callable)`` .. note:: These operators do not have", "will always be the right operand. .. caution:: Since the rhs is opaque", "the lambda, we can't check it until it resolves. \"\"\" from ast import", "caution:: Since the rhs is opaque inside the lambda, we can't check it", "= node.values delegate = Call( func=Name(id=runtime, ctx=Load()), args=[ lhs, # Make the rhs", "it has defined the proper protocol: - ``__lazyboolnot__(self)`` - ``__lazybooland__(self, rhs_callable)`` - ``__lazyboolor__(self,", "the boolean operators (``not``, ``and``, ``or``) since they have short-circuiting semantics (PEP-532 is", "operand. .. caution:: Since the rhs is opaque inside the lambda, we can't", "use a ``cmd and ok or fail`` or similar constructs, which are quite", "dump # print(dump(parse('lambda: 10'))) cmd = 0 ok = 'ok' fail = 'fail'", "node) fix_missing_locations(delegate) return delegate def visit_UnaryOp(self, node: UnaryOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if", "Make logical operators aware of laziness. \"\"\" def visit_BoolOp(self, node: BoolOp) -> Union[UnaryOp,", "delegate to it if it has defined the proper protocol: - ``__lazyboolnot__(self)`` -", "Python interpreter will try to resolve it immediately, trigering the evaluation of ``cmd``", "not have a reverse, the argument will always be the right operand. ..", "import parse, dump # print(dump(parse('lambda: 10'))) cmd = 0 ok = 'ok' fail", "``cmd`` to know if it should go with the ``and`` or the ``or``", "trying to use a ``cmd and ok or fail`` or similar constructs, which", "the evaluation of ``cmd`` to know if it should go with the ``and``", "lazily evaluated but is not possible since the Python interpreter will try to", "Since the rhs is opaque inside the lambda, we can't check it until", "(``not``, ``and``, ``or``) since they have short-circuiting semantics (PEP-532 is deferred right now).", "deferred() def __lazyboolnot__(expr): if hasattr(expr, '__lazyboolnot__'): result = expr.__lazynot__() if result is not", "in shell scripts. We would like to keep that expression lazily evaluated but", "if hasattr(expr, '__lazyboolnot__'): result = expr.__lazynot__() if result is not NotImplemented: return result", "not possible to overload the boolean operators (``not``, ``and``, ``or``) since they have", "'ok' fail = 'fail' node = parse(r''' print( cmd and ok or not", "to use a ``cmd and ok or fail`` or similar constructs, which are", "'__lazyboolor__', '__lazyboolnot__'] class LazyBoolsTransformer(NodeTransformer): \"\"\" Make logical operators aware of laziness. \"\"\" def", "to resolve it immediately, trigering the evaluation of ``cmd`` to know if it", "These operators do not have a reverse, the argument will always be the", "fail`` or similar constructs, which are quite common in shell scripts. We would", "or similar constructs, which are quite common in shell scripts. We would like", "Lambda( args=arguments(args=[], kwonlyargs=[], kw_defaults=[], defaults=[]), body=rhs) ], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate", "Or, Not, Call, Lambda, arguments, Name, Load from typing import Union __all__ =", "``OR`` and ``AND`` are runtime helpers that will inspect the value and delegate", "manifests when trying to use a ``cmd and ok or fail`` or similar", "the rhs a deferred computation by wrapping with a lambda Lambda( args=arguments(args=[], kwonlyargs=[],", "now). The problem manifests when trying to use a ``cmd and ok or", "return result return expr and deferred() def __lazyboolor__(expr, deferred): if hasattr(expr, '__lazyboolor__'): result", "to: >>> OR(AND(cmd, lambda: ok), lambda: fail) Where ``OR`` and ``AND`` are runtime", "operators aware of laziness. \"\"\" def visit_BoolOp(self, node: BoolOp) -> Union[UnaryOp, Call]: self.generic_visit(node)", "AST, \\ BoolOp, UnaryOp, And, Or, Not, Call, Lambda, arguments, Name, Load from", "trigering the evaluation of ``cmd`` to know if it should go with the", "(PEP-532 is deferred right now). The problem manifests when trying to use a", "runtime = '__lazybooland__' elif isinstance(node.op, Or): runtime = '__lazyboolor__' else: return node lhs,", "-> Union[UnaryOp, Call]: self.generic_visit(node) if not isinstance(node.op, Not): return node delegate = Call(", "note:: These operators do not have a reverse, the argument will always be", "lambda Lambda( args=arguments(args=[], kwonlyargs=[], kw_defaults=[], defaults=[]), body=rhs) ], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return", "In Python it's not possible to overload the boolean operators (``not``, ``and``, ``or``)", "by wrapping with a lambda Lambda( args=arguments(args=[], kwonlyargs=[], kw_defaults=[], defaults=[]), body=rhs) ], keywords=[])", "have a reverse, the argument will always be the right operand. .. caution::", "arguments, Name, Load from typing import Union __all__ = ['__lazybooland__', '__lazyboolor__', '__lazyboolnot__'] class", "Union[UnaryOp, Call]: self.generic_visit(node) if not isinstance(node.op, Not): return node delegate = Call( func=Name(id='__lazyboolnot__',", "'__lazyboolor__' else: return node lhs, rhs = node.values delegate = Call( func=Name(id=runtime, ctx=Load()),", "would like to keep that expression lazily evaluated but is not possible since", "expr or deferred() def __lazyboolnot__(expr): if hasattr(expr, '__lazyboolnot__'): result = expr.__lazynot__() if result", "NotImplemented: return result return expr and deferred() def __lazyboolor__(expr, deferred): if hasattr(expr, '__lazyboolor__'):", "lambda: fail) Where ``OR`` and ``AND`` are runtime helpers that will inspect the", "rhs_callable)`` - ``__lazyboolor__(self, rhs_callable)`` .. note:: These operators do not have a reverse,", "-> AST: return LazyBoolsTransformer().visit(node) from ast import parse, dump # print(dump(parse('lambda: 10'))) cmd", "args=arguments(args=[], kwonlyargs=[], kw_defaults=[], defaults=[]), body=rhs) ], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def", "common in shell scripts. We would like to keep that expression lazily evaluated", "which are quite common in shell scripts. We would like to keep that", "import Union __all__ = ['__lazybooland__', '__lazyboolor__', '__lazyboolnot__'] class LazyBoolsTransformer(NodeTransformer): \"\"\" Make logical operators", "ok = 'ok' fail = 'fail' node = parse(r''' print( cmd and ok", "immediately, trigering the evaluation of ``cmd`` to know if it should go with", "from ast import parse, dump # print(dump(parse('lambda: 10'))) cmd = 0 ok =", ".. caution:: Since the rhs is opaque inside the lambda, we can't check", "= ['__lazybooland__', '__lazyboolor__', '__lazyboolnot__'] class LazyBoolsTransformer(NodeTransformer): \"\"\" Make logical operators aware of laziness.", "NotImplemented: return result return expr or deferred() def __lazyboolnot__(expr): if hasattr(expr, '__lazyboolnot__'): result", "copy_location(delegate, node) fix_missing_locations(delegate) return delegate def __lazybooland__(expr, deferred): if hasattr(expr, '__lazybooland__'): result =", "the argument will always be the right operand. .. caution:: Since the rhs", "is not NotImplemented: return result return not expr def parser(node: AST) -> AST:", "the ``or`` branch. This tranformation converts the above example to: >>> OR(AND(cmd, lambda:", "a lambda Lambda( args=arguments(args=[], kwonlyargs=[], kw_defaults=[], defaults=[]), body=rhs) ], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate)", "the Python interpreter will try to resolve it immediately, trigering the evaluation of", "should go with the ``and`` or the ``or`` branch. This tranformation converts the", "fix_missing_locations(delegate) return delegate def __lazybooland__(expr, deferred): if hasattr(expr, '__lazybooland__'): result = expr.__lazyand__(deferred) if", "And): runtime = '__lazybooland__' elif isinstance(node.op, Or): runtime = '__lazyboolor__' else: return node", "self.generic_visit(node) if isinstance(node.op, And): runtime = '__lazybooland__' elif isinstance(node.op, Or): runtime = '__lazyboolor__'", "the value and delegate to it if it has defined the proper protocol:", "is deferred right now). The problem manifests when trying to use a ``cmd", "ctx=Load()), args=[ lhs, # Make the rhs a deferred computation by wrapping with", "keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def __lazybooland__(expr, deferred): if hasattr(expr, '__lazybooland__'): result", "LazyBoolsTransformer().visit(node) from ast import parse, dump # print(dump(parse('lambda: 10'))) cmd = 0 ok", "expr.__lazyor__(deferred) if result is not NotImplemented: return result return expr or deferred() def", "result return not expr def parser(node: AST) -> AST: return LazyBoolsTransformer().visit(node) from ast", "result = expr.__lazyor__(deferred) if result is not NotImplemented: return result return expr or", "a ``cmd and ok or fail`` or similar constructs, which are quite common", "Load from typing import Union __all__ = ['__lazybooland__', '__lazyboolor__', '__lazyboolnot__'] class LazyBoolsTransformer(NodeTransformer): \"\"\"", "and deferred() def __lazyboolor__(expr, deferred): if hasattr(expr, '__lazyboolor__'): result = expr.__lazyor__(deferred) if result", "the proper protocol: - ``__lazyboolnot__(self)`` - ``__lazybooland__(self, rhs_callable)`` - ``__lazyboolor__(self, rhs_callable)`` .. note::", "['__lazybooland__', '__lazyboolor__', '__lazyboolnot__'] class LazyBoolsTransformer(NodeTransformer): \"\"\" Make logical operators aware of laziness. \"\"\"", "delegate = Call( func=Name(id='__lazyboolnot__', ctx=Load()), args=[node.operand], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def", "isinstance(node.op, And): runtime = '__lazybooland__' elif isinstance(node.op, Or): runtime = '__lazyboolor__' else: return", "a deferred computation by wrapping with a lambda Lambda( args=arguments(args=[], kwonlyargs=[], kw_defaults=[], defaults=[]),", "example to: >>> OR(AND(cmd, lambda: ok), lambda: fail) Where ``OR`` and ``AND`` are", "NodeTransformer, copy_location, fix_missing_locations, AST, \\ BoolOp, UnaryOp, And, Or, Not, Call, Lambda, arguments,", "And, Or, Not, Call, Lambda, arguments, Name, Load from typing import Union __all__", "# print(dump(parse('lambda: 10'))) cmd = 0 ok = 'ok' fail = 'fail' node", "runtime helpers that will inspect the value and delegate to it if it", "defined the proper protocol: - ``__lazyboolnot__(self)`` - ``__lazybooland__(self, rhs_callable)`` - ``__lazyboolor__(self, rhs_callable)`` ..", "if result is not NotImplemented: return result return expr and deferred() def __lazyboolor__(expr,", ">>> OR(AND(cmd, lambda: ok), lambda: fail) Where ``OR`` and ``AND`` are runtime helpers", "``or``) since they have short-circuiting semantics (PEP-532 is deferred right now). The problem", "with the ``and`` or the ``or`` branch. This tranformation converts the above example", "keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def visit_UnaryOp(self, node: UnaryOp) -> Union[UnaryOp, Call]:", "the above example to: >>> OR(AND(cmd, lambda: ok), lambda: fail) Where ``OR`` and", "the right operand. .. caution:: Since the rhs is opaque inside the lambda,", "deferred right now). The problem manifests when trying to use a ``cmd and", "deferred): if hasattr(expr, '__lazybooland__'): result = expr.__lazyand__(deferred) if result is not NotImplemented: return", "inside the lambda, we can't check it until it resolves. \"\"\" from ast", "def __lazybooland__(expr, deferred): if hasattr(expr, '__lazybooland__'): result = expr.__lazyand__(deferred) if result is not", "it immediately, trigering the evaluation of ``cmd`` to know if it should go", "return result return expr or deferred() def __lazyboolnot__(expr): if hasattr(expr, '__lazyboolnot__'): result =", "print( cmd and ok or not fail ) ''') node = parser(node) print(dump(node))", "def visit_BoolOp(self, node: BoolOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if isinstance(node.op, And): runtime =", "else: return node lhs, rhs = node.values delegate = Call( func=Name(id=runtime, ctx=Load()), args=[", "it if it has defined the proper protocol: - ``__lazyboolnot__(self)`` - ``__lazybooland__(self, rhs_callable)``", "or not fail ) ''') node = parser(node) print(dump(node)) co_code = compile(node, '<string>',", "is opaque inside the lambda, we can't check it until it resolves. \"\"\"", "helpers that will inspect the value and delegate to it if it has", "= parse(r''' print( cmd and ok or not fail ) ''') node =", "not NotImplemented: return result return expr or deferred() def __lazyboolnot__(expr): if hasattr(expr, '__lazyboolnot__'):", "UnaryOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if not isinstance(node.op, Not): return node delegate =", "result is not NotImplemented: return result return expr and deferred() def __lazyboolor__(expr, deferred):", "always be the right operand. .. caution:: Since the rhs is opaque inside", "= Call( func=Name(id=runtime, ctx=Load()), args=[ lhs, # Make the rhs a deferred computation", "not NotImplemented: return result return expr and deferred() def __lazyboolor__(expr, deferred): if hasattr(expr,", "has defined the proper protocol: - ``__lazyboolnot__(self)`` - ``__lazybooland__(self, rhs_callable)`` - ``__lazyboolor__(self, rhs_callable)``", "node: BoolOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if isinstance(node.op, And): runtime = '__lazybooland__' elif", "Call, Lambda, arguments, Name, Load from typing import Union __all__ = ['__lazybooland__', '__lazyboolor__',", "fail = 'fail' node = parse(r''' print( cmd and ok or not fail", "are runtime helpers that will inspect the value and delegate to it if", "do not have a reverse, the argument will always be the right operand.", "result is not NotImplemented: return result return not expr def parser(node: AST) ->", "and ok or not fail ) ''') node = parser(node) print(dump(node)) co_code =", "= expr.__lazyand__(deferred) if result is not NotImplemented: return result return expr and deferred()", "possible to overload the boolean operators (``not``, ``and``, ``or``) since they have short-circuiting", "defaults=[]), body=rhs) ], keywords=[]) copy_location(delegate, node) fix_missing_locations(delegate) return delegate def visit_UnaryOp(self, node: UnaryOp)", "try to resolve it immediately, trigering the evaluation of ``cmd`` to know if", "result is not NotImplemented: return result return expr or deferred() def __lazyboolnot__(expr): if", "know if it should go with the ``and`` or the ``or`` branch. This", "if isinstance(node.op, And): runtime = '__lazybooland__' elif isinstance(node.op, Or): runtime = '__lazyboolor__' else:", "``__lazyboolor__(self, rhs_callable)`` .. note:: These operators do not have a reverse, the argument", "that expression lazily evaluated but is not possible since the Python interpreter will", "'__lazyboolnot__'] class LazyBoolsTransformer(NodeTransformer): \"\"\" Make logical operators aware of laziness. \"\"\" def visit_BoolOp(self,", "\"\"\" Make logical operators aware of laziness. \"\"\" def visit_BoolOp(self, node: BoolOp) ->", "if result is not NotImplemented: return result return expr or deferred() def __lazyboolnot__(expr):", "# Make the rhs a deferred computation by wrapping with a lambda Lambda(", "visit_UnaryOp(self, node: UnaryOp) -> Union[UnaryOp, Call]: self.generic_visit(node) if not isinstance(node.op, Not): return node" ]
[ "import views urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path( 'login/', auth_views.LoginView.as_view(template_name='auth/authForm.html'), name='login' ),", "auth_views.PasswordChangeDoneView.as_view( template_name='auth/changePasswordDone.html' ), name='password_change_done' ), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='auth/resetPassword.html'), name='password_reset' ), path( 'password-reset-done/', auth_views.PasswordResetDoneView.as_view(", "name='login' ), path( 'logout/', auth_views.LogoutView.as_view(template_name='auth/logout.html'), name='logout' ), path( 'password-change/', auth_views.PasswordChangeView.as_view( template_name='auth/changePassword.html' ), name='password_change'", "template_name='auth/changePasswordDone.html' ), name='password_change_done' ), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='auth/resetPassword.html'), name='password_reset' ), path( 'password-reset-done/', auth_views.PasswordResetDoneView.as_view( template_name='auth/resetPasswordDone.html'", "), path( 'password-change-done/', auth_views.PasswordChangeDoneView.as_view( template_name='auth/changePasswordDone.html' ), name='password_change_done' ), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='auth/resetPassword.html'), name='password_reset' ),", "), name='password_change' ), path( 'password-change-done/', auth_views.PasswordChangeDoneView.as_view( template_name='auth/changePasswordDone.html' ), name='password_change_done' ), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='auth/resetPassword.html'),", "name='password_reset' ), path( 'password-reset-done/', auth_views.PasswordResetDoneView.as_view( template_name='auth/resetPasswordDone.html' ), name='password_reset_done' ), path( 'password-reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='auth/resetPasswordConfirm.html'", "path( 'logout/', auth_views.LogoutView.as_view(template_name='auth/logout.html'), name='logout' ), path( 'password-change/', auth_views.PasswordChangeView.as_view( template_name='auth/changePassword.html' ), name='password_change' ), path(", "'password-reset-done/', auth_views.PasswordResetDoneView.as_view( template_name='auth/resetPasswordDone.html' ), name='password_reset_done' ), path( 'password-reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='auth/resetPasswordConfirm.html' ), name='password_reset_confirm' ),", "'login/', auth_views.LoginView.as_view(template_name='auth/authForm.html'), name='login' ), path( 'logout/', auth_views.LogoutView.as_view(template_name='auth/logout.html'), name='logout' ), path( 'password-change/', auth_views.PasswordChangeView.as_view( template_name='auth/changePassword.html'", "from django.contrib.auth import views as auth_views from django.urls import path from . import", "import views as auth_views from django.urls import path from . import views urlpatterns", "auth_views.LogoutView.as_view(template_name='auth/logout.html'), name='logout' ), path( 'password-change/', auth_views.PasswordChangeView.as_view( template_name='auth/changePassword.html' ), name='password_change' ), path( 'password-change-done/', auth_views.PasswordChangeDoneView.as_view(", "), path( 'logout/', auth_views.LogoutView.as_view(template_name='auth/logout.html'), name='logout' ), path( 'password-change/', auth_views.PasswordChangeView.as_view( template_name='auth/changePassword.html' ), name='password_change' ),", "path( 'password-reset-done/', auth_views.PasswordResetDoneView.as_view( template_name='auth/resetPasswordDone.html' ), name='password_reset_done' ), path( 'password-reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='auth/resetPasswordConfirm.html' ), name='password_reset_confirm'", "from . import views urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path( 'login/', auth_views.LoginView.as_view(template_name='auth/authForm.html'),", "), path( 'password-change/', auth_views.PasswordChangeView.as_view( template_name='auth/changePassword.html' ), name='password_change' ), path( 'password-change-done/', auth_views.PasswordChangeDoneView.as_view( template_name='auth/changePasswordDone.html' ),", "django.urls import path from . import views urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'),", "path('password-reset/', auth_views.PasswordResetView.as_view( template_name='auth/resetPassword.html'), name='password_reset' ), path( 'password-reset-done/', auth_views.PasswordResetDoneView.as_view( template_name='auth/resetPasswordDone.html' ), name='password_reset_done' ), path(", "), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='auth/resetPassword.html'), name='password_reset' ), path( 'password-reset-done/', auth_views.PasswordResetDoneView.as_view( template_name='auth/resetPasswordDone.html' ), name='password_reset_done' ),", "views.SignUp.as_view(), name='signup'), path( 'login/', auth_views.LoginView.as_view(template_name='auth/authForm.html'), name='login' ), path( 'logout/', auth_views.LogoutView.as_view(template_name='auth/logout.html'), name='logout' ), path(", "path from . import views urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path( 'login/',", "<gh_stars>0 from django.contrib.auth import views as auth_views from django.urls import path from .", "as auth_views from django.urls import path from . import views urlpatterns = [", "'password-change-done/', auth_views.PasswordChangeDoneView.as_view( template_name='auth/changePasswordDone.html' ), name='password_change_done' ), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='auth/resetPassword.html'), name='password_reset' ), path( 'password-reset-done/',", "name='password_change' ), path( 'password-change-done/', auth_views.PasswordChangeDoneView.as_view( template_name='auth/changePasswordDone.html' ), name='password_change_done' ), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='auth/resetPassword.html'), name='password_reset'", "template_name='auth/changePassword.html' ), name='password_change' ), path( 'password-change-done/', auth_views.PasswordChangeDoneView.as_view( template_name='auth/changePasswordDone.html' ), name='password_change_done' ), path('password-reset/', auth_views.PasswordResetView.as_view(", "auth_views.PasswordResetView.as_view( template_name='auth/resetPassword.html'), name='password_reset' ), path( 'password-reset-done/', auth_views.PasswordResetDoneView.as_view( template_name='auth/resetPasswordDone.html' ), name='password_reset_done' ), path( 'password-reset/confirm/<uidb64>/<token>/',", "), path( 'password-reset-done/', auth_views.PasswordResetDoneView.as_view( template_name='auth/resetPasswordDone.html' ), name='password_reset_done' ), path( 'password-reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='auth/resetPasswordConfirm.html' ),", "path('signup/', views.SignUp.as_view(), name='signup'), path( 'login/', auth_views.LoginView.as_view(template_name='auth/authForm.html'), name='login' ), path( 'logout/', auth_views.LogoutView.as_view(template_name='auth/logout.html'), name='logout' ),", "name='signup'), path( 'login/', auth_views.LoginView.as_view(template_name='auth/authForm.html'), name='login' ), path( 'logout/', auth_views.LogoutView.as_view(template_name='auth/logout.html'), name='logout' ), path( 'password-change/',", "from django.urls import path from . import views urlpatterns = [ path('signup/', views.SignUp.as_view(),", "'password-change/', auth_views.PasswordChangeView.as_view( template_name='auth/changePassword.html' ), name='password_change' ), path( 'password-change-done/', auth_views.PasswordChangeDoneView.as_view( template_name='auth/changePasswordDone.html' ), name='password_change_done' ),", "views as auth_views from django.urls import path from . import views urlpatterns =", "django.contrib.auth import views as auth_views from django.urls import path from . import views", "auth_views.LoginView.as_view(template_name='auth/authForm.html'), name='login' ), path( 'logout/', auth_views.LogoutView.as_view(template_name='auth/logout.html'), name='logout' ), path( 'password-change/', auth_views.PasswordChangeView.as_view( template_name='auth/changePassword.html' ),", "path( 'login/', auth_views.LoginView.as_view(template_name='auth/authForm.html'), name='login' ), path( 'logout/', auth_views.LogoutView.as_view(template_name='auth/logout.html'), name='logout' ), path( 'password-change/', auth_views.PasswordChangeView.as_view(", "path( 'password-change/', auth_views.PasswordChangeView.as_view( template_name='auth/changePassword.html' ), name='password_change' ), path( 'password-change-done/', auth_views.PasswordChangeDoneView.as_view( template_name='auth/changePasswordDone.html' ), name='password_change_done'", "auth_views.PasswordResetDoneView.as_view( template_name='auth/resetPasswordDone.html' ), name='password_reset_done' ), path( 'password-reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='auth/resetPasswordConfirm.html' ), name='password_reset_confirm' ), ]", "import path from . import views urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path(", "= [ path('signup/', views.SignUp.as_view(), name='signup'), path( 'login/', auth_views.LoginView.as_view(template_name='auth/authForm.html'), name='login' ), path( 'logout/', auth_views.LogoutView.as_view(template_name='auth/logout.html'),", "[ path('signup/', views.SignUp.as_view(), name='signup'), path( 'login/', auth_views.LoginView.as_view(template_name='auth/authForm.html'), name='login' ), path( 'logout/', auth_views.LogoutView.as_view(template_name='auth/logout.html'), name='logout'", ". import views urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path( 'login/', auth_views.LoginView.as_view(template_name='auth/authForm.html'), name='login'", "'logout/', auth_views.LogoutView.as_view(template_name='auth/logout.html'), name='logout' ), path( 'password-change/', auth_views.PasswordChangeView.as_view( template_name='auth/changePassword.html' ), name='password_change' ), path( 'password-change-done/',", "), name='password_change_done' ), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='auth/resetPassword.html'), name='password_reset' ), path( 'password-reset-done/', auth_views.PasswordResetDoneView.as_view( template_name='auth/resetPasswordDone.html' ),", "urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path( 'login/', auth_views.LoginView.as_view(template_name='auth/authForm.html'), name='login' ), path( 'logout/',", "name='password_change_done' ), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='auth/resetPassword.html'), name='password_reset' ), path( 'password-reset-done/', auth_views.PasswordResetDoneView.as_view( template_name='auth/resetPasswordDone.html' ), name='password_reset_done'", "template_name='auth/resetPassword.html'), name='password_reset' ), path( 'password-reset-done/', auth_views.PasswordResetDoneView.as_view( template_name='auth/resetPasswordDone.html' ), name='password_reset_done' ), path( 'password-reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(", "name='logout' ), path( 'password-change/', auth_views.PasswordChangeView.as_view( template_name='auth/changePassword.html' ), name='password_change' ), path( 'password-change-done/', auth_views.PasswordChangeDoneView.as_view( template_name='auth/changePasswordDone.html'", "path( 'password-change-done/', auth_views.PasswordChangeDoneView.as_view( template_name='auth/changePasswordDone.html' ), name='password_change_done' ), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='auth/resetPassword.html'), name='password_reset' ), path(", "auth_views.PasswordChangeView.as_view( template_name='auth/changePassword.html' ), name='password_change' ), path( 'password-change-done/', auth_views.PasswordChangeDoneView.as_view( template_name='auth/changePasswordDone.html' ), name='password_change_done' ), path('password-reset/',", "auth_views from django.urls import path from . import views urlpatterns = [ path('signup/',", "views urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path( 'login/', auth_views.LoginView.as_view(template_name='auth/authForm.html'), name='login' ), path(" ]
[ "from the environment.\"\"\" args: CLIArgs var_prefix = \"BEVY_APP_\" path_key = \"PATH\" config_file_key =", "object aggregates all options values that the Bevy.App application pulls in from the", "return self._env_options[item] return self._options[item] def __contains__(self, item: str) -> bool: return item in", "self._env_options.copy() def add_using_arg_parser(self, parser: ArgumentParser): \"\"\"Uses an ArgumentParser to populate the CLI options.\"\"\"", "None = None) -> Any | None: try: return self[item] except KeyError: return", "self._build_base_options() def __getitem__(self, item: str) -> Any: if item in self._cli_options: return self._cli_options[item]", "Any: if item in self._cli_options: return self._cli_options[item] if item in self._env_options: return self._env_options[item]", "in (self._cli_options | self._env_options | self._options) @property def cli(self) -> dict[str, Any]: return", "_get_path(self): return os.getcwd() def _load_env(self) -> dict[str, Any]: return { key.removeprefix(self.prefix): value for", "= {} self._env_options = self._load_env() self._options = self._build_base_options() def __getitem__(self, item: str) ->", "path_key = \"PATH\" config_file_key = \"CONFIG_FILE\" logger_level_key = \"LOGGER_LEVEL\" logger_name_key = \"LOGGER_NAME\" def", "self._cli_options = {} self._env_options = self._load_env() self._options = self._build_base_options() def __getitem__(self, item: str)", "import Any import os @detect_dependencies class Options(AutoInject): \"\"\"The options object aggregates all options", "return self._cli_options[item] if item in self._env_options: return self._env_options[item] return self._options[item] def __contains__(self, item:", "args: CLIArgs var_prefix = \"BEVY_APP_\" path_key = \"PATH\" config_file_key = \"CONFIG_FILE\" logger_level_key =", "return item in (self._cli_options | self._env_options | self._options) @property def cli(self) -> dict[str,", "return self._env_options.copy() def add_using_arg_parser(self, parser: ArgumentParser): \"\"\"Uses an ArgumentParser to populate the CLI", "pulls in from the environment.\"\"\" args: CLIArgs var_prefix = \"BEVY_APP_\" path_key = \"PATH\"", "the environment.\"\"\" args: CLIArgs var_prefix = \"BEVY_APP_\" path_key = \"PATH\" config_file_key = \"CONFIG_FILE\"", "return {self.path_key: self._get_path()} def _get_path(self): return os.getcwd() def _load_env(self) -> dict[str, Any]: return", "item in (self._cli_options | self._env_options | self._options) @property def cli(self) -> dict[str, Any]:", "self._env_options = self._load_env() self._options = self._build_base_options() def __getitem__(self, item: str) -> Any: if", "AutoInject, detect_dependencies from bevy.app.args import ArgumentParser, CLIArgs from typing import Any import os", "| None = None) -> Any | None: try: return self[item] except KeyError:", "str, default: Any | None = None) -> Any | None: try: return", "logger_name_key = \"LOGGER_NAME\" def __init__(self): self._cli_options = {} self._env_options = self._load_env() self._options =", "Any]: return self._env_options.copy() def add_using_arg_parser(self, parser: ArgumentParser): \"\"\"Uses an ArgumentParser to populate the", "item: str) -> bool: return item in (self._cli_options | self._env_options | self._options) @property", "\"LOGGER_LEVEL\" logger_name_key = \"LOGGER_NAME\" def __init__(self): self._cli_options = {} self._env_options = self._load_env() self._options", "None: try: return self[item] except KeyError: return default def _build_base_options(self) -> dict[str, Any]:", "str) -> bool: return item in (self._cli_options | self._env_options | self._options) @property def", "-> Any | None: try: return self[item] except KeyError: return default def _build_base_options(self)", "dict[str, Any]: return self._env_options.copy() def add_using_arg_parser(self, parser: ArgumentParser): \"\"\"Uses an ArgumentParser to populate", "get(self, item: str, default: Any | None = None) -> Any | None:", "bool: return item in (self._cli_options | self._env_options | self._options) @property def cli(self) ->", "-> dict[str, Any]: return { key.removeprefix(self.prefix): value for key, value in os.environ.items() if", "def _build_base_options(self) -> dict[str, Any]: return {self.path_key: self._get_path()} def _get_path(self): return os.getcwd() def", "item: str, default: Any | None = None) -> Any | None: try:", "CLIArgs var_prefix = \"BEVY_APP_\" path_key = \"PATH\" config_file_key = \"CONFIG_FILE\" logger_level_key = \"LOGGER_LEVEL\"", "= self._build_base_options() def __getitem__(self, item: str) -> Any: if item in self._cli_options: return", "return self[item] except KeyError: return default def _build_base_options(self) -> dict[str, Any]: return {self.path_key:", "@property def cli(self) -> dict[str, Any]: return self._cli_options.copy() @property def env(self) -> dict[str,", "Options(AutoInject): \"\"\"The options object aggregates all options values that the Bevy.App application pulls", "item in self._env_options: return self._env_options[item] return self._options[item] def __contains__(self, item: str) -> bool:", "= \"PATH\" config_file_key = \"CONFIG_FILE\" logger_level_key = \"LOGGER_LEVEL\" logger_name_key = \"LOGGER_NAME\" def __init__(self):", "def __init__(self): self._cli_options = {} self._env_options = self._load_env() self._options = self._build_base_options() def __getitem__(self,", "def _get_path(self): return os.getcwd() def _load_env(self) -> dict[str, Any]: return { key.removeprefix(self.prefix): value", "self._options[item] def __contains__(self, item: str) -> bool: return item in (self._cli_options | self._env_options", "def __getitem__(self, item: str) -> Any: if item in self._cli_options: return self._cli_options[item] if", "options values that the Bevy.App application pulls in from the environment.\"\"\" args: CLIArgs", "except KeyError: return default def _build_base_options(self) -> dict[str, Any]: return {self.path_key: self._get_path()} def", "None) -> Any | None: try: return self[item] except KeyError: return default def", "CLIArgs from typing import Any import os @detect_dependencies class Options(AutoInject): \"\"\"The options object", "self._env_options | self._options) @property def cli(self) -> dict[str, Any]: return self._cli_options.copy() @property def", "bevy.injection import AutoInject, detect_dependencies from bevy.app.args import ArgumentParser, CLIArgs from typing import Any", "if item in self._env_options: return self._env_options[item] return self._options[item] def __contains__(self, item: str) ->", "self._env_options[item] return self._options[item] def __contains__(self, item: str) -> bool: return item in (self._cli_options", "from bevy.app.args import ArgumentParser, CLIArgs from typing import Any import os @detect_dependencies class", "options.\"\"\" self._cli_options.update(self.args.parse_args(parser).to_dict()) def get(self, item: str, default: Any | None = None) ->", "Any]: return { key.removeprefix(self.prefix): value for key, value in os.environ.items() if key.startswith(self.prefix) }", "try: return self[item] except KeyError: return default def _build_base_options(self) -> dict[str, Any]: return", "return self._cli_options.copy() @property def env(self) -> dict[str, Any]: return self._env_options.copy() def add_using_arg_parser(self, parser:", "__init__(self): self._cli_options = {} self._env_options = self._load_env() self._options = self._build_base_options() def __getitem__(self, item:", "aggregates all options values that the Bevy.App application pulls in from the environment.\"\"\"", "the Bevy.App application pulls in from the environment.\"\"\" args: CLIArgs var_prefix = \"BEVY_APP_\"", "bevy.app.args import ArgumentParser, CLIArgs from typing import Any import os @detect_dependencies class Options(AutoInject):", "ArgumentParser): \"\"\"Uses an ArgumentParser to populate the CLI options.\"\"\" self._cli_options.update(self.args.parse_args(parser).to_dict()) def get(self, item:", "= self._load_env() self._options = self._build_base_options() def __getitem__(self, item: str) -> Any: if item", "dict[str, Any]: return self._cli_options.copy() @property def env(self) -> dict[str, Any]: return self._env_options.copy() def", "in self._env_options: return self._env_options[item] return self._options[item] def __contains__(self, item: str) -> bool: return", "@detect_dependencies class Options(AutoInject): \"\"\"The options object aggregates all options values that the Bevy.App", "Any | None: try: return self[item] except KeyError: return default def _build_base_options(self) ->", "{} self._env_options = self._load_env() self._options = self._build_base_options() def __getitem__(self, item: str) -> Any:", "an ArgumentParser to populate the CLI options.\"\"\" self._cli_options.update(self.args.parse_args(parser).to_dict()) def get(self, item: str, default:", "@property def env(self) -> dict[str, Any]: return self._env_options.copy() def add_using_arg_parser(self, parser: ArgumentParser): \"\"\"Uses", "self._cli_options: return self._cli_options[item] if item in self._env_options: return self._env_options[item] return self._options[item] def __contains__(self,", "| self._env_options | self._options) @property def cli(self) -> dict[str, Any]: return self._cli_options.copy() @property", "= \"BEVY_APP_\" path_key = \"PATH\" config_file_key = \"CONFIG_FILE\" logger_level_key = \"LOGGER_LEVEL\" logger_name_key =", "self._options) @property def cli(self) -> dict[str, Any]: return self._cli_options.copy() @property def env(self) ->", "add_using_arg_parser(self, parser: ArgumentParser): \"\"\"Uses an ArgumentParser to populate the CLI options.\"\"\" self._cli_options.update(self.args.parse_args(parser).to_dict()) def", "self._options = self._build_base_options() def __getitem__(self, item: str) -> Any: if item in self._cli_options:", "def env(self) -> dict[str, Any]: return self._env_options.copy() def add_using_arg_parser(self, parser: ArgumentParser): \"\"\"Uses an", "| None: try: return self[item] except KeyError: return default def _build_base_options(self) -> dict[str,", "import os @detect_dependencies class Options(AutoInject): \"\"\"The options object aggregates all options values that", "that the Bevy.App application pulls in from the environment.\"\"\" args: CLIArgs var_prefix =", "Bevy.App application pulls in from the environment.\"\"\" args: CLIArgs var_prefix = \"BEVY_APP_\" path_key", "self._cli_options[item] if item in self._env_options: return self._env_options[item] return self._options[item] def __contains__(self, item: str)", "self._env_options: return self._env_options[item] return self._options[item] def __contains__(self, item: str) -> bool: return item", "return self._options[item] def __contains__(self, item: str) -> bool: return item in (self._cli_options |", "default: Any | None = None) -> Any | None: try: return self[item]", "from bevy.injection import AutoInject, detect_dependencies from bevy.app.args import ArgumentParser, CLIArgs from typing import", "env(self) -> dict[str, Any]: return self._env_options.copy() def add_using_arg_parser(self, parser: ArgumentParser): \"\"\"Uses an ArgumentParser", "in from the environment.\"\"\" args: CLIArgs var_prefix = \"BEVY_APP_\" path_key = \"PATH\" config_file_key", "dict[str, Any]: return {self.path_key: self._get_path()} def _get_path(self): return os.getcwd() def _load_env(self) -> dict[str,", "var_prefix = \"BEVY_APP_\" path_key = \"PATH\" config_file_key = \"CONFIG_FILE\" logger_level_key = \"LOGGER_LEVEL\" logger_name_key", "ArgumentParser, CLIArgs from typing import Any import os @detect_dependencies class Options(AutoInject): \"\"\"The options", "self._cli_options.update(self.args.parse_args(parser).to_dict()) def get(self, item: str, default: Any | None = None) -> Any", "dict[str, Any]: return { key.removeprefix(self.prefix): value for key, value in os.environ.items() if key.startswith(self.prefix)", "typing import Any import os @detect_dependencies class Options(AutoInject): \"\"\"The options object aggregates all", "| self._options) @property def cli(self) -> dict[str, Any]: return self._cli_options.copy() @property def env(self)", "\"LOGGER_NAME\" def __init__(self): self._cli_options = {} self._env_options = self._load_env() self._options = self._build_base_options() def", "return os.getcwd() def _load_env(self) -> dict[str, Any]: return { key.removeprefix(self.prefix): value for key,", "\"\"\"Uses an ArgumentParser to populate the CLI options.\"\"\" self._cli_options.update(self.args.parse_args(parser).to_dict()) def get(self, item: str,", "_load_env(self) -> dict[str, Any]: return { key.removeprefix(self.prefix): value for key, value in os.environ.items()", "os.getcwd() def _load_env(self) -> dict[str, Any]: return { key.removeprefix(self.prefix): value for key, value", "Any import os @detect_dependencies class Options(AutoInject): \"\"\"The options object aggregates all options values", "= \"LOGGER_NAME\" def __init__(self): self._cli_options = {} self._env_options = self._load_env() self._options = self._build_base_options()", "= None) -> Any | None: try: return self[item] except KeyError: return default", "= \"CONFIG_FILE\" logger_level_key = \"LOGGER_LEVEL\" logger_name_key = \"LOGGER_NAME\" def __init__(self): self._cli_options = {}", "def _load_env(self) -> dict[str, Any]: return { key.removeprefix(self.prefix): value for key, value in", "options object aggregates all options values that the Bevy.App application pulls in from", "application pulls in from the environment.\"\"\" args: CLIArgs var_prefix = \"BEVY_APP_\" path_key =", "-> bool: return item in (self._cli_options | self._env_options | self._options) @property def cli(self)", "self._cli_options.copy() @property def env(self) -> dict[str, Any]: return self._env_options.copy() def add_using_arg_parser(self, parser: ArgumentParser):", "-> dict[str, Any]: return self._cli_options.copy() @property def env(self) -> dict[str, Any]: return self._env_options.copy()", "to populate the CLI options.\"\"\" self._cli_options.update(self.args.parse_args(parser).to_dict()) def get(self, item: str, default: Any |", "all options values that the Bevy.App application pulls in from the environment.\"\"\" args:", "the CLI options.\"\"\" self._cli_options.update(self.args.parse_args(parser).to_dict()) def get(self, item: str, default: Any | None =", "class Options(AutoInject): \"\"\"The options object aggregates all options values that the Bevy.App application", "KeyError: return default def _build_base_options(self) -> dict[str, Any]: return {self.path_key: self._get_path()} def _get_path(self):", "\"PATH\" config_file_key = \"CONFIG_FILE\" logger_level_key = \"LOGGER_LEVEL\" logger_name_key = \"LOGGER_NAME\" def __init__(self): self._cli_options", "= \"LOGGER_LEVEL\" logger_name_key = \"LOGGER_NAME\" def __init__(self): self._cli_options = {} self._env_options = self._load_env()", "os @detect_dependencies class Options(AutoInject): \"\"\"The options object aggregates all options values that the", "cli(self) -> dict[str, Any]: return self._cli_options.copy() @property def env(self) -> dict[str, Any]: return", "Any | None = None) -> Any | None: try: return self[item] except", "default def _build_base_options(self) -> dict[str, Any]: return {self.path_key: self._get_path()} def _get_path(self): return os.getcwd()", "\"\"\"The options object aggregates all options values that the Bevy.App application pulls in", "if item in self._cli_options: return self._cli_options[item] if item in self._env_options: return self._env_options[item] return", "def get(self, item: str, default: Any | None = None) -> Any |", "from typing import Any import os @detect_dependencies class Options(AutoInject): \"\"\"The options object aggregates", "self[item] except KeyError: return default def _build_base_options(self) -> dict[str, Any]: return {self.path_key: self._get_path()}", "environment.\"\"\" args: CLIArgs var_prefix = \"BEVY_APP_\" path_key = \"PATH\" config_file_key = \"CONFIG_FILE\" logger_level_key", "__contains__(self, item: str) -> bool: return item in (self._cli_options | self._env_options | self._options)", "Any]: return self._cli_options.copy() @property def env(self) -> dict[str, Any]: return self._env_options.copy() def add_using_arg_parser(self,", "-> dict[str, Any]: return self._env_options.copy() def add_using_arg_parser(self, parser: ArgumentParser): \"\"\"Uses an ArgumentParser to", "parser: ArgumentParser): \"\"\"Uses an ArgumentParser to populate the CLI options.\"\"\" self._cli_options.update(self.args.parse_args(parser).to_dict()) def get(self,", "self._load_env() self._options = self._build_base_options() def __getitem__(self, item: str) -> Any: if item in", "item in self._cli_options: return self._cli_options[item] if item in self._env_options: return self._env_options[item] return self._options[item]", "config_file_key = \"CONFIG_FILE\" logger_level_key = \"LOGGER_LEVEL\" logger_name_key = \"LOGGER_NAME\" def __init__(self): self._cli_options =", "ArgumentParser to populate the CLI options.\"\"\" self._cli_options.update(self.args.parse_args(parser).to_dict()) def get(self, item: str, default: Any", "populate the CLI options.\"\"\" self._cli_options.update(self.args.parse_args(parser).to_dict()) def get(self, item: str, default: Any | None", "{self.path_key: self._get_path()} def _get_path(self): return os.getcwd() def _load_env(self) -> dict[str, Any]: return {", "def cli(self) -> dict[str, Any]: return self._cli_options.copy() @property def env(self) -> dict[str, Any]:", "self._get_path()} def _get_path(self): return os.getcwd() def _load_env(self) -> dict[str, Any]: return { key.removeprefix(self.prefix):", "-> Any: if item in self._cli_options: return self._cli_options[item] if item in self._env_options: return", "detect_dependencies from bevy.app.args import ArgumentParser, CLIArgs from typing import Any import os @detect_dependencies", "str) -> Any: if item in self._cli_options: return self._cli_options[item] if item in self._env_options:", "Any]: return {self.path_key: self._get_path()} def _get_path(self): return os.getcwd() def _load_env(self) -> dict[str, Any]:", "values that the Bevy.App application pulls in from the environment.\"\"\" args: CLIArgs var_prefix", "logger_level_key = \"LOGGER_LEVEL\" logger_name_key = \"LOGGER_NAME\" def __init__(self): self._cli_options = {} self._env_options =", "__getitem__(self, item: str) -> Any: if item in self._cli_options: return self._cli_options[item] if item", "def __contains__(self, item: str) -> bool: return item in (self._cli_options | self._env_options |", "CLI options.\"\"\" self._cli_options.update(self.args.parse_args(parser).to_dict()) def get(self, item: str, default: Any | None = None)", "import AutoInject, detect_dependencies from bevy.app.args import ArgumentParser, CLIArgs from typing import Any import", "-> dict[str, Any]: return {self.path_key: self._get_path()} def _get_path(self): return os.getcwd() def _load_env(self) ->", "import ArgumentParser, CLIArgs from typing import Any import os @detect_dependencies class Options(AutoInject): \"\"\"The", "(self._cli_options | self._env_options | self._options) @property def cli(self) -> dict[str, Any]: return self._cli_options.copy()", "def add_using_arg_parser(self, parser: ArgumentParser): \"\"\"Uses an ArgumentParser to populate the CLI options.\"\"\" self._cli_options.update(self.args.parse_args(parser).to_dict())", "return default def _build_base_options(self) -> dict[str, Any]: return {self.path_key: self._get_path()} def _get_path(self): return", "item: str) -> Any: if item in self._cli_options: return self._cli_options[item] if item in", "in self._cli_options: return self._cli_options[item] if item in self._env_options: return self._env_options[item] return self._options[item] def", "\"CONFIG_FILE\" logger_level_key = \"LOGGER_LEVEL\" logger_name_key = \"LOGGER_NAME\" def __init__(self): self._cli_options = {} self._env_options", "\"BEVY_APP_\" path_key = \"PATH\" config_file_key = \"CONFIG_FILE\" logger_level_key = \"LOGGER_LEVEL\" logger_name_key = \"LOGGER_NAME\"", "_build_base_options(self) -> dict[str, Any]: return {self.path_key: self._get_path()} def _get_path(self): return os.getcwd() def _load_env(self)" ]
[ "value in data: if value.split(',')[122] == '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) elif", "value.split(',')[127] == '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) #covid and more specific conditions:", "== '1': COVID_hypertension.append(value) elif value.split(',')[127] == '1' and value.split(',')[150] == '1': COVID_hypertension.append(value) COVID_pulm_disease", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[145] == '1':", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[159] ==", "== '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif", "for value in data: if value.split(',')[122] == '1' and value.split(',')[156] == '1': COVID_diabetes.append(value)", "COVID_adeno = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[132]", "pathologies: COVID_comorbidities = [] for value in data: if value.split(',')[122] == '1' and", "and value.split(',')[167] == '1': COVID_&_vaccines.append(value) #covid and pathologies: COVID_comorbidities = [] for value", "value.split(',')[122] == '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) elif value.split(',')[127] == '1' and", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[154] ==", "== '1': COVID_kawasaki.append(value) COVID_hiv = [] for value in data: if value.split(',')[122] ==", "value.split(',')[148] == '1': COVID_comorbidities.append(value) #covid and more specific conditions: COVID_cardiopathy = [] for", "== '1': COVID_hepB.append(value) COVID_epilepsy = [] for value in data: if value.split(',')[122] ==", "== '1' and value.split(',')[162] == '1': COVID_hiv.append(value) COVID_obesity = [] for value in", "COVID_comorbidities.append(value) #covid and more specific conditions: COVID_cardiopathy = [] for value in data:", "== '1': COVID_vrs.append(value) elif value.split(',')[127] == '1' and value.split(',')[131] == '1': COVID_vrs.append(value) COVID_adeno", "== '1': COVID_immunodeficiency.append(value) elif value.split(',')[127] == '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) COVID_neoplasia", "value.split(',')[167] == '1': COVID_&_vaccines.append(value) #covid and pathologies: COVID_comorbidities = [] for value in", "if value.split(',')[122] == '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) elif value.split(',')[127] == '1'", "elif value.split(',')[127] == '1' and value.split(',')[131] == '1': COVID_vrs.append(value) COVID_adeno = [] for", "'1' and value.split(',')[132] == '1': COVID_adeno.append(value) COVID_fluA&B = [] for value in data:", "COVID_asthma.append(value) elif value.split(',')[127] == '1' and value.split(',')[152] == '1': COVID_asthma.append(value) COVID_nephrology = []", "value in data: if value.split(',')[122] == '1' and value.split(',')[150] == '1': COVID_hypertension.append(value) elif", "and value.split(',')[156] == '1': COVID_diabetes.append(value) COVID_tuberculosis = [] for value in data: if", "value in data: if value.split(',')[122] == '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) elif", "if value.split(',')[122] == '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) elif value.split(',')[127] == '1'", "value.split(',')[153] == '1': COVID_nephrology.append(value) COVID_hepB = [] for value in data: if value.split(',')[122]", "in data: if value.split(',')[122] == '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[127]", "for value in data: if value.split(',')[122] == '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value)", "'1': COVID_bacteria.append(value) COVID_inflam_diseases = [] for value in data: if value.split(',')[122] == '1'", "if value.split(',')[122] == '1' and value.split(',')[152] == '1': COVID_asthma.append(value) elif value.split(',')[127] == '1'", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[153] ==", "value.split(',')[127] == '1' and value.split(',')[162] == '1': COVID_hiv.append(value) COVID_obesity = [] for value", "COVID_comorbidities = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[148]", "value in data: if value.split(',')[122] == '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) elif", "COVID_asthma.append(value) COVID_nephrology = [] for value in data: if value.split(',')[122] == '1' and", "COVID_hiv.append(value) COVID_obesity = [] for value in data: if value.split(',')[122] == '1' and", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[133] == '1':", "value.split(',')[122] == '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) elif value.split(',')[127] == '1' and", "and value.split(',')[160] == '1': COVID_kawasaki.append(value) elif value.split(',')[127] == '1' and value.split(',')[160] == '1':", "'1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) elif value.split(',')[127] == '1' and value.split(',')[151] ==", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[156] == '1':", "COVID_vrs.append(value) COVID_adeno = [] for value in data: if value.split(',')[122] == '1' and", "== '1': COVID_adeno.append(value) COVID_fluA&B = [] for value in data: if value.split(',')[122] ==", "COVID_pulm_disease = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[151]", "and more specific conditions: COVID_cardiopathy = [] for value in data: if value.split(',')[122]", "elif value.split(',')[127] == '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) COVID_hypertension = [] for", "and value.split(',')[132] == '1': COVID_adeno.append(value) elif value.split(',')[127] == '1' and value.split(',')[132] == '1':", "== '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) COVID_diabetes = [] for value in", "and value.split(',')[167] == '1': COVID_&_vaccines.append(value) elif value.split(',')[127] == '1' and value.split(',')[167] == '1':", "COVID_hypertension = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[150]", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[150] ==", "value.split(',')[158] == '1': COVID_immunodeficiency.append(value) COVID_neoplasia = [] for value in data: if value.split(',')[122]", "value.split(',')[160] == '1': COVID_kawasaki.append(value) COVID_hiv = [] for value in data: if value.split(',')[122]", "in data: if value.split(',')[122] == '1' and value.split(',')[145] == '1': COVID_bacteria.append(value) elif value.split(',')[127]", "and other more generically: COVID_resp_vir = [] for value in data: if value.split(',')[122]", "value.split(',')[127] == '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) COVID_&_vaccines = [] for value", "value.split(',')[150] == '1': COVID_hypertension.append(value) elif value.split(',')[127] == '1' and value.split(',')[150] == '1': COVID_hypertension.append(value)", "COVID_nephrology = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[153]", "in data: if value.split(',')[122] == '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) elif value.split(',')[127]", "== '1': COVID_pulm_disease.append(value) elif value.split(',')[127] == '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) COVID_asthma", "in data: if value.split(',')[122] == '1' and value.split(',')[156] == '1': COVID_diabetes.append(value) elif value.split(',')[127]", "value in data: if value.split(',')[122] == '1' and value.split(',')[152] == '1': COVID_asthma.append(value) elif", "value.split(',')[127] == '1' and value.split(',')[132] == '1': COVID_adeno.append(value) COVID_fluA&B = [] for value", "value.split(',')[122] == '1' and value.split(',')[163] == '1': COVID_obesity.append(value) elif value.split(',')[127] == '1' and", "value.split(',')[152] == '1': COVID_asthma.append(value) COVID_nephrology = [] for value in data: if value.split(',')[122]", "value in data: if value.split(',')[122] == '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) elif", "value.split(',')[158] == '1': COVID_immunodeficiency.append(value) elif value.split(',')[127] == '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value)", "and value.split(',')[155] == '1': COVID_epilepsy.append(value) COVID_diabetes = [] for value in data: if", "'1': COVID_comorbidities.append(value) elif value.split(',')[127] == '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) #covid and", "data: if value.split(',')[122] == '1' and value.split(',')[131] == '1': COVID_vrs.append(value) elif value.split(',')[127] ==", "== '1' and value.split(',')[152] == '1': COVID_asthma.append(value) elif value.split(',')[127] == '1' and value.split(',')[152]", "value.split(',')[127] == '1' and value.split(',')[156] == '1': COVID_diabetes.append(value) COVID_tuberculosis = [] for value", "value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value)", "elif value.split(',')[127] == '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) COVID_neoplasia = [] for", "'1': COVID_hiv.append(value) elif value.split(',')[127] == '1' and value.split(',')[162] == '1': COVID_hiv.append(value) COVID_obesity =", "value.split(',')[132] == '1': COVID_adeno.append(value) COVID_fluA&B = [] for value in data: if value.split(',')[122]", "for value in data: if value.split(',')[122] == '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value)", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[157] ==", "value.split(',')[127] == '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) COVID_bacteria = [] for value", "for value in data: if value.split(',')[122] == '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value)", "illnesses: COVID_vrs = [] for value in data: if value.split(',')[122] == '1' and", "data: if value.split(',')[122] == '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) elif value.split(',')[127] ==", "and value.split(',')[142] == '1': COVID_resp_vir.append(value) elif value.split(',')[127] == '1' and value.split(',')[142] == '1':", "and value.split(',')[153] == '1': COVID_nephrology.append(value) COVID_hepB = [] for value in data: if", "'1': COVID_vrs.append(value) COVID_adeno = [] for value in data: if value.split(',')[122] == '1'", "value.split(',')[167] == '1': COVID_&_vaccines.append(value) elif value.split(',')[127] == '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value)", "value.split(',')[153] == '1': COVID_nephrology.append(value) elif value.split(',')[127] == '1' and value.split(',')[153] == '1': COVID_nephrology.append(value)", "'1': COVID_asthma.append(value) elif value.split(',')[127] == '1' and value.split(',')[152] == '1': COVID_asthma.append(value) COVID_nephrology =", "data: if value.split(',')[122] == '1' and value.split(',')[145] == '1': COVID_bacteria.append(value) elif value.split(',')[127] ==", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[161] == '1':", "elif value.split(',')[127] == '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) COVID_hiv = [] for", "'1': COVID_nephrology.append(value) elif value.split(',')[127] == '1' and value.split(',')[153] == '1': COVID_nephrology.append(value) COVID_hepB =", "value in data: if value.split(',')[122] == '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) elif", "'1' and value.split(',')[145] == '1': COVID_bacteria.append(value) elif value.split(',')[127] == '1' and value.split(',')[145] ==", "value.split(',')[162] == '1': COVID_hiv.append(value) elif value.split(',')[127] == '1' and value.split(',')[162] == '1': COVID_hiv.append(value)", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[163] == '1':", "'1' and value.split(',')[153] == '1': COVID_nephrology.append(value) COVID_hepB = [] for value in data:", "== '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) elif value.split(',')[127] == '1' and value.split(',')[155]", "value.split(',')[122] == '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) elif value.split(',')[127] == '1' and", "== '1' and value.split(',')[132] == '1': COVID_adeno.append(value) COVID_fluA&B = [] for value in", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[151] == '1':", "'1' and value.split(',')[156] == '1': COVID_diabetes.append(value) elif value.split(',')[127] == '1' and value.split(',')[156] ==", "== '1': COVID_bacteria.append(value) COVID_inflam_diseases = [] for value in data: if value.split(',')[122] ==", "#covid and other illnesses: COVID_vrs = [] for value in data: if value.split(',')[122]", "'1': COVID_hepB.append(value) elif value.split(',')[127] == '1' and value.split(',')[154] == '1': COVID_hepB.append(value) COVID_epilepsy =", "value.split(',')[122] == '1' and value.split(',')[132] == '1': COVID_adeno.append(value) elif value.split(',')[127] == '1' and", "if value.split(',')[122] == '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) elif value.split(',')[127] == '1'", "value.split(',')[127] == '1' and value.split(',')[154] == '1': COVID_hepB.append(value) COVID_epilepsy = [] for value", "and other illnesses: COVID_vrs = [] for value in data: if value.split(',')[122] ==", "value.split(',')[156] == '1': COVID_diabetes.append(value) elif value.split(',')[127] == '1' and value.split(',')[156] == '1': COVID_diabetes.append(value)", "COVID_inflam_diseases.append(value) elif value.split(',')[127] == '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) COVID_&_vaccines = []", "== '1': COVID_cardiopathy.append(value) COVID_hypertension = [] for value in data: if value.split(',')[122] ==", "'1': COVID_&_vaccines.append(value) #covid and pathologies: COVID_comorbidities = [] for value in data: if", "== '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) #covid and pathologies: COVID_comorbidities = []", "== '1' and value.split(',')[163] == '1': COVID_obesity.append(value) elif value.split(',')[127] == '1' and value.split(',')[163]", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[167] == '1':", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[163] ==", "and value.split(',')[152] == '1': COVID_asthma.append(value) COVID_nephrology = [] for value in data: if", "'1': COVID_asthma.append(value) COVID_nephrology = [] for value in data: if value.split(',')[122] == '1'", "and value.split(',')[132] == '1': COVID_adeno.append(value) COVID_fluA&B = [] for value in data: if", "COVID_fluA&B.append(value) elif value.split(',')[122] == '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] ==", "'1' and value.split(',')[152] == '1': COVID_asthma.append(value) elif value.split(',')[127] == '1' and value.split(',')[152] ==", "== '1': COVID_hepB.append(value) elif value.split(',')[127] == '1' and value.split(',')[154] == '1': COVID_hepB.append(value) COVID_epilepsy", "and value.split(',')[134] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[134] == '1':", "for value in data: if value.split(',')[122] == '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value)", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[156] ==", "'1' and value.split(',')[154] == '1': COVID_hepB.append(value) elif value.split(',')[127] == '1' and value.split(',')[154] ==", "== '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) elif value.split(',')[127] == '1' and value.split(',')[158]", "value.split(',')[159] == '1': COVID_neoplasia.append(value) elif value.split(',')[127] == '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value)", "and value.split(',')[150] == '1': COVID_hypertension.append(value) elif value.split(',')[127] == '1' and value.split(',')[150] == '1':", "== '1' and value.split(',')[145] == '1': COVID_bacteria.append(value) COVID_inflam_diseases = [] for value in", "and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[133] == '1':", "'1' and value.split(',')[131] == '1': COVID_vrs.append(value) COVID_adeno = [] for value in data:", "COVID_hypertension.append(value) elif value.split(',')[127] == '1' and value.split(',')[150] == '1': COVID_hypertension.append(value) COVID_pulm_disease = []", "if value.split(',')[122] == '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) elif value.split(',')[127] == '1'", "value.split(',')[122] == '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and", "== '1': COVID_hiv.append(value) elif value.split(',')[127] == '1' and value.split(',')[162] == '1': COVID_hiv.append(value) COVID_obesity", "and value.split(',')[155] == '1': COVID_epilepsy.append(value) elif value.split(',')[127] == '1' and value.split(',')[155] == '1':", "COVID_epilepsy.append(value) elif value.split(',')[127] == '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) COVID_diabetes = []", "value.split(',')[132] == '1': COVID_adeno.append(value) elif value.split(',')[127] == '1' and value.split(',')[132] == '1': COVID_adeno.append(value)", "value.split(',')[127] == '1' and value.split(',')[152] == '1': COVID_asthma.append(value) COVID_nephrology = [] for value", "value in data: if value.split(',')[122] == '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif", "elif value.split(',')[127] == '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) COVID_&_vaccines = [] for", "value.split(',')[122] == '1' and value.split(',')[154] == '1': COVID_hepB.append(value) elif value.split(',')[127] == '1' and", "data: if value.split(',')[122] == '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] ==", "'1': COVID_diabetes.append(value) COVID_tuberculosis = [] for value in data: if value.split(',')[122] == '1'", "== '1': COVID_inflam_diseases.append(value) elif value.split(',')[127] == '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) COVID_&_vaccines", "data: if value.split(',')[122] == '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) elif value.split(',')[127] ==", "for value in data: if value.split(',')[122] == '1' and value.split(',')[131] == '1': COVID_vrs.append(value)", "== '1': COVID_resp_vir.append(value) elif value.split(',')[127] == '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) COVID_bacteria", "== '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) COVID_hypertension = [] for value in", "== '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) COVID_bacteria = [] for value in", "in data: if value.split(',')[122] == '1' and value.split(',')[153] == '1': COVID_nephrology.append(value) elif value.split(',')[127]", "== '1' and value.split(',')[150] == '1': COVID_hypertension.append(value) COVID_pulm_disease = [] for value in", "other illnesses: COVID_vrs = [] for value in data: if value.split(',')[122] == '1'", "and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) COVID_neoplasia = [] for value in data: if", "and value.split(',')[162] == '1': COVID_hiv.append(value) COVID_obesity = [] for value in data: if", "COVID_hypertension.append(value) COVID_pulm_disease = [] for value in data: if value.split(',')[122] == '1' and", "== '1': COVID_kawasaki.append(value) elif value.split(',')[127] == '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) COVID_hiv", "data: if value.split(',')[122] == '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) elif value.split(',')[127] ==", "and value.split(',')[131] == '1': COVID_vrs.append(value) elif value.split(',')[127] == '1' and value.split(',')[131] == '1':", "'1': COVID_fluA&B.append(value) #covid and other more generically: COVID_resp_vir = [] for value in", "== '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[122] == '1' and value.split(',')[134]", "== '1' and value.split(',')[145] == '1': COVID_bacteria.append(value) elif value.split(',')[127] == '1' and value.split(',')[145]", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[159] == '1':", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[152] == '1':", "COVID_neoplasia.append(value) COVID_kawasaki = [] for value in data: if value.split(',')[122] == '1' and", "and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) elif value.split(',')[127] == '1' and value.split(',')[161] == '1':", "'1': COVID_epilepsy.append(value) elif value.split(',')[127] == '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) COVID_diabetes =", "'1' and value.split(',')[163] == '1': COVID_obesity.append(value) elif value.split(',')[127] == '1' and value.split(',')[163] ==", "if value.split(',')[122] == '1' and value.split(',')[154] == '1': COVID_hepB.append(value) elif value.split(',')[127] == '1'", "COVID_fluA&B = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[133]", "and value.split(',')[131] == '1': COVID_vrs.append(value) COVID_adeno = [] for value in data: if", "COVID_tuberculosis.append(value) COVID_immunodeficiency = [] for value in data: if value.split(',')[122] == '1' and", "value.split(',')[127] == '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) #covid and other more generically:", "elif value.split(',')[122] == '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1'", "COVID_diabetes.append(value) COVID_tuberculosis = [] for value in data: if value.split(',')[122] == '1' and", "'1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) elif value.split(',')[127] == '1' and value.split(',')[158] ==", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[167] ==", "== '1': COVID_fluA&B.append(value) #covid and other more generically: COVID_resp_vir = [] for value", "== '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) #covid and more specific conditions: COVID_cardiopathy", "'1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) COVID_diabetes = [] for value in data:", "(\"./Files/COPEDICATClinicSympt_DATA_2020-12-17_1642.csv\", 'r') data = [] for line in f: data.append(line) #covid and other", "data: if value.split(',')[122] == '1' and value.split(',')[156] == '1': COVID_diabetes.append(value) elif value.split(',')[127] ==", "COVID_tuberculosis = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[157]", "'1': COVID_cardiopathy.append(value) COVID_hypertension = [] for value in data: if value.split(',')[122] == '1'", "elif value.split(',')[127] == '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) #covid and pathologies: COVID_comorbidities", "for value in data: if value.split(',')[122] == '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value)", "'1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) #covid and", "== '1' and value.split(',')[150] == '1': COVID_hypertension.append(value) elif value.split(',')[127] == '1' and value.split(',')[150]", "== '1' and value.split(',')[156] == '1': COVID_diabetes.append(value) elif value.split(',')[127] == '1' and value.split(',')[156]", "value.split(',')[122] == '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) elif value.split(',')[127] == '1' and", "COVID_kawasaki.append(value) COVID_hiv = [] for value in data: if value.split(',')[122] == '1' and", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[149] ==", "== '1': COVID_pulm_disease.append(value) COVID_asthma = [] for value in data: if value.split(',')[122] ==", "and value.split(',')[134] == '1': COVID_fluA&B.append(value) #covid and other more generically: COVID_resp_vir = []", "'1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) elif value.split(',')[127] == '1' and value.split(',')[142] ==", "value in data: if value.split(',')[122] == '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) elif", "== '1': COVID_adeno.append(value) elif value.split(',')[127] == '1' and value.split(',')[132] == '1': COVID_adeno.append(value) COVID_fluA&B", "== '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) elif value.split(',')[127] == '1' and value.split(',')[149]", "'1' and value.split(',')[132] == '1': COVID_adeno.append(value) elif value.split(',')[127] == '1' and value.split(',')[132] ==", "== '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) elif value.split(',')[127] == '1' and value.split(',')[148]", "for value in data: if value.split(',')[122] == '1' and value.split(',')[154] == '1': COVID_hepB.append(value)", "'1': COVID_hiv.append(value) COVID_obesity = [] for value in data: if value.split(',')[122] == '1'", "'1' and value.split(',')[131] == '1': COVID_vrs.append(value) elif value.split(',')[127] == '1' and value.split(',')[131] ==", "value.split(',')[149] == '1': COVID_cardiopathy.append(value) COVID_hypertension = [] for value in data: if value.split(',')[122]", "in data: if value.split(',')[122] == '1' and value.split(',')[152] == '1': COVID_asthma.append(value) elif value.split(',')[127]", "value.split(',')[127] == '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) COVID_diabetes = [] for value", "if value.split(',')[122] == '1' and value.split(',')[153] == '1': COVID_nephrology.append(value) elif value.split(',')[127] == '1'", "value in data: if value.split(',')[122] == '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) elif", "'1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) elif value.split(',')[127] == '1' and value.split(',')[161] ==", "value.split(',')[157] == '1': COVID_tuberculosis.append(value) COVID_immunodeficiency = [] for value in data: if value.split(',')[122]", "== '1': COVID_hiv.append(value) COVID_obesity = [] for value in data: if value.split(',')[122] ==", "'1': COVID_&_vaccines.append(value) elif value.split(',')[127] == '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) #covid and", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[152] ==", "value.split(',')[127] == '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[122] == '1' and", "value in data: if value.split(',')[122] == '1' and value.split(',')[132] == '1': COVID_adeno.append(value) elif", "for value in data: if value.split(',')[122] == '1' and value.split(',')[132] == '1': COVID_adeno.append(value)", "for value in data: if value.split(',')[122] == '1' and value.split(',')[152] == '1': COVID_asthma.append(value)", "== '1': COVID_diabetes.append(value) COVID_tuberculosis = [] for value in data: if value.split(',')[122] ==", "'1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) COVID_neoplasia = [] for value in data:", "== '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) COVID_neoplasia = [] for value in", "'r') data = [] for line in f: data.append(line) #covid and other illnesses:", "if value.split(',')[122] == '1' and value.split(',')[162] == '1': COVID_hiv.append(value) elif value.split(',')[127] == '1'", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[131] == '1':", "in data: if value.split(',')[122] == '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) elif value.split(',')[127]", "== '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) elif value.split(',')[127] == '1' and value.split(',')[167]", "for value in data: if value.split(',')[122] == '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value)", "if value.split(',')[122] == '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) elif value.split(',')[127] == '1'", "value.split(',')[131] == '1': COVID_vrs.append(value) elif value.split(',')[127] == '1' and value.split(',')[131] == '1': COVID_vrs.append(value)", "== '1': COVID_resp_vir.append(value) COVID_bacteria = [] for value in data: if value.split(',')[122] ==", "== '1': COVID_hypertension.append(value) COVID_pulm_disease = [] for value in data: if value.split(',')[122] ==", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[148] == '1':", "COVID_pulm_disease.append(value) elif value.split(',')[127] == '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) COVID_asthma = []", "value.split(',')[127] == '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) #covid and pathologies: COVID_comorbidities =", "if value.split(',')[122] == '1' and value.split(',')[163] == '1': COVID_obesity.append(value) elif value.split(',')[127] == '1'", "COVID_fluA&B.append(value) #covid and other more generically: COVID_resp_vir = [] for value in data:", "in data: if value.split(',')[122] == '1' and value.split(',')[150] == '1': COVID_hypertension.append(value) elif value.split(',')[127]", "value.split(',')[134] == '1': COVID_fluA&B.append(value) #covid and other more generically: COVID_resp_vir = [] for", "== '1': COVID_asthma.append(value) elif value.split(',')[127] == '1' and value.split(',')[152] == '1': COVID_asthma.append(value) COVID_nephrology", "more generically: COVID_resp_vir = [] for value in data: if value.split(',')[122] == '1'", "'1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) COVID_bacteria = [] for value in data:", "'1': COVID_immunodeficiency.append(value) COVID_neoplasia = [] for value in data: if value.split(',')[122] == '1'", "'1': COVID_hypertension.append(value) COVID_pulm_disease = [] for value in data: if value.split(',')[122] == '1'", "value.split(',')[145] == '1': COVID_bacteria.append(value) elif value.split(',')[127] == '1' and value.split(',')[145] == '1': COVID_bacteria.append(value)", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[132] ==", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[142] ==", "'1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) COVID_&_vaccines = [] for value in data:", "'1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) elif value.split(',')[127] == '1' and value.split(',')[157] ==", "== '1' and value.split(',')[152] == '1': COVID_asthma.append(value) COVID_nephrology = [] for value in", "== '1': COVID_bacteria.append(value) elif value.split(',')[127] == '1' and value.split(',')[145] == '1': COVID_bacteria.append(value) COVID_inflam_diseases", "elif value.split(',')[127] == '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) #covid and other more", "value.split(',')[127] == '1' and value.split(',')[131] == '1': COVID_vrs.append(value) COVID_adeno = [] for value", "'1': COVID_cardiopathy.append(value) elif value.split(',')[127] == '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) COVID_hypertension =", "elif value.split(',')[127] == '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) #covid and more specific", "== '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) COVID_asthma = [] for value in", "== '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) elif value.split(',')[127] == '1' and value.split(',')[160]", "== '1': COVID_nephrology.append(value) COVID_hepB = [] for value in data: if value.split(',')[122] ==", "'1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) COVID_kawasaki = [] for value in data:", "in data: if value.split(',')[122] == '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) elif value.split(',')[127]", "data: if value.split(',')[122] == '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) elif value.split(',')[127] ==", "COVID_adeno.append(value) COVID_fluA&B = [] for value in data: if value.split(',')[122] == '1' and", "COVID_epilepsy = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[155]", "value in data: if value.split(',')[122] == '1' and value.split(',')[131] == '1': COVID_vrs.append(value) elif", "COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[122] ==", "open (\"./Files/COPEDICATClinicSympt_DATA_2020-12-17_1642.csv\", 'r') data = [] for line in f: data.append(line) #covid and", "value.split(',')[160] == '1': COVID_kawasaki.append(value) elif value.split(',')[127] == '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value)", "COVID_&_vaccines.append(value) #covid and pathologies: COVID_comorbidities = [] for value in data: if value.split(',')[122]", "if value.split(',')[122] == '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) elif value.split(',')[127] == '1'", "== '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) #covid and other more generically: COVID_resp_vir", "'1': COVID_inflam_diseases.append(value) COVID_&_vaccines = [] for value in data: if value.split(',')[122] == '1'", "value.split(',')[122] == '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) elif value.split(',')[127] == '1' and", "value.split(',')[163] == '1': COVID_obesity.append(value) elif value.split(',')[127] == '1' and value.split(',')[163] == '1': COVID_obesity.append(value)", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[153] == '1':", "for value in data: if value.split(',')[122] == '1' and value.split(',')[150] == '1': COVID_hypertension.append(value)", "and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) COVID_&_vaccines = [] for value in data: if", "'1': COVID_fluA&B.append(value) elif value.split(',')[122] == '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) elif value.split(',')[127]", "value.split(',')[161] == '1': COVID_inflam_diseases.append(value) COVID_&_vaccines = [] for value in data: if value.split(',')[122]", "== '1' and value.split(',')[153] == '1': COVID_nephrology.append(value) COVID_hepB = [] for value in", "elif value.split(',')[127] == '1' and value.split(',')[156] == '1': COVID_diabetes.append(value) COVID_tuberculosis = [] for", "data: if value.split(',')[122] == '1' and value.split(',')[132] == '1': COVID_adeno.append(value) elif value.split(',')[127] ==", "COVID_hiv = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[162]", "COVID_bacteria.append(value) elif value.split(',')[127] == '1' and value.split(',')[145] == '1': COVID_bacteria.append(value) COVID_inflam_diseases = []", "COVID_kawasaki.append(value) elif value.split(',')[127] == '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) COVID_hiv = []", "in data: if value.split(',')[122] == '1' and value.split(',')[162] == '1': COVID_hiv.append(value) elif value.split(',')[127]", "COVID_hepB.append(value) COVID_epilepsy = [] for value in data: if value.split(',')[122] == '1' and", "'1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) elif value.split(',')[127] == '1' and value.split(',')[160] ==", "'1': COVID_tuberculosis.append(value) COVID_immunodeficiency = [] for value in data: if value.split(',')[122] == '1'", "in data: if value.split(',')[122] == '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) elif value.split(',')[127]", "== '1': COVID_neoplasia.append(value) COVID_kawasaki = [] for value in data: if value.split(',')[122] ==", "more specific conditions: COVID_cardiopathy = [] for value in data: if value.split(',')[122] ==", "and value.split(',')[154] == '1': COVID_hepB.append(value) elif value.split(',')[127] == '1' and value.split(',')[154] == '1':", "= open (\"./Files/COPEDICATClinicSympt_DATA_2020-12-17_1642.csv\", 'r') data = [] for line in f: data.append(line) #covid", "and value.split(',')[145] == '1': COVID_bacteria.append(value) COVID_inflam_diseases = [] for value in data: if", "for value in data: if value.split(',')[122] == '1' and value.split(',')[163] == '1': COVID_obesity.append(value)", "'1' and value.split(',')[156] == '1': COVID_diabetes.append(value) COVID_tuberculosis = [] for value in data:", "COVID_hiv.append(value) elif value.split(',')[127] == '1' and value.split(',')[162] == '1': COVID_hiv.append(value) COVID_obesity = []", "value.split(',')[122] == '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) elif value.split(',')[127] == '1' and", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[149] == '1':", "value.split(',')[149] == '1': COVID_cardiopathy.append(value) elif value.split(',')[127] == '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value)", "and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[122] == '1' and value.split(',')[134] == '1':", "COVID_resp_vir.append(value) COVID_bacteria = [] for value in data: if value.split(',')[122] == '1' and", "'1': COVID_immunodeficiency.append(value) elif value.split(',')[127] == '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) COVID_neoplasia =", "for value in data: if value.split(',')[122] == '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value)", "value in data: if value.split(',')[122] == '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) elif", "COVID_obesity = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[163]", "and value.split(',')[151] == '1': COVID_pulm_disease.append(value) COVID_asthma = [] for value in data: if", "elif value.split(',')[127] == '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) COVID_kawasaki = [] for", "for value in data: if value.split(',')[122] == '1' and value.split(',')[153] == '1': COVID_nephrology.append(value)", "'1': COVID_neoplasia.append(value) COVID_kawasaki = [] for value in data: if value.split(',')[122] == '1'", "value.split(',')[122] == '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) elif value.split(',')[127] == '1' and", "'1': COVID_epilepsy.append(value) COVID_diabetes = [] for value in data: if value.split(',')[122] == '1'", "value.split(',')[127] == '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) COVID_immunodeficiency = [] for value", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[160] == '1':", "and value.split(',')[149] == '1': COVID_cardiopathy.append(value) elif value.split(',')[127] == '1' and value.split(',')[149] == '1':", "'1': COVID_comorbidities.append(value) #covid and more specific conditions: COVID_cardiopathy = [] for value in", "COVID_nephrology.append(value) elif value.split(',')[127] == '1' and value.split(',')[153] == '1': COVID_nephrology.append(value) COVID_hepB = []", "if value.split(',')[122] == '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) elif value.split(',')[127] == '1'", "value in data: if value.split(',')[122] == '1' and value.split(',')[163] == '1': COVID_obesity.append(value) elif", "COVID_immunodeficiency = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[158]", "COVID_asthma = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[152]", "in data: if value.split(',')[122] == '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) elif value.split(',')[127]", "== '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) elif value.split(',')[127] == '1' and value.split(',')[157]", "COVID_cardiopathy = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[149]", "COVID_neoplasia.append(value) elif value.split(',')[127] == '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) COVID_kawasaki = []", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[150] == '1':", "and value.split(',')[154] == '1': COVID_hepB.append(value) COVID_epilepsy = [] for value in data: if", "'1': COVID_kawasaki.append(value) COVID_hiv = [] for value in data: if value.split(',')[122] == '1'", "data: if value.split(',')[122] == '1' and value.split(',')[154] == '1': COVID_hepB.append(value) elif value.split(',')[127] ==", "== '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) #covid", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[133] ==", "'1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) COVID_asthma = [] for value in data:", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[154] == '1':", "for value in data: if value.split(',')[122] == '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value)", "== '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) COVID_hiv = [] for value in", "in data: if value.split(',')[122] == '1' and value.split(',')[132] == '1': COVID_adeno.append(value) elif value.split(',')[127]", "COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) #covid and other", "'1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) elif value.split(',')[127] == '1' and value.split(',')[149] ==", "specific conditions: COVID_cardiopathy = [] for value in data: if value.split(',')[122] == '1'", "value.split(',')[151] == '1': COVID_pulm_disease.append(value) COVID_asthma = [] for value in data: if value.split(',')[122]", "value.split(',')[122] == '1' and value.split(',')[162] == '1': COVID_hiv.append(value) elif value.split(',')[127] == '1' and", "data: if value.split(',')[122] == '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) elif value.split(',')[127] ==", "value.split(',')[122] == '1' and value.split(',')[131] == '1': COVID_vrs.append(value) elif value.split(',')[127] == '1' and", "COVID_nephrology.append(value) COVID_hepB = [] for value in data: if value.split(',')[122] == '1' and", "and value.split(',')[145] == '1': COVID_bacteria.append(value) elif value.split(',')[127] == '1' and value.split(',')[145] == '1':", "and value.split(',')[163] == '1': COVID_obesity.append(value) elif value.split(',')[127] == '1' and value.split(',')[163] == '1':", "value in data: if value.split(',')[122] == '1' and value.split(',')[153] == '1': COVID_nephrology.append(value) elif", "'1': COVID_pulm_disease.append(value) COVID_asthma = [] for value in data: if value.split(',')[122] == '1'", "in data: if value.split(',')[122] == '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) elif value.split(',')[127]", "'1': COVID_nephrology.append(value) COVID_hepB = [] for value in data: if value.split(',')[122] == '1'", "== '1': COVID_comorbidities.append(value) elif value.split(',')[127] == '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) #covid", "== '1': COVID_epilepsy.append(value) COVID_diabetes = [] for value in data: if value.split(',')[122] ==", "value.split(',')[127] == '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) COVID_neoplasia = [] for value", "data: if value.split(',')[122] == '1' and value.split(',')[163] == '1': COVID_obesity.append(value) elif value.split(',')[127] ==", "if value.split(',')[122] == '1' and value.split(',')[150] == '1': COVID_hypertension.append(value) elif value.split(',')[127] == '1'", "in data: if value.split(',')[122] == '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) elif value.split(',')[127]", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[155] ==", "and value.split(',')[157] == '1': COVID_tuberculosis.append(value) elif value.split(',')[127] == '1' and value.split(',')[157] == '1':", "== '1' and value.split(',')[131] == '1': COVID_vrs.append(value) COVID_adeno = [] for value in", "COVID_inflam_diseases = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[161]", "line in f: data.append(line) #covid and other illnesses: COVID_vrs = [] for value", "value.split(',')[152] == '1': COVID_asthma.append(value) elif value.split(',')[127] == '1' and value.split(',')[152] == '1': COVID_asthma.append(value)", "for value in data: if value.split(',')[122] == '1' and value.split(',')[145] == '1': COVID_bacteria.append(value)", "and value.split(',')[148] == '1': COVID_comorbidities.append(value) elif value.split(',')[127] == '1' and value.split(',')[148] == '1':", "if value.split(',')[122] == '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) elif value.split(',')[127] == '1'", "in data: if value.split(',')[122] == '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) elif value.split(',')[127]", "value.split(',')[154] == '1': COVID_hepB.append(value) elif value.split(',')[127] == '1' and value.split(',')[154] == '1': COVID_hepB.append(value)", "COVID_cardiopathy.append(value) COVID_hypertension = [] for value in data: if value.split(',')[122] == '1' and", "data: if value.split(',')[122] == '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) elif value.split(',')[127] ==", "'1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[122] == '1' and value.split(',')[134] ==", "== '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) COVID_&_vaccines = [] for value in", "for value in data: if value.split(',')[122] == '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value)", "'1' and value.split(',')[152] == '1': COVID_asthma.append(value) COVID_nephrology = [] for value in data:", "== '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) COVID_immunodeficiency = [] for value in", "value in data: if value.split(',')[122] == '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) elif", "COVID_inflam_diseases.append(value) COVID_&_vaccines = [] for value in data: if value.split(',')[122] == '1' and", "== '1': COVID_immunodeficiency.append(value) COVID_neoplasia = [] for value in data: if value.split(',')[122] ==", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[158] == '1':", "and value.split(',')[142] == '1': COVID_resp_vir.append(value) COVID_bacteria = [] for value in data: if", "value.split(',')[122] == '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) elif value.split(',')[127] == '1' and", "elif value.split(',')[127] == '1' and value.split(',')[132] == '1': COVID_adeno.append(value) COVID_fluA&B = [] for", "value.split(',')[127] == '1' and value.split(',')[153] == '1': COVID_nephrology.append(value) COVID_hepB = [] for value", "for value in data: if value.split(',')[122] == '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value)", "'1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) #covid and other more generically: COVID_resp_vir =", "and value.split(',')[151] == '1': COVID_pulm_disease.append(value) elif value.split(',')[127] == '1' and value.split(',')[151] == '1':", "'1': COVID_bacteria.append(value) elif value.split(',')[127] == '1' and value.split(',')[145] == '1': COVID_bacteria.append(value) COVID_inflam_diseases =", "'1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) #covid and more specific conditions: COVID_cardiopathy =", "value.split(',')[122] == '1' and value.split(',')[152] == '1': COVID_asthma.append(value) elif value.split(',')[127] == '1' and", "data = [] for line in f: data.append(line) #covid and other illnesses: COVID_vrs", "elif value.split(',')[127] == '1' and value.split(',')[154] == '1': COVID_hepB.append(value) COVID_epilepsy = [] for", "'1' and value.split(',')[162] == '1': COVID_hiv.append(value) COVID_obesity = [] for value in data:", "'1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) elif value.split(',')[127] == '1' and value.split(',')[159] ==", "in data: if value.split(',')[122] == '1' and value.split(',')[154] == '1': COVID_hepB.append(value) elif value.split(',')[127]", "elif value.split(',')[127] == '1' and value.split(',')[153] == '1': COVID_nephrology.append(value) COVID_hepB = [] for", "COVID_immunodeficiency.append(value) COVID_neoplasia = [] for value in data: if value.split(',')[122] == '1' and", "elif value.split(',')[127] == '1' and value.split(',')[145] == '1': COVID_bacteria.append(value) COVID_inflam_diseases = [] for", "'1': COVID_hepB.append(value) COVID_epilepsy = [] for value in data: if value.split(',')[122] == '1'", "'1' and value.split(',')[154] == '1': COVID_hepB.append(value) COVID_epilepsy = [] for value in data:", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[131] ==", "COVID_bacteria.append(value) COVID_inflam_diseases = [] for value in data: if value.split(',')[122] == '1' and", "== '1': COVID_diabetes.append(value) elif value.split(',')[127] == '1' and value.split(',')[156] == '1': COVID_diabetes.append(value) COVID_tuberculosis", "value.split(',')[127] == '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) COVID_asthma = [] for value", "value.split(',')[122] == '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) elif value.split(',')[127] == '1' and", "= [] for line in f: data.append(line) #covid and other illnesses: COVID_vrs =", "value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[122] == '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value)", "value.split(',')[150] == '1': COVID_hypertension.append(value) COVID_pulm_disease = [] for value in data: if value.split(',')[122]", "if value.split(',')[122] == '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) elif value.split(',')[127] == '1'", "value in data: if value.split(',')[122] == '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) elif", "COVID_resp_vir.append(value) elif value.split(',')[127] == '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) COVID_bacteria = []", "in data: if value.split(',')[122] == '1' and value.split(',')[131] == '1': COVID_vrs.append(value) elif value.split(',')[127]", "elif value.split(',')[127] == '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[122] == '1'", "value in data: if value.split(',')[122] == '1' and value.split(',')[145] == '1': COVID_bacteria.append(value) elif", "== '1' and value.split(',')[156] == '1': COVID_diabetes.append(value) COVID_tuberculosis = [] for value in", "if value.split(',')[122] == '1' and value.split(',')[132] == '1': COVID_adeno.append(value) elif value.split(',')[127] == '1'", "COVID_immunodeficiency.append(value) elif value.split(',')[127] == '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) COVID_neoplasia = []", "== '1' and value.split(',')[153] == '1': COVID_nephrology.append(value) elif value.split(',')[127] == '1' and value.split(',')[153]", "data: if value.split(',')[122] == '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) elif value.split(',')[127] ==", "data: if value.split(',')[122] == '1' and value.split(',')[150] == '1': COVID_hypertension.append(value) elif value.split(',')[127] ==", "value.split(',')[122] == '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and", "value.split(',')[127] == '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) COVID_kawasaki = [] for value", "elif value.split(',')[127] == '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) COVID_immunodeficiency = [] for", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[162] == '1':", "== '1': COVID_&_vaccines.append(value) elif value.split(',')[127] == '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) #covid", "== '1' and value.split(',')[154] == '1': COVID_hepB.append(value) COVID_epilepsy = [] for value in", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[151] ==", "'1' and value.split(',')[162] == '1': COVID_hiv.append(value) elif value.split(',')[127] == '1' and value.split(',')[162] ==", "data: if value.split(',')[122] == '1' and value.split(',')[162] == '1': COVID_hiv.append(value) elif value.split(',')[127] ==", "elif value.split(',')[127] == '1' and value.split(',')[162] == '1': COVID_hiv.append(value) COVID_obesity = [] for", "[] for line in f: data.append(line) #covid and other illnesses: COVID_vrs = []", "data: if value.split(',')[122] == '1' and value.split(',')[152] == '1': COVID_asthma.append(value) elif value.split(',')[127] ==", "value.split(',')[148] == '1': COVID_comorbidities.append(value) elif value.split(',')[127] == '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value)", "for value in data: if value.split(',')[122] == '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value)", "'1': COVID_neoplasia.append(value) elif value.split(',')[127] == '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) COVID_kawasaki =", "value.split(',')[151] == '1': COVID_pulm_disease.append(value) elif value.split(',')[127] == '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value)", "elif value.split(',')[127] == '1' and value.split(',')[152] == '1': COVID_asthma.append(value) COVID_nephrology = [] for", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[160] ==", "'1': COVID_tuberculosis.append(value) elif value.split(',')[127] == '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) COVID_immunodeficiency =", "value.split(',')[131] == '1': COVID_vrs.append(value) COVID_adeno = [] for value in data: if value.split(',')[122]", "f: data.append(line) #covid and other illnesses: COVID_vrs = [] for value in data:", "COVID_vrs.append(value) elif value.split(',')[127] == '1' and value.split(',')[131] == '1': COVID_vrs.append(value) COVID_adeno = []", "'1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[133] ==", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[132] == '1':", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[148] ==", "value.split(',')[162] == '1': COVID_hiv.append(value) COVID_obesity = [] for value in data: if value.split(',')[122]", "'1': COVID_vrs.append(value) elif value.split(',')[127] == '1' and value.split(',')[131] == '1': COVID_vrs.append(value) COVID_adeno =", "== '1': COVID_nephrology.append(value) elif value.split(',')[127] == '1' and value.split(',')[153] == '1': COVID_nephrology.append(value) COVID_hepB", "== '1': COVID_inflam_diseases.append(value) COVID_&_vaccines = [] for value in data: if value.split(',')[122] ==", "data: if value.split(',')[122] == '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) elif value.split(',')[127] ==", "== '1': COVID_epilepsy.append(value) elif value.split(',')[127] == '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) COVID_diabetes", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[157] == '1':", "value.split(',')[155] == '1': COVID_epilepsy.append(value) elif value.split(',')[127] == '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value)", "and value.split(',')[153] == '1': COVID_nephrology.append(value) elif value.split(',')[127] == '1' and value.split(',')[153] == '1':", "== '1': COVID_fluA&B.append(value) elif value.split(',')[122] == '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) elif", "COVID_comorbidities.append(value) elif value.split(',')[127] == '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) #covid and more", "'1': COVID_resp_vir.append(value) COVID_bacteria = [] for value in data: if value.split(',')[122] == '1'", "== '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) elif value.split(',')[127] == '1' and value.split(',')[161]", "in data: if value.split(',')[122] == '1' and value.split(',')[163] == '1': COVID_obesity.append(value) elif value.split(',')[127]", "== '1' and value.split(',')[162] == '1': COVID_hiv.append(value) elif value.split(',')[127] == '1' and value.split(',')[162]", "COVID_hepB = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[154]", "value.split(',')[127] == '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) COVID_hiv = [] for value", "and value.split(',')[152] == '1': COVID_asthma.append(value) elif value.split(',')[127] == '1' and value.split(',')[152] == '1':", "value.split(',')[154] == '1': COVID_hepB.append(value) COVID_epilepsy = [] for value in data: if value.split(',')[122]", "'1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) COVID_hiv = [] for value in data:", "value.split(',')[127] == '1' and value.split(',')[145] == '1': COVID_bacteria.append(value) COVID_inflam_diseases = [] for value", "in data: if value.split(',')[122] == '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) elif value.split(',')[127]", "'1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) COVID_hypertension = [] for value in data:", "== '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[134]", "value in data: if value.split(',')[122] == '1' and value.split(',')[154] == '1': COVID_hepB.append(value) elif", "COVID_pulm_disease.append(value) COVID_asthma = [] for value in data: if value.split(',')[122] == '1' and", "COVID_adeno.append(value) elif value.split(',')[127] == '1' and value.split(',')[132] == '1': COVID_adeno.append(value) COVID_fluA&B = []", "'1' and value.split(',')[150] == '1': COVID_hypertension.append(value) COVID_pulm_disease = [] for value in data:", "#covid and more specific conditions: COVID_cardiopathy = [] for value in data: if", "'1': COVID_inflam_diseases.append(value) elif value.split(',')[127] == '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) COVID_&_vaccines =", "COVID_vrs = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[131]", "== '1': COVID_asthma.append(value) COVID_nephrology = [] for value in data: if value.split(',')[122] ==", "elif value.split(',')[127] == '1' and value.split(',')[150] == '1': COVID_hypertension.append(value) COVID_pulm_disease = [] for", "value.split(',')[142] == '1': COVID_resp_vir.append(value) COVID_bacteria = [] for value in data: if value.split(',')[122]", "if value.split(',')[122] == '1' and value.split(',')[131] == '1': COVID_vrs.append(value) elif value.split(',')[127] == '1'", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[161] ==", "elif value.split(',')[127] == '1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) COVID_diabetes = [] for", "value.split(',')[122] == '1' and value.split(',')[156] == '1': COVID_diabetes.append(value) elif value.split(',')[127] == '1' and", "value.split(',')[134] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[134] == '1': COVID_fluA&B.append(value)", "data.append(line) #covid and other illnesses: COVID_vrs = [] for value in data: if", "'1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) elif value.split(',')[127] == '1' and value.split(',')[148] ==", "and value.split(',')[149] == '1': COVID_cardiopathy.append(value) COVID_hypertension = [] for value in data: if", "value.split(',')[122] == '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) elif value.split(',')[127] == '1' and", "value in data: if value.split(',')[122] == '1' and value.split(',')[162] == '1': COVID_hiv.append(value) elif", "'1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) elif value.split(',')[127] == '1' and value.split(',')[167] ==", "COVID_epilepsy.append(value) COVID_diabetes = [] for value in data: if value.split(',')[122] == '1' and", "'1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) #covid and pathologies: COVID_comorbidities = [] for", "data: if value.split(',')[122] == '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) elif value.split(',')[127] ==", "value.split(',')[122] == '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) elif value.split(',')[127] == '1' and", "value.split(',')[127] == '1' and value.split(',')[150] == '1': COVID_hypertension.append(value) COVID_pulm_disease = [] for value", "value.split(',')[142] == '1': COVID_resp_vir.append(value) elif value.split(',')[127] == '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value)", "value in data: if value.split(',')[122] == '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) elif", "for value in data: if value.split(',')[122] == '1' and value.split(',')[162] == '1': COVID_hiv.append(value)", "conditions: COVID_cardiopathy = [] for value in data: if value.split(',')[122] == '1' and", "other more generically: COVID_resp_vir = [] for value in data: if value.split(',')[122] ==", "'1': COVID_pulm_disease.append(value) elif value.split(',')[127] == '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) COVID_asthma =", "and value.split(',')[162] == '1': COVID_hiv.append(value) elif value.split(',')[127] == '1' and value.split(',')[162] == '1':", "== '1': COVID_tuberculosis.append(value) elif value.split(',')[127] == '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) COVID_immunodeficiency", "value.split(',')[156] == '1': COVID_diabetes.append(value) COVID_tuberculosis = [] for value in data: if value.split(',')[122]", "and value.split(',')[157] == '1': COVID_tuberculosis.append(value) COVID_immunodeficiency = [] for value in data: if", "COVID_hepB.append(value) elif value.split(',')[127] == '1' and value.split(',')[154] == '1': COVID_hepB.append(value) COVID_epilepsy = []", "and value.split(',')[148] == '1': COVID_comorbidities.append(value) #covid and more specific conditions: COVID_cardiopathy = []", "'1': COVID_adeno.append(value) elif value.split(',')[127] == '1' and value.split(',')[132] == '1': COVID_adeno.append(value) COVID_fluA&B =", "value.split(',')[122] == '1' and value.split(',')[153] == '1': COVID_nephrology.append(value) elif value.split(',')[127] == '1' and", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[162] ==", "== '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) COVID_kawasaki = [] for value in", "and value.split(',')[159] == '1': COVID_neoplasia.append(value) elif value.split(',')[127] == '1' and value.split(',')[159] == '1':", "== '1': COVID_tuberculosis.append(value) COVID_immunodeficiency = [] for value in data: if value.split(',')[122] ==", "'1' and value.split(',')[155] == '1': COVID_epilepsy.append(value) elif value.split(',')[127] == '1' and value.split(',')[155] ==", "for line in f: data.append(line) #covid and other illnesses: COVID_vrs = [] for", "== '1': COVID_cardiopathy.append(value) elif value.split(',')[127] == '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) COVID_hypertension", "value.split(',')[122] == '1' and value.split(',')[150] == '1': COVID_hypertension.append(value) elif value.split(',')[127] == '1' and", "== '1': COVID_&_vaccines.append(value) #covid and pathologies: COVID_comorbidities = [] for value in data:", "COVID_cardiopathy.append(value) elif value.split(',')[127] == '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) COVID_hypertension = []", "== '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) elif value.split(',')[127] == '1' and value.split(',')[159]", "COVID_diabetes = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[156]", "== '1' and value.split(',')[131] == '1': COVID_vrs.append(value) elif value.split(',')[127] == '1' and value.split(',')[131]", "and value.split(',')[156] == '1': COVID_diabetes.append(value) elif value.split(',')[127] == '1' and value.split(',')[156] == '1':", "COVID_kawasaki = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[160]", "== '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) elif value.split(',')[127] == '1' and value.split(',')[142]", "COVID_tuberculosis.append(value) elif value.split(',')[127] == '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) COVID_immunodeficiency = []", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[155] == '1':", "and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) elif value.split(',')[127] == '1' and value.split(',')[158] == '1':", "'1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value) COVID_immunodeficiency = [] for value in data:", "[] for value in data: if value.split(',')[122] == '1' and value.split(',')[142] == '1':", "and pathologies: COVID_comorbidities = [] for value in data: if value.split(',')[122] == '1'", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[158] ==", "data: if value.split(',')[122] == '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) elif value.split(',')[127] ==", "'1' and value.split(',')[145] == '1': COVID_bacteria.append(value) COVID_inflam_diseases = [] for value in data:", "if value.split(',')[122] == '1' and value.split(',')[156] == '1': COVID_diabetes.append(value) elif value.split(',')[127] == '1'", "COVID_&_vaccines = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[167]", "== '1': COVID_comorbidities.append(value) #covid and more specific conditions: COVID_cardiopathy = [] for value", "value.split(',')[122] == '1' and value.split(',')[145] == '1': COVID_bacteria.append(value) elif value.split(',')[127] == '1' and", "value.split(',')[145] == '1': COVID_bacteria.append(value) COVID_inflam_diseases = [] for value in data: if value.split(',')[122]", "value.split(',')[127] == '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) COVID_hypertension = [] for value", "in data: if value.split(',')[122] == '1' and value.split(',')[158] == '1': COVID_immunodeficiency.append(value) elif value.split(',')[127]", "COVID_&_vaccines.append(value) elif value.split(',')[127] == '1' and value.split(',')[167] == '1': COVID_&_vaccines.append(value) #covid and pathologies:", "and value.split(',')[160] == '1': COVID_kawasaki.append(value) COVID_hiv = [] for value in data: if", "'1': COVID_adeno.append(value) COVID_fluA&B = [] for value in data: if value.split(',')[122] == '1'", "#covid and pathologies: COVID_comorbidities = [] for value in data: if value.split(',')[122] ==", "elif value.split(',')[127] == '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) COVID_bacteria = [] for", "value.split(',')[161] == '1': COVID_inflam_diseases.append(value) elif value.split(',')[127] == '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value)", "value in data: if value.split(',')[122] == '1' and value.split(',')[156] == '1': COVID_diabetes.append(value) elif", "'1' and value.split(',')[134] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[134] ==", "== '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[133]", "elif value.split(',')[127] == '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) COVID_asthma = [] for", "value.split(',')[159] == '1': COVID_neoplasia.append(value) COVID_kawasaki = [] for value in data: if value.split(',')[122]", "if value.split(',')[122] == '1' and value.split(',')[145] == '1': COVID_bacteria.append(value) elif value.split(',')[127] == '1'", "'1' and value.split(',')[150] == '1': COVID_hypertension.append(value) elif value.split(',')[127] == '1' and value.split(',')[150] ==", "#covid and other more generically: COVID_resp_vir = [] for value in data: if", "= [] for value in data: if value.split(',')[122] == '1' and value.split(',')[145] ==", "and value.split(',')[150] == '1': COVID_hypertension.append(value) COVID_pulm_disease = [] for value in data: if", "in f: data.append(line) #covid and other illnesses: COVID_vrs = [] for value in", "data: if value.split(',')[122] == '1' and value.split(',')[148] == '1': COVID_comorbidities.append(value) elif value.split(',')[127] ==", "in data: if value.split(',')[122] == '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) elif value.split(',')[127]", "data: if value.split(',')[122] == '1' and value.split(',')[153] == '1': COVID_nephrology.append(value) elif value.split(',')[127] ==", "COVID_diabetes.append(value) elif value.split(',')[127] == '1' and value.split(',')[156] == '1': COVID_diabetes.append(value) COVID_tuberculosis = []", "'1': COVID_hypertension.append(value) elif value.split(',')[127] == '1' and value.split(',')[150] == '1': COVID_hypertension.append(value) COVID_pulm_disease =", "COVID_neoplasia = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[159]", "if value.split(',')[122] == '1' and value.split(',')[149] == '1': COVID_cardiopathy.append(value) elif value.split(',')[127] == '1'", "value.split(',')[155] == '1': COVID_epilepsy.append(value) COVID_diabetes = [] for value in data: if value.split(',')[122]", "if value.split(',')[122] == '1' and value.split(',')[161] == '1': COVID_inflam_diseases.append(value) elif value.split(',')[127] == '1'", "== '1': COVID_vrs.append(value) COVID_adeno = [] for value in data: if value.split(',')[122] ==", "'1': COVID_resp_vir.append(value) elif value.split(',')[127] == '1' and value.split(',')[142] == '1': COVID_resp_vir.append(value) COVID_bacteria =", "== '1': COVID_neoplasia.append(value) elif value.split(',')[127] == '1' and value.split(',')[159] == '1': COVID_neoplasia.append(value) COVID_kawasaki", "and value.split(',')[159] == '1': COVID_neoplasia.append(value) COVID_kawasaki = [] for value in data: if", "'1' and value.split(',')[153] == '1': COVID_nephrology.append(value) elif value.split(',')[127] == '1' and value.split(',')[153] ==", "f = open (\"./Files/COPEDICATClinicSympt_DATA_2020-12-17_1642.csv\", 'r') data = [] for line in f: data.append(line)", "'1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[122]", "for value in data: if value.split(',')[122] == '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value)", "COVID_bacteria = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[145]", "value.split(',')[157] == '1': COVID_tuberculosis.append(value) elif value.split(',')[127] == '1' and value.split(',')[157] == '1': COVID_tuberculosis.append(value)", "generically: COVID_resp_vir = [] for value in data: if value.split(',')[122] == '1' and", "== '1' and value.split(',')[151] == '1': COVID_pulm_disease.append(value) elif value.split(',')[127] == '1' and value.split(',')[151]", "== '1' and value.split(',')[154] == '1': COVID_hepB.append(value) elif value.split(',')[127] == '1' and value.split(',')[154]", "COVID_resp_vir = [] for value in data: if value.split(',')[122] == '1' and value.split(',')[142]", "'1': COVID_kawasaki.append(value) elif value.split(',')[127] == '1' and value.split(',')[160] == '1': COVID_kawasaki.append(value) COVID_hiv =", "== '1' and value.split(',')[132] == '1': COVID_adeno.append(value) elif value.split(',')[127] == '1' and value.split(',')[132]", "'1': COVID_diabetes.append(value) elif value.split(',')[127] == '1' and value.split(',')[156] == '1': COVID_diabetes.append(value) COVID_tuberculosis =", "if value.split(',')[122] == '1' and value.split(',')[133] == '1': COVID_fluA&B.append(value) elif value.split(',')[127] == '1'" ]
[ "**kwargs): \"\"\"Generate default with translation uniformly b/w (-1,1) \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg", "background=bg, foreground=fg, rotation=0, scale=scale, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "seed=None, **kwargs): \"\"\"Generate 3-10 symbols at fixed scale. Samples 'a' with prob 70%", "occlusion over the existing symbol. \"\"\" def n_occlusion(rng): if rng.rand() < 0.2: return", "# ------------------- def generate_large_translation(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Synbols are translated beyond the border", "attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), is_bold=False, is_slant=False, scale=lambda rng: 0.5 * np.exp(rng.randn() * 0.1),", "3), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_many_small_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add", "alphabet=alphabet, is_slant=True, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return", "foreground=fg, rotation=0, scale=None, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "\"\"\" font_list = [] symbols_list = [] for language in LANGUAGE_MAP.values(): alphabet =", "len(fonts), len(alphabet.fonts), alphabet.name) font_list.extend(zip(fonts, [alphabet] * len(fonts))) logging.info(\"Using %d/%d symbols from alphabet %s\",", "Samples 'a' with prob 70% or a latin lowercase otherwise. \"\"\" def n_symbols(rng):", "> 0.1: return tuple(rng.rand(2) * 2 - 1) else: return 10 attr_generator =", "fixed to 0.5. \"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), scale=0.5, translation=lambda rng: tuple(rng.rand(2) *", "= SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet,", "basic_attribute_sampler( alphabet=alphabet, is_slant=True, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, )", "attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(), background=bg, foreground=fg) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_natural_images_dataset(n_samples, language=\"english\", seed=None,", "translation = (0.0,0.0) if set == 'rotation': rotation = (lambda rng: rng.uniform(low=0, high=1)*math.pi)", "is_slant=True, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler,", "0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=True, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0,", "fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) rotation = 0", "\"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0)", "alphabet=alphabet, background=lambda rng: ImagePattern(seed=rand_seed(rng)), #lambda rng: Gradient(seed=rand_seed(_rng)) foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), is_slant=False, is_bold=False, rotation=0,", "language=\"english\", seed=None, **kwarg): \"\"\"With probability 20%, add a large occlusion over the existing", "rotation=0, scale=1.0, translation=lambda rng: tuple(rng.uniform(low=-1, high=1, size=2)), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples,", "= SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=True, background=bg, foreground=fg, rotation=0,", "rng.uniform(low=0, high=1)*math.pi) elif set == 'translation': translation= (lambda rng: tuple(rng.uniform(low=-1, high=1, size=2))) elif", "language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() fonts = alphabet.fonts[:200] symbols = alphabet.symbols[:200] logging.info(\"Using", "basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=n_occlusion, scale=lambda rng: 0.6 * np.exp(rng.randn() * 0.1), translation=lambda rng: tuple(rng.rand(2) *", "n_occlusion=lambda rng: rng.randint(0, 5), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_pixel_noise(n_samples, language=\"english\",", "[] for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() fonts = alphabet.fonts[:200] symbols =", "generate_non_camou_shade_dataset, \"segmentation\": generate_segmentation_dataset, \"counting\": generate_counting_dataset, \"counting-fix-scale\": generate_counting_dataset_scale_fix, \"counting-crowded\": generate_counting_dataset_crowded, \"missing-symbol\": missing_symbol_dataset, \"some-large-occlusion\": generate_some_large_occlusions,", "= basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=lambda rng: tuple(rng.uniform(low=-1, high=1,", "bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=True, background=bg, foreground=fg,", "as foreground and background.\"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), background=lambda rng: ImagePattern(seed=rand_seed(rng)), foreground=lambda rng:", "n_symbols: %d.\", len(font_list), len(symbols_list)) def attr_sampler(seed=None): if np.random.rand() > 0.5: font, alphabet =", "at various scale. Samples 'a' with prob 70% or a latin lowercase otherwise.", "tuple(rng.rand(2) * 2 - 1) else: return 10 attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), translation=tr,", "\"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"shade\", seed=seed, **kwargs) # for segmentation, detection, counting #", "**kwarg): \"\"\"With 10% probability, no symbols are drawn\"\"\" def background(rng): return MultiGradient(alpha=0.5, n_gradients=2,", "'a' with prob 70% or a latin lowercase otherwise. \"\"\" def n_symbols(rng): return", "rng.randn() * 0.1, ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) DATASET_GENERATOR_MAP = { \"plain\": generate_plain_dataset,", "0.1) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=scale, translation=(0.0, 0.0),", "same attribute distribution as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"bw\", seed=seed,", "1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=True,", "scale=0.5, translation=lambda rng: tuple(rng.rand(2) * 4 - 2) ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "n_occlusion(rng): if rng.rand() < 0.2: return 1 else: return 0 attr_sampler = add_occlusion(", "translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_bold_dataset(n_samples, language=\"english\", seed=None,", "scale=scale, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_tiny_dataset(n_samples, language=\"english\",", "elif texture == \"bw\": fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0,", "def tr(rng): if rng.rand() > 0.1: return tuple(rng.rand(2) * 2 - 1) else:", "**kwargs): \"\"\"Generate 30-50 symbols at fixed scale. Samples 'a' with prob 70% or", "50))) return generate_counting_dataset(n_samples, scale_variation=0.1, n_symbols=n_symbols, seed=seed, **kwargs) # for few-shot learning # ---------------------", "at fixed scale. Samples 'a' with prob 70% or a latin lowercase otherwise.", "is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=rotation, scale=0.7, translation=translation, inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples,", "* np.exp(rng.randn() * 0.4) def n_symbols(rng): return rng.choice(list(range(3, 10))) attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False),", "font, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=rotation, scale=0.7, translation=translation, inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler,", "0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_natural_dataset(n_samples, language=\"english\", seed=None, **kwargs):", "pixel noise with probability 0.5.\"\"\" def pixel_noise(rng): if rng.rand() > 0.1: return 0", "language=\"english\", seed=None, **kwarg): \"\"\"With 10% probability, no symbols are drawn\"\"\" def background(rng): return", "LANGUAGE_MAP.values(): alphabet = language.get_alphabet() fonts = alphabet.fonts[:200] symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d fonts", "= LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False,", "basic_attribute_sampler(alphabet=alphabet, char=char)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_balanced_font_chars_dataset(n_samples, seed=None, **kwarg): \"\"\"Samples uniformly from", "resolution=(8, 8), is_gray=True, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_default_dataset(n_samples, language=\"english\", seed=None, **kwarg):", "else: return 0.3 attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), pixel_noise_scale=pixel_noise ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "rng: tuple(rng.rand(2) * 4 - 2) ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def missing_symbol_dataset(n_samples,", "is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=lambda rng: tuple(rng.uniform(low=-1, high=1, size=2)), inverse_color=False, pixel_noise_scale=0.0, )", "attr_sampler = basic_attribute_sampler( alphabet=alphabet, font = font, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=rotation, scale=0.7,", "from .fonts import LANGUAGE_MAP from .generate import ( dataset_generator, basic_attribute_sampler, flatten_mask, flatten_mask_except_first, add_occlusion,", "language=\"english\", seed=None, **kwarg): \"\"\"Synbols are translated beyond the border of the image to", "inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_bold_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"", "symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) logging.info(\"Total n_fonts: %d, n_symbols: %d.\", len(font_list), len(symbols_list)) def attr_sampler(seed=None):", "for the foreground and background. \"\"\" def attr_sampler(seed=None): if texture == \"camouflage\": angle", "texture=\"shade\", seed=seed, **kwargs) # for segmentation, detection, counting # ------------------------------------- def generate_segmentation_dataset(n_samples, language=\"english\",", "background=lambda rng: ImagePattern(seed=rand_seed(rng)), foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_korean_1k_dataset(n_samples,", "language=\"english\", resolution=(128, 128), seed=None, **kwarg): \"\"\"Generate 3-10 symbols of various scale and rotation", "= LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]),", "attr_generator = basic_attribute_sampler( char=char_sampler, resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols ) return dataset_generator(attr_generator, n_samples, flatten_mask,", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_natural_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black,", "all images. Number of occlusions are sampled uniformly in [0,5). \"\"\" attr_sampler =", "pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_translated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate default", "to 200 per languages). Note: some fonts may appear rarely. \"\"\" symbols_list =", "camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"bw\", seed=seed, **kwargs) def generate_non_camou_shade_dataset(n_samples, language=\"english\", seed=None,", "fg = [SolidColor((1, 1, 1)), ImagePattern(seed=123)] bg = [SolidColor((0, 0, 0)), ImagePattern(seed=123)] attr_sampler", "rng.choice(chars), font=lambda rng: rng.choice(fonts)) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_camouflage_dataset(n_samples, language=\"english\", texture=\"camouflage\", seed=None,", "0, 0)) else: raise ValueError(\"Unknown texture %s.\" % texture) scale = 0.7 *", "None, None elif texture == \"bw\": fg = SolidColor((1, 1, 1)) bg =", "foreground=fg, rotation=0, scale=scale, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "rng.choice(list(range(3, 10))) attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols, ) return dataset_generator(attr_generator,", "texture == \"shade\": fg, bg = None, None elif texture == \"bw\": fg", "n_symbols is None: def n_symbols(rng): return rng.choice(list(range(3, 10))) def scale(rng): return 0.1 *", "alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0),", "(str, optional): [description]. Defaults to \"english\". seed ([type], optional): [description]. Defaults to None.", "else: return 10 attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), translation=tr, background=background ) return dataset_generator(attr_generator, n_samples,", "probability 50%. \"\"\" font_list = [] symbols_list = [] for language in LANGUAGE_MAP.values():", "LANGUAGE_MAP[language].get_alphabet(support_bold=True) fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler =", "rotation=0, scale=None, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_bold_dataset(n_samples,", "segmentation, detection, counting # ------------------------------------- def generate_segmentation_dataset(n_samples, language=\"english\", resolution=(128, 128), seed=None, **kwarg): \"\"\"Generate", "%d.\", len(font_list), len(symbols_list)) def attr_sampler(seed=None): if np.random.rand() > 0.5: font, alphabet = font_list[np.random.choice(len(font_list))]", "= SolidColor((0, 0, 0)) rotation = 0 translation = (0.0,0.0) if set ==", "basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), background=bg, foreground=fg, is_bold=False, is_slant=False, scale=1, resolution=(8, 8), is_gray=True, ) return dataset_generator(attr_sampler,", "pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\"", "alphabet.name) font_list.extend(zip(fonts, [alphabet] * len(fonts))) logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols),", "scale=scale, is_bold=False, n_symbols=n_symbols, ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset( n_samples, language=\"english\",", "seed ([type], optional): [description]. Defaults to None. \"\"\" if alphabet is None: alphabet", "alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, background= lambda rng:rng.choice(bg), foreground=", "counting # ------------------------------------- def generate_segmentation_dataset(n_samples, language=\"english\", resolution=(128, 128), seed=None, **kwarg): \"\"\"Generate 3-10 symbols", "chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) fg = [SolidColor((1, 1,", "* 2 - 1) else: return 10 attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), translation=tr, background=background", "np.exp(rng.randn() * 0.1), translation=lambda rng: tuple(rng.rand(2) * 6 - 3), ) return dataset_generator(attr_sampler,", "datasets, but uses white on black.\"\"\" fg = SolidColor((1, 1, 1)) bg =", "scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_translated_dataset(n_samples, language=\"english\",", "rng: ImagePattern(seed=rand_seed(rng)), foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_korean_1k_dataset(n_samples, seed=None,", "SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) else: raise ValueError(\"Unknown texture %s.\"", "optional): [description]. Defaults to None. \"\"\" if alphabet is None: alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False)", "= (lambda rng: rng.uniform(low=0, high=1)*math.pi) elif set == 'translation': translation= (lambda rng: tuple(rng.uniform(low=-1,", "background(rng): return MultiGradient(alpha=0.5, n_gradients=2, types=(\"linear\", \"radial\"), seed=rand_seed(rng)) def tr(rng): if rng.rand() > 0.1:", "alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=lambda rng: rng.uniform(low=0, high=1)*math.pi, scale=1.0, translation=(0.0, 0.0), inverse_color=False,", "------------------- def generate_large_translation(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Synbols are translated beyond the border of", ") return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_pixel_noise(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add large", "the first 1000 korean symbols\"\"\" alphabet = LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True) chars = alphabet.symbols[:1000] fonts =", "[] for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d", "seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) angle = 0 fg = Camouflage(stroke_angle=angle,", "fonts may appear rarely. \"\"\" symbols_list = [] for language in LANGUAGE_MAP.values(): alphabet", "n_samples, dataset_seed=seed) def generate_tiny_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate a dataset of 8x8 resolution", "language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=True) fg = SolidColor((1, 1, 1))", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_korean_1k_dataset(n_samples, seed=None, **kwarg): \"\"\"Uses the first 1000 korean symbols\"\"\"", "def generate_plain_bold_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=True) fg = SolidColor((1,", "0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_tiny_dataset(n_samples, language=\"english\", seed=None, **kwarg):", "= None bg = None attr_sampler = basic_attribute_sampler( alphabet=alphabet, font = font, is_slant=False,", "alphabet.fonts[:200] symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d fonts from alphabet %s\", len(fonts), len(alphabet.fonts), alphabet.name)", "logging import numpy as np import math from .drawing import Camouflage, NoPattern, SolidColor,", "translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_rotated_dataset(n_samples, language=\"english\", seed=None,", "0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=None, translation=(0.0, 0.0),", "([type]): [description] language (str, optional): [description]. Defaults to \"english\". seed ([type], optional): [description].", "language=\"english\", resolution=(128, 128), n_symbols=None, scale_variation=0.5, seed=None, **kwarg ): \"\"\"Generate 3-10 symbols at various", "**kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng:", "= add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=lambda rng: rng.randint(0, 5), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed)", "\"\"\"With probability 20%, add a large occlusion over the existing symbol. \"\"\" def", "\"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0,", "alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) def attr_sampler(seed=None): char, alphabet = symbols_list[np.random.choice(len(symbols_list))] return basic_attribute_sampler(alphabet=alphabet,", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False)", "[description]. Defaults to \"english\". seed ([type], optional): [description]. Defaults to None. \"\"\" if", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_default_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate the default", "font, alphabet = font_list[np.random.choice(len(font_list))] symbol = np.random.choice(alphabet.symbols[:200]) else: symbol, alphabet = symbols_list[np.random.choice(len(symbols_list))] font", "len(symbols_list)) def attr_sampler(seed=None): if np.random.rand() > 0.5: font, alphabet = font_list[np.random.choice(len(font_list))] symbol =", "uniformly from all symbols (max 200 per alphabet) with probability 50%. \"\"\" font_list", "with same attribute distribution as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"shade\",", "language=\"english\", seed=None, **kwarg): \"\"\"Generate a dataset of 8x8 resolution in gray scale with", "SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=None,", "(0.0,0.0) if set == 'rotation': rotation = (lambda rng: rng.uniform(low=0, high=1)*math.pi) elif set", "n_samples, dataset_seed=seed) def generate_some_large_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With probability 20%, add a large", "**kwargs): \"\"\"Generate a black and white dataset with the same attribute distribution as", "**kwarg): \"\"\"Generate 3-10 symbols of various scale and rotation and translation (no bold).", "= LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) fg = [SolidColor((1, 1, 1)), ImagePattern(seed=123)] bg = [SolidColor((0, 0,", "set == 'translation': translation= (lambda rng: tuple(rng.uniform(low=-1, high=1, size=2))) elif set == 'gradient':", "variations are font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet,", "gray scale with scale of 1 and minimal variations. \"\"\" fg = SolidColor((1,", "NoPattern, SolidColor, MultiGradient, ImagePattern, Gradient, Image, Symbol from .fonts import LANGUAGE_MAP from .generate", "None, language=\"english\", font = 'calibri', set = \"plain\", seed=None, **kwargs): \"\"\"[summary] Args: n_samples", "1)) bg = SolidColor((0, 0, 0)) rotation = 0 translation = (0.0,0.0) if", "Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg = Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1, stroke_length=0.6,", "basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, background= lambda rng:rng.choice(bg),", "pixel_noise(rng): if rng.rand() > 0.1: return 0 else: return 0.3 attr_sampler = basic_attribute_sampler(", "alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, background=lambda rng: ImagePattern(seed=rand_seed(rng)), #lambda rng: Gradient(seed=rand_seed(_rng))", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_korean_1k_dataset(n_samples, seed=None, **kwarg): \"\"\"Uses the first 1000 korean", "language=\"english\", seed=None, **kwarg): \"\"\"Add large pixel noise with probability 0.5.\"\"\" def pixel_noise(rng): if", "translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_italic_dataset(n_samples, language=\"english\", seed=None,", "**kwargs) # for segmentation, detection, counting # ------------------------------------- def generate_segmentation_dataset(n_samples, language=\"english\", resolution=(128, 128),", "n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_pixel_noise(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add large pixel noise with", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet_onlygrad(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet =", "n_samples, dataset_seed=seed) def generate_non_camou_bw_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a black and white dataset", "stroke_noise=0) elif texture == \"shade\": fg, bg = None, None elif texture ==", "alphabet.symbols[:200] logging.info(\"Using %d/%d fonts from alphabet %s\", len(fonts), len(alphabet.fonts), alphabet.name) font_list.extend(zip(fonts, [alphabet] *", "rng.rand() < 0.2: return 1 else: return 0 attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=n_occlusion,", "return tuple(rng.rand(2) * 2 - 1) else: return 10 attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(),", "dataset_seed=seed) def generate_plain_gradient_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols. The", "language=\"english\", seed=None, **kwarg): \"\"\"Add small occlusions on all images. Number of occlusions are", "= alphabet.fonts[:200] symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d fonts from alphabet %s\", len(fonts), len(alphabet.fonts),", "(max 200 per alphabet) with probability 50%. \"\"\" font_list = [] symbols_list =", "\"\"\" attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), is_bold=False, is_slant=False, scale=lambda rng: 0.5 * np.exp(rng.randn() *", "a more accessible font classification task. \"\"\" attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), is_bold=False, is_slant=False,", "= \"plain\", seed=None, **kwargs): \"\"\"[summary] Args: n_samples ([type]): [description] language (str, optional): [description].", "bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=True, is_bold=False, background=bg, foreground=fg,", "n_samples, dataset_seed=seed) DATASET_GENERATOR_MAP = { \"plain\": generate_plain_dataset, \"default\": generate_default_dataset, \"default-bw\": generate_solid_bg_dataset, \"korean-1k\": generate_korean_1k_dataset,", "#lambda rng: Gradient(seed=rand_seed(_rng)) foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False,", "= SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) rotation = 0 translation", "generate_counting_dataset( n_samples, language=\"english\", resolution=(128, 128), n_symbols=None, scale_variation=0.5, seed=None, **kwarg ): \"\"\"Generate 3-10 symbols", "basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True), background=bg, foreground=fg, is_bold=True, is_slant=False, scale=scale, )(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "fonts from alphabet %s\", len(fonts), len(alphabet.fonts), alphabet.name) font_list.extend(zip(fonts, [alphabet] * len(fonts))) logging.info(\"Using %d/%d", "rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, background= lambda rng:rng.choice(bg), foreground= lambda rng:rng.choice(fg), rotation=0, scale=0.7, translation=(0.0, 0.0),", "generate_plain_scaled_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1,", "------------------------------------- def generate_segmentation_dataset(n_samples, language=\"english\", resolution=(128, 128), seed=None, **kwarg): \"\"\"Generate 3-10 symbols of various", "\"radial\"), seed=rand_seed(rng)) def tr(rng): if rng.rand() > 0.1: return tuple(rng.rand(2) * 2 -", "= alphabet.symbols[:200] logging.info(\"Using %d/%d fonts from alphabet %s\", len(fonts), len(alphabet.fonts), alphabet.name) font_list.extend(zip(fonts, [alphabet]", "translation= (lambda rng: tuple(rng.uniform(low=-1, high=1, size=2))) elif set == 'gradient': fg = None", "n_samples, dataset_seed=seed) # for active learning # ------------------- def generate_large_translation(n_samples, language=\"english\", seed=None, **kwarg):", "generate_plain_dataset_alphabet_onlygrad(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) attr_sampler = basic_attribute_sampler(", "fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler(", "scale = 0.7 * np.exp(np.random.randn() * 0.1) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False,", "return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset_scale_fix(n_samples, seed=None, **kwargs): \"\"\"Generate 3-10 symbols at", "LANGUAGE_MAP.values(): alphabet = language.get_alphabet() symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d symbols from alphabet %s\",", "from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) def attr_sampler(seed=None): char,", "scale with scale of 1 and minimal variations. \"\"\" fg = SolidColor((1, 1,", "generate_plain_dataset_alphabet(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) fg = [SolidColor((1,", "\"plain\", seed=None, **kwargs): \"\"\"[summary] Args: n_samples ([type]): [description] language (str, optional): [description]. Defaults", "Camouflage, NoPattern, SolidColor, MultiGradient, ImagePattern, Gradient, Image, Symbol from .fonts import LANGUAGE_MAP from", "basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=scale, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, )", "\"\"\"Generate default with translation uniformly b/w (-1,1) \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg =", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet_onlygrad(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False)", "lambda rng:rng.choice(bg), foreground= lambda rng:rng.choice(fg), rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return", "high=1)*math.pi, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_translated_dataset(n_samples,", "n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset_scale_fix(n_samples, seed=None, **kwargs): \"\"\"Generate 3-10 symbols at fixed scale.", "size=2)), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_scaled_dataset(n_samples, language=\"english\", seed=None, **kwargs):", "stroke_length=0.6, stroke_noise=0) scale = 0.7 * np.exp(np.random.randn() * 0.1) attr_sampler = basic_attribute_sampler( alphabet=alphabet,", "basic_attribute_sampler(char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(fonts)) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_camouflage_dataset(n_samples, language=\"english\",", "char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, background= lambda rng:rng.choice(bg), foreground= lambda", "len(symbols))) logging.info(\"Total n_fonts: %d, n_symbols: %d.\", len(font_list), len(symbols_list)) def attr_sampler(seed=None): if np.random.rand() >", "translation (no bold). \"\"\" def scale(rng): return 0.1 * np.exp(rng.randn() * 0.4) def", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_bold_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=True)", "return generate_counting_dataset(n_samples, scale_variation=0, seed=seed, **kwargs) def generate_counting_dataset_crowded(n_samples, seed=None, **kwargs): \"\"\"Generate 30-50 symbols at", "seed=None, **kwargs): \"\"\"Generate a black and white dataset with the same attribute distribution", "n_symbols=n_symbols, ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset( n_samples, language=\"english\", resolution=(128, 128),", "basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=lambda rng: rng.randint(0, 5), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_pixel_noise(n_samples,", "**kwargs) def generate_non_camou_shade_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a gradient foreground and background dataset", "generate_solid_bg_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Same as default datasets, but uses white on black.\"\"\"", "large occlusion over the existing symbol. \"\"\" def n_occlusion(rng): if rng.rand() < 0.2:", "SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0,", "basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, rotation=0, scale=0.7, translation=(0.0,", "def generate_non_camou_shade_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a gradient foreground and background dataset with", "= basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(), background=bg, foreground=fg) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_natural_images_dataset(n_samples, language=\"english\", seed=None, **kwargs):", "using gradiant as foreground and background. \"\"\" attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()) return dataset_generator(attr_sampler, n_samples,", "as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"shade\", seed=seed, **kwargs) # for", "translation uniformly b/w (-1,1) \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1))", "inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet(n_samples, chars, seed=None, **kwargs): \"\"\"", "= 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg = Camouflage(stroke_angle=angle + np.pi", "logging.info(\"Total n_fonts: %d, n_symbols: %d.\", len(font_list), len(symbols_list)) def attr_sampler(seed=None): if np.random.rand() > 0.5:", "\"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), scale=0.5, translation=lambda rng: tuple(rng.rand(2) * 4 - 2)", "8), is_gray=True, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_default_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate", "def scale(rng): return 0.1 * np.exp(rng.randn() * scale_variation) def char_sampler(rng): if rng.rand() <", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_non_camou_bw_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a black and white", "less_variations(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Less variations in scale and rotations. Also, no bold", "rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_natural_dataset(n_samples,", "\"\"\"Generate 3-10 symbols at various scale. Samples 'a' with prob 70% or a", "LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True) chars = alphabet.symbols[:1000] fonts = alphabet.fonts attr_sampler = basic_attribute_sampler(char=lambda rng: rng.choice(chars), font=lambda", "are font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1))", "**kwarg): \"\"\"Synbols are translated beyond the border of the image to create a", "1 else: return 0 attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=n_occlusion, scale=lambda rng: 0.6 *", "**kwarg): \"\"\"Generate the default dataset, using gradiant as foreground and background. \"\"\" attr_sampler", "alphabet=alphabet, is_slant=False, is_bold=True, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return", "= basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=lambda rng: rng.uniform(low=0, high=1)*math.pi, scale=1.0, translation=(0.0,", "translation=lambda rng: tuple(rng.uniform(low=-1, high=1, size=2)), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "rng.uniform(low=0, high=1)*math.pi, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_korean_1k_dataset(n_samples, seed=None, **kwarg): \"\"\"Uses the first 1000", "= LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler", "scale=scale, is_bold=False, n_symbols=n_symbols ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset_scale_fix(n_samples, seed=None, **kwargs):", "n_symbols(rng): return rng.choice(list(range(3, 10))) attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols, )", "1 and minimal variations. \"\"\" fg = SolidColor((1, 1, 1)) bg = SolidColor((0,", "uniformly in [0,5). \"\"\" attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=lambda rng: rng.randint(0, 5), )", "0)), ImagePattern(seed=123)] attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False,", "background=bg, foreground=fg, rotation=0, scale=None, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_tiny_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate a dataset of", "rotation=lambda rng: rng.randn() * 0.1, ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) DATASET_GENERATOR_MAP = {", "fg, bg = None, None elif texture == \"bw\": fg = SolidColor((1, 1,", "print(alphabet) fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) rotation =", "0.3 attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), pixel_noise_scale=pixel_noise ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for", "generate_non_camou_bw_dataset, \"non-camou-shade\": generate_non_camou_shade_dataset, \"segmentation\": generate_segmentation_dataset, \"counting\": generate_counting_dataset, \"counting-fix-scale\": generate_counting_dataset_scale_fix, \"counting-crowded\": generate_counting_dataset_crowded, \"missing-symbol\": missing_symbol_dataset,", "occlusions on all images. Number of occlusions are sampled uniformly in [0,5). \"\"\"", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def missing_symbol_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With 10% probability, no symbols", "def generate_plain_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1,", "generate_camouflage_dataset(n_samples, language=language, texture=\"bw\", seed=seed, **kwargs) def generate_non_camou_shade_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a gradient", "background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "generate_many_small_occlusions, \"large-translation\": generate_large_translation, \"tiny\": generate_tiny_dataset, \"balanced-font-chars\": generate_balanced_font_chars_dataset, \"all-chars\": all_chars, \"less-variations\": less_variations, \"pixel-noise\": generate_pixel_noise,", "dataset_seed=seed) def generate_solid_bg_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Same as default datasets, but uses white", "elif set == 'translation': translation= (lambda rng: tuple(rng.uniform(low=-1, high=1, size=2))) elif set ==", "seed=None, **kwarg): \"\"\"Add large pixel noise with probability 0.5.\"\"\" def pixel_noise(rng): if rng.rand()", "add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=lambda rng: rng.randint(0, 5), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def", "scale and rotations. Also, no bold and no italic. This makes a more", "# ----------------------- def less_variations(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Less variations in scale and rotations.", "LANGUAGE_MAP[language].get_alphabet(support_bold=False) print(alphabet) fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) rotation", "variations are font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1,", "np.exp(rng.randn() * scale_variation) def char_sampler(rng): if rng.rand() < 0.3: return rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols) else: return", "len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) def attr_sampler(seed=None): char, alphabet = symbols_list[np.random.choice(len(symbols_list))] return", "chars = alphabet.symbols[:1000] fonts = alphabet.fonts attr_sampler = basic_attribute_sampler(char=lambda rng: rng.choice(chars), font=lambda rng:", "n_samples, dataset_seed=seed) def generate_plain_rotated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg", "symbols_list = [] for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() symbols = alphabet.symbols[:200]", "is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=lambda rng: rng.uniform(low=0, high=1)*math.pi, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0,", "alphabet=alphabet, font = font, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=rotation, scale=0.7, translation=translation, inverse_color=False, pixel_noise_scale=0.0,", "generate_plain_rotated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1,", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_solid_bg_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Same as default datasets,", "fg = None bg = None attr_sampler = basic_attribute_sampler( alphabet=alphabet, font = font,", "size=2))) elif set == 'gradient': fg = None bg = None attr_sampler =", "rng: 0.5 * np.exp(rng.randn() * 0.1), rotation=lambda rng: rng.randn() * 0.1, ) return", "n_samples, dataset_seed=seed) def generate_korean_1k_dataset(n_samples, seed=None, **kwarg): \"\"\"Uses the first 1000 korean symbols\"\"\" alphabet", "alphabet=LANGUAGE_MAP[language].get_alphabet(), is_bold=False, is_slant=False, scale=lambda rng: 0.5 * np.exp(rng.randn() * 0.1), rotation=lambda rng: rng.randn()", "attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, rotation=0,", "where the pixel distribution is the same for the foreground and background. \"\"\"", "scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_rotated_dataset(n_samples, language=\"english\",", "uniformly b/w (-1,1) \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg", "task. \"\"\" attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), is_bold=False, is_slant=False, scale=lambda rng: 0.5 * np.exp(rng.randn()", "> 0.1: return 0 else: return 0.3 attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), pixel_noise_scale=pixel_noise )", "rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_italic_dataset(n_samples,", "symbols\"\"\" alphabet = LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True) chars = alphabet.symbols[:1000] fonts = alphabet.fonts attr_sampler = basic_attribute_sampler(char=lambda", "0, 0)) rotation = 0 translation = (0.0,0.0) if set == 'rotation': rotation", "in scale and rotations. Also, no bold and no italic. This makes a", ") return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset_scale_fix(n_samples, seed=None, **kwargs): \"\"\"Generate 3-10 symbols", "a black and white dataset with the same attribute distribution as the camouflage", "return 0.1 * np.exp(rng.randn() * scale_variation) def char_sampler(rng): if rng.rand() < 0.3: return", "%s.\" % texture) scale = 0.7 * np.exp(np.random.randn() * 0.1) return basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True),", "n_symbols=None, scale_variation=0.5, seed=None, **kwarg ): \"\"\"Generate 3-10 symbols at various scale. Samples 'a'", "basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), background=lambda rng: ImagePattern(seed=rand_seed(rng)), foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "is_bold=False, n_symbols=n_symbols ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset_scale_fix(n_samples, seed=None, **kwargs): \"\"\"Generate", "0.5. \"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), scale=0.5, translation=lambda rng: tuple(rng.rand(2) * 4 -", "translation=tr, background=background ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) def generate_some_large_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With", "fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(),", "generate_camouflage_dataset(n_samples, language=language, texture=\"shade\", seed=seed, **kwargs) # for segmentation, detection, counting # ------------------------------------- def", "beyond the border of the image to create a cropping effect. Scale is", "black, centered symbols. The only factors of variations are font and char. \"\"\"", "def generate_plain_scaled_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1,", "are sampled uniformly in [0,5). \"\"\" attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=lambda rng: rng.randint(0,", "* np.exp(rng.randn() * 0.1), rotation=lambda rng: rng.randn() * 0.1, ) return dataset_generator(attr_generator, n_samples,", "n_samples ([type]): [description] language (str, optional): [description]. Defaults to \"english\". seed ([type], optional):", "0.3: return rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols) else: return \"a\" attr_generator = basic_attribute_sampler( char=char_sampler, resolution=resolution, scale=scale, is_bold=False,", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet_onlygrad(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet", "rng: tuple(rng.rand(2) * 6 - 3), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def", "add_occlusion, rand_seed, ) def generate_i(n_samples, alphabet = None, language=\"english\", font = 'calibri', set", "images as foreground and background.\"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), background=lambda rng: ImagePattern(seed=rand_seed(rng)), foreground=lambda", "inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_scaled_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"", "return MultiGradient(alpha=0.5, n_gradients=2, types=(\"linear\", \"radial\"), seed=rand_seed(rng)) def tr(rng): if rng.rand() > 0.1: return", "0 attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=n_occlusion, scale=lambda rng: 0.6 * np.exp(rng.randn() * 0.1),", "attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=True, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False,", "* 0.1), translation=lambda rng: tuple(rng.rand(2) * 6 - 3), ) return dataset_generator(attr_sampler, n_samples,", "scale. Samples 'a' with prob 70% or a latin lowercase otherwise. \"\"\" def", "language.get_alphabet() fonts = alphabet.fonts[:200] symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d fonts from alphabet %s\",", "\"\"\"Uses the first 1000 korean symbols\"\"\" alphabet = LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True) chars = alphabet.symbols[:1000] fonts", "generate_plain_camouflage_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) angle = 0 fg", "def generate_i(n_samples, alphabet = None, language=\"english\", font = 'calibri', set = \"plain\", seed=None,", "the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"bw\", seed=seed, **kwargs) def generate_non_camou_shade_dataset(n_samples, language=\"english\",", "missing_symbol_dataset, \"some-large-occlusion\": generate_some_large_occlusions, \"many-small-occlusion\": generate_many_small_occlusions, \"large-translation\": generate_large_translation, \"tiny\": generate_tiny_dataset, \"balanced-font-chars\": generate_balanced_font_chars_dataset, \"all-chars\": all_chars,", "* np.exp(rng.randn() * scale_variation) def char_sampler(rng): if rng.rand() < 0.3: return rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols) else:", "np.exp(rng.randn() * 0.1), rotation=lambda rng: rng.randn() * 0.1, ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed)", "background= lambda rng:rng.choice(bg), foreground= lambda rng:rng.choice(fg), rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, )", "**kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1,", ") return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_many_small_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add small", "**kwarg): \"\"\"Combines the symbols of all languages (up to 200 per languages). Note:", "is_bold=False, background=bg, foreground=fg, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples,", "a dataset where the pixel distribution is the same for the foreground and", "bg = None, None elif texture == \"bw\": fg = SolidColor((1, 1, 1))", "dataset_seed=seed) def generate_natural_images_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Same as default dataset, but uses natural", "basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), scale=0.5, translation=lambda rng: tuple(rng.rand(2) * 4 - 2) ) return dataset_generator(attr_sampler,", "set == 'gradient': fg = None bg = None attr_sampler = basic_attribute_sampler( alphabet=alphabet,", "sampled uniformly in [0,5). \"\"\" attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=lambda rng: rng.randint(0, 5),", "np import math from .drawing import Camouflage, NoPattern, SolidColor, MultiGradient, ImagePattern, Gradient, Image,", "only factors of variations are font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler", "\"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"bw\", seed=seed, **kwargs) def generate_non_camou_shade_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate", "background=lambda rng: ImagePattern(seed=rand_seed(rng)), #lambda rng: Gradient(seed=rand_seed(_rng)) foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), is_slant=False, is_bold=False, rotation=0, scale=1.0,", "* 0.1) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=scale, translation=(0.0,", "= basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), pixel_noise_scale=pixel_noise ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for font classification", "alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=None, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return", "distribution is the same for the foreground and background. \"\"\" def attr_sampler(seed=None): if", "translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset(n_samples, language=\"english\", seed=None,", "if rng.rand() > 0.1: return tuple(rng.rand(2) * 2 - 1) else: return 10", "language=\"english\", seed=None, **kwargs): \"\"\"Generate default with translation uniformly b/w (-1,1) \"\"\" alphabet =", "0.1 * np.exp(rng.randn() * scale_variation) def char_sampler(rng): if rng.rand() < 0.3: return rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols)", "None. \"\"\" if alphabet is None: alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) print(alphabet) fg = SolidColor((1,", "is_bold=False, background= lambda rng:rng.choice(bg), foreground= lambda rng:rng.choice(fg), rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0,", "len(alphabet.fonts), alphabet.name) font_list.extend(zip(fonts, [alphabet] * len(fonts))) logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols),", "background dataset with same attribute distribution as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples,", "SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False,", "200 per alphabet) or uniformly from all symbols (max 200 per alphabet) with", "\"counting-fix-scale\": generate_counting_dataset_scale_fix, \"counting-crowded\": generate_counting_dataset_crowded, \"missing-symbol\": missing_symbol_dataset, \"some-large-occlusion\": generate_some_large_occlusions, \"many-small-occlusion\": generate_many_small_occlusions, \"large-translation\": generate_large_translation, \"tiny\":", "dataset_seed=seed) def generate_korean_1k_dataset(n_samples, seed=None, **kwarg): \"\"\"Uses the first 1000 korean symbols\"\"\" alphabet =", "symbols (max 200 per alphabet) with probability 50%. \"\"\" font_list = [] symbols_list", "= font_list[np.random.choice(len(font_list))] symbol = np.random.choice(alphabet.symbols[:200]) else: symbol, alphabet = symbols_list[np.random.choice(len(symbols_list))] font = np.random.choice(alphabet.fonts[:200])", "background=bg, foreground=fg, rotation=rotation, scale=0.7, translation=translation, inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "generate_segmentation_dataset(n_samples, language=\"english\", resolution=(128, 128), seed=None, **kwarg): \"\"\"Generate 3-10 symbols of various scale and", "0.1), translation=lambda rng: tuple(rng.rand(2) * 6 - 3), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first,", "def generate_plain_dataset_alphabet(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) fg =", "if n_symbols is None: def n_symbols(rng): return rng.choice(list(range(3, 10))) def scale(rng): return 0.1", "1)) bg = SolidColor((0, 0, 0)) else: raise ValueError(\"Unknown texture %s.\" % texture)", "basic_attribute_sampler( alphabet=alphabet, background=lambda rng: ImagePattern(seed=rand_seed(rng)), #lambda rng: Gradient(seed=rand_seed(_rng)) foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), is_slant=False, is_bold=False,", "background=bg, foreground=fg, rotation=lambda rng: rng.uniform(low=0, high=1)*math.pi, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return", "Also, no bold and no italic. This makes a more accessible font classification", "attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols, ) return dataset_generator(attr_generator, n_samples, flatten_mask,", "latin lowercase otherwise. \"\"\" if n_symbols is None: def n_symbols(rng): return rng.choice(list(range(3, 10)))", "SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=True, background=bg, foreground=fg, rotation=0, scale=1.0,", "white dataset with the same attribute distribution as the camouflage dataset. \"\"\" return", "dataset_seed=seed) def generate_camouflage_dataset(n_samples, language=\"english\", texture=\"camouflage\", seed=None, **kwarg): \"\"\"Generate a dataset where the pixel", "prob 70% or a latin lowercase otherwise. \"\"\" return generate_counting_dataset(n_samples, scale_variation=0, seed=seed, **kwargs)", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_gradient_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black,", "is None: alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) print(alphabet) fg = SolidColor((1, 1, 1)) bg =", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def missing_symbol_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With 10% probability,", "scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_natural_dataset(n_samples, language=\"english\",", "font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, background= lambda rng:rng.choice(bg), foreground= lambda rng:rng.choice(fg), rotation=0, scale=0.7,", "rng: ImagePattern(seed=rand_seed(rng)), ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_korean_1k_dataset(n_samples, seed=None, **kwarg): \"\"\"Uses the", "3-10 symbols at various scale. Samples 'a' with prob 70% or a latin", "**kwargs): \"\"\"[summary] Args: n_samples ([type]): [description] language (str, optional): [description]. Defaults to \"english\".", "def generate_plain_dataset_alphabet_onlygrad(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) attr_sampler =", "basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=lambda rng: tuple(rng.uniform(low=-1, high=1, size=2)),", "rotation=lambda rng: rng.uniform(low=0, high=1)*math.pi, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples,", "SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) rotation = 0 translation =", "korean symbols\"\"\" alphabet = LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True) chars = alphabet.symbols[:1000] fonts = alphabet.fonts attr_sampler =", "Samples 'a' with prob 70% or a latin lowercase otherwise. \"\"\" if n_symbols", "language (str, optional): [description]. Defaults to \"english\". seed ([type], optional): [description]. Defaults to", "return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_pixel_noise(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add large pixel", "def generate_pixel_noise(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add large pixel noise with probability 0.5.\"\"\" def", "high=1, size=2)), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_scaled_dataset(n_samples, language=\"english\", seed=None,", "[alphabet] * len(fonts))) logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols,", "rng.rand() > 0.1: return tuple(rng.rand(2) * 2 - 1) else: return 10 attr_generator", "flatten_mask, dataset_seed=seed) def generate_counting_dataset( n_samples, language=\"english\", resolution=(128, 128), n_symbols=None, scale_variation=0.5, seed=None, **kwarg ):", "black.\"\"\" fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler =", "return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset( n_samples, language=\"english\", resolution=(128, 128), n_symbols=None, scale_variation=0.5,", "basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=lambda rng: rng.uniform(low=0, high=1)*math.pi, scale=1.0, translation=(0.0, 0.0),", "rotation and translation (no bold). \"\"\" def scale(rng): return 0.1 * np.exp(rng.randn() *", "= basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=scale, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0,", "pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_gradient_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white", "[0,5). \"\"\" attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=lambda rng: rng.randint(0, 5), ) return dataset_generator(attr_sampler,", "0 translation = (0.0,0.0) if set == 'rotation': rotation = (lambda rng: rng.uniform(low=0,", "\"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda", "uniformly from all fonts (max 200 per alphabet) or uniformly from all symbols", "background. \"\"\" def attr_sampler(seed=None): if texture == \"camouflage\": angle = 0 fg =", "= basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, background= lambda", "--------------------- def all_chars(n_samples, seed=None, **kwarg): \"\"\"Combines the symbols of all languages (up to", "if rng.rand() < 0.2: return 1 else: return 0 attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()),", "0.1, ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) DATASET_GENERATOR_MAP = { \"plain\": generate_plain_dataset, \"default\": generate_default_dataset,", "\"\"\"Generate a black and white dataset with the same attribute distribution as the", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for font classification # ----------------------- def less_variations(n_samples,", "symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols,", "generate_plain_italic_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols. The only factors", "* len(fonts))) logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet]", "%d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) logging.info(\"Total", "seed=None, **kwarg): \"\"\"Generate a dataset of 8x8 resolution in gray scale with scale", "SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=0.7,", "or uniformly from all symbols (max 200 per alphabet) with probability 50%. \"\"\"", "1)), ImagePattern(seed=123)] bg = [SolidColor((0, 0, 0)), ImagePattern(seed=123)] attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda", "0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_rotated_dataset(n_samples, language=\"english\", seed=None, **kwargs):", "= basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0,", "n_symbols(rng): return rng.choice(list(range(3, 10))) def scale(rng): return 0.1 * np.exp(rng.randn() * scale_variation) def", "* np.exp(np.random.randn() * 0.1) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0,", "translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_translated_dataset(n_samples, language=\"english\", seed=None,", "symbols at various scale. Samples 'a' with prob 70% or a latin lowercase", "as default dataset, but uses natural images as foreground and background.\"\"\" attr_sampler =", "font = np.random.choice(alphabet.fonts[:200]) return basic_attribute_sampler(char=symbol, font=font, is_bold=False, is_slant=False)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) #", "dataset_seed=seed) def generate_plain_translated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate default with translation uniformly b/w (-1,1)", "ImagePattern(seed=123)] bg = [SolidColor((0, 0, 0)), ImagePattern(seed=123)] attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng:", "attribute distribution as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"shade\", seed=seed, **kwargs)", "seed=None, **kwarg): \"\"\"Combines the symbols of all languages (up to 200 per languages).", "fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) else: raise ValueError(\"Unknown", "dataset_seed=seed) def generate_plain_italic_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols. The", "SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), background=bg,", "generate_plain_translated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate default with translation uniformly b/w (-1,1) \"\"\" alphabet", "0)) rotation = 0 translation = (0.0,0.0) if set == 'rotation': rotation =", "**kwarg): \"\"\"Less variations in scale and rotations. Also, no bold and no italic.", "0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=True, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0),", "ImagePattern, Gradient, Image, Symbol from .fonts import LANGUAGE_MAP from .generate import ( dataset_generator,", "of various scale and rotation and translation (no bold). \"\"\" def scale(rng): return", "and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, background=lambda rng: ImagePattern(seed=rand_seed(rng)),", "\"a\" attr_generator = basic_attribute_sampler( char=char_sampler, resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols ) return dataset_generator(attr_generator, n_samples,", "\"non-camou-bw\": generate_non_camou_bw_dataset, \"non-camou-shade\": generate_non_camou_shade_dataset, \"segmentation\": generate_segmentation_dataset, \"counting\": generate_counting_dataset, \"counting-fix-scale\": generate_counting_dataset_scale_fix, \"counting-crowded\": generate_counting_dataset_crowded, \"missing-symbol\":", "char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False,", "scale_variation) def char_sampler(rng): if rng.rand() < 0.3: return rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols) else: return \"a\" attr_generator", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_natural_images_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Same as default dataset, but", "return generate_camouflage_dataset(n_samples, language=language, texture=\"bw\", seed=seed, **kwargs) def generate_non_camou_shade_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a", "as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"bw\", seed=seed, **kwargs) def generate_non_camou_shade_dataset(n_samples,", "= { \"plain\": generate_plain_dataset, \"default\": generate_default_dataset, \"default-bw\": generate_solid_bg_dataset, \"korean-1k\": generate_korean_1k_dataset, \"camouflage\": generate_camouflage_dataset, \"non-camou-bw\":", "the image to create a cropping effect. Scale is fixed to 0.5. \"\"\"", "attr_sampler = basic_attribute_sampler( alphabet=alphabet, background=lambda rng: ImagePattern(seed=rand_seed(rng)), #lambda rng: Gradient(seed=rand_seed(_rng)) foreground=lambda rng: ImagePattern(seed=rand_seed(rng)),", "symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) logging.info(\"Total n_fonts:", "background=bg, foreground=fg, rotation=0, scale=1.0, translation=lambda rng: tuple(rng.uniform(low=-1, high=1, size=2)), inverse_color=False, pixel_noise_scale=0.0, ) return", "cropping effect. Scale is fixed to 0.5. \"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), scale=0.5,", "texture == \"camouflage\": angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg", "scale=scale, )(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_non_camou_bw_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a", "set == 'rotation': rotation = (lambda rng: rng.uniform(low=0, high=1)*math.pi) elif set == 'translation':", "= SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=lambda", "def background(rng): return MultiGradient(alpha=0.5, n_gradients=2, types=(\"linear\", \"radial\"), seed=rand_seed(rng)) def tr(rng): if rng.rand() >", "# for font classification # ----------------------- def less_variations(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Less variations", "but uses white on black.\"\"\" fg = SolidColor((1, 1, 1)) bg = SolidColor((0,", "5), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_pixel_noise(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add", "lowercase otherwise. \"\"\" if n_symbols is None: def n_symbols(rng): return rng.choice(list(range(3, 10))) def", "bg = Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) elif texture ==", "language=\"english\", seed=None, **kwarg): \"\"\"Same as default datasets, but uses white on black.\"\"\" fg", "n_samples, dataset_seed=seed) def generate_plain_translated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate default with translation uniformly b/w", "alphabet.symbols[:200] logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] *", "n_samples, dataset_seed=seed) def generate_plain_camouflage_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) angle", "large pixel noise with probability 0.5.\"\"\" def pixel_noise(rng): if rng.rand() > 0.1: return", "latin lowercase otherwise. \"\"\" return generate_counting_dataset(n_samples, scale_variation=0, seed=seed, **kwargs) def generate_counting_dataset_crowded(n_samples, seed=None, **kwargs):", "foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "scale. Samples 'a' with prob 70% or a latin lowercase otherwise. \"\"\" if", "otherwise. \"\"\" def n_symbols(rng): return rng.choice(list(range(30, 50))) return generate_counting_dataset(n_samples, scale_variation=0.1, n_symbols=n_symbols, seed=seed, **kwargs)", "dataset_seed=seed) def generate_plain_natural_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols. The", "noise with probability 0.5.\"\"\" def pixel_noise(rng): if rng.rand() > 0.1: return 0 else:", "0.5 * np.exp(rng.randn() * 0.1), rotation=lambda rng: rng.randn() * 0.1, ) return dataset_generator(attr_generator,", "seed=None, **kwarg): \"\"\"With probability 20%, add a large occlusion over the existing symbol.", "1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=True, is_bold=False,", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_italic_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered", "3-10 symbols at fixed scale. Samples 'a' with prob 70% or a latin", "char=char_sampler, resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset_scale_fix(n_samples,", "attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), pixel_noise_scale=pixel_noise ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for font", "dataset_seed=seed) def generate_counting_dataset_scale_fix(n_samples, seed=None, **kwargs): \"\"\"Generate 3-10 symbols at fixed scale. Samples 'a'", "n_samples, dataset_seed=seed) def generate_natural_images_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Same as default dataset, but uses", "1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=True, is_bold=False, background=bg,", "([type], optional): [description]. Defaults to None. \"\"\" if alphabet is None: alphabet =", "scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_italic_dataset(n_samples, language=\"english\",", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for font classification # ----------------------- def less_variations(n_samples, language=\"english\",", "dataset_seed=seed) # for font classification # ----------------------- def less_variations(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Less", "language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d symbols from", "= SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), background=bg, foreground=fg, is_bold=False, is_slant=False, scale=1,", "language=\"english\", texture=\"camouflage\", seed=None, **kwarg): \"\"\"Generate a dataset where the pixel distribution is the", "**kwargs) def generate_counting_dataset_crowded(n_samples, seed=None, **kwargs): \"\"\"Generate 30-50 symbols at fixed scale. Samples 'a'", "alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) def attr_sampler(seed=None): char, alphabet", "return rng.choice(list(range(3, 10))) attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols, ) return", "scale=0.7, translation=translation, inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet_onlygrad(n_samples, chars, seed=None,", "with prob 70% or a latin lowercase otherwise. \"\"\" def n_symbols(rng): return rng.choice(list(range(30,", "30-50 symbols at fixed scale. Samples 'a' with prob 70% or a latin", "is_bold=False, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=None, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler,", "\"\"\" if n_symbols is None: def n_symbols(rng): return rng.choice(list(range(3, 10))) def scale(rng): return", "resolution in gray scale with scale of 1 and minimal variations. \"\"\" fg", "dataset_seed=seed) # for active learning # ------------------- def generate_large_translation(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Synbols", "200 per alphabet) with probability 50%. \"\"\" font_list = [] symbols_list = []", "language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1))", "**kwargs): \"\"\"Same as default dataset, but uses natural images as foreground and background.\"\"\"", "%d, n_symbols: %d.\", len(font_list), len(symbols_list)) def attr_sampler(seed=None): if np.random.rand() > 0.5: font, alphabet", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_camouflage_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False)", "bg = [SolidColor((0, 0, 0)), ImagePattern(seed=123)] attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars),", "basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), pixel_noise_scale=pixel_noise ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for font classification #", "inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_italic_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate", "None elif texture == \"bw\": fg = SolidColor((1, 1, 1)) bg = SolidColor((0,", "of 1 and minimal variations. \"\"\" fg = SolidColor((1, 1, 1)) bg =", "is_slant=False, is_bold=True, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler,", "\"\"\"Generate 3-10 symbols at fixed scale. Samples 'a' with prob 70% or a", "uses natural images as foreground and background.\"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), background=lambda rng:", "are font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False,", "def all_chars(n_samples, seed=None, **kwarg): \"\"\"Combines the symbols of all languages (up to 200", "generate_plain_gradient_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols. The only factors", "(up to 200 per languages). Note: some fonts may appear rarely. \"\"\" symbols_list", "70% or a latin lowercase otherwise. \"\"\" return generate_counting_dataset(n_samples, scale_variation=0, seed=seed, **kwargs) def", "for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() fonts = alphabet.fonts[:200] symbols = alphabet.symbols[:200]", "\"large-translation\": generate_large_translation, \"tiny\": generate_tiny_dataset, \"balanced-font-chars\": generate_balanced_font_chars_dataset, \"all-chars\": all_chars, \"less-variations\": less_variations, \"pixel-noise\": generate_pixel_noise, \"natural-patterns\":", "per languages). Note: some fonts may appear rarely. \"\"\" symbols_list = [] for", "**kwargs): \"\"\"Generate a gradient foreground and background dataset with same attribute distribution as", "\"\"\"Combines the symbols of all languages (up to 200 per languages). Note: some", "= basic_attribute_sampler(char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(fonts)) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_camouflage_dataset(n_samples,", "(lambda rng: rng.uniform(low=0, high=1)*math.pi) elif set == 'translation': translation= (lambda rng: tuple(rng.uniform(low=-1, high=1,", "return rng.choice(list(range(30, 50))) return generate_counting_dataset(n_samples, scale_variation=0.1, n_symbols=n_symbols, seed=seed, **kwargs) # for few-shot learning", "else: return 0 attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=n_occlusion, scale=lambda rng: 0.6 * np.exp(rng.randn()", "**kwarg): \"\"\"Add large pixel noise with probability 0.5.\"\"\" def pixel_noise(rng): if rng.rand() >", "pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_scaled_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\"", "0.7 * np.exp(np.random.randn() * 0.1) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg,", "with translation uniformly b/w (-1,1) \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1,", "dataset, using gradiant as foreground and background. \"\"\" attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()) return dataset_generator(attr_sampler,", "alphabet=LANGUAGE_MAP[language].get_alphabet(), scale=0.5, translation=lambda rng: tuple(rng.rand(2) * 4 - 2) ) return dataset_generator(attr_sampler, n_samples,", "\"\"\" def n_occlusion(rng): if rng.rand() < 0.2: return 1 else: return 0 attr_sampler", "[] symbols_list = [] for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() fonts =", "SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(), background=bg, foreground=fg)", "gradient foreground and background dataset with same attribute distribution as the camouflage dataset.", "symbol, alphabet = symbols_list[np.random.choice(len(symbols_list))] font = np.random.choice(alphabet.fonts[:200]) return basic_attribute_sampler(char=symbol, font=font, is_bold=False, is_slant=False)(seed) return", "def attr_sampler(seed=None): char, alphabet = symbols_list[np.random.choice(len(symbols_list))] return basic_attribute_sampler(alphabet=alphabet, char=char)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "is_bold=False, background=bg, foreground=fg, rotation=lambda rng: rng.uniform(low=0, high=1)*math.pi, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, )", "of variations are font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler(", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_balanced_font_chars_dataset(n_samples, seed=None, **kwarg): \"\"\"Samples uniformly from all fonts (max", "Image, Symbol from .fonts import LANGUAGE_MAP from .generate import ( dataset_generator, basic_attribute_sampler, flatten_mask,", "translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet(n_samples, chars, seed=None,", "rotations. Also, no bold and no italic. This makes a more accessible font", "default with translation uniformly b/w (-1,1) \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1,", "rotation = 0 translation = (0.0,0.0) if set == 'rotation': rotation = (lambda", "# ------------------------------------- def generate_segmentation_dataset(n_samples, language=\"english\", resolution=(128, 128), seed=None, **kwarg): \"\"\"Generate 3-10 symbols of", "font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return", "factors of variations are font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler =", "def generate_some_large_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With probability 20%, add a large occlusion over", "language=\"english\", seed=None, **kwarg): \"\"\"Generate the default dataset, using gradiant as foreground and background.", "to create a cropping effect. Scale is fixed to 0.5. \"\"\" attr_sampler =", "n_samples, dataset_seed=seed) def generate_plain_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg", "flatten_mask_except_first, dataset_seed=seed) def generate_many_small_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add small occlusions on all images.", "alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=True) fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0))", "= basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return", "**kwarg ): \"\"\"Generate 3-10 symbols at various scale. Samples 'a' with prob 70%", "alphabet %s\", len(fonts), len(alphabet.fonts), alphabet.name) font_list.extend(zip(fonts, [alphabet] * len(fonts))) logging.info(\"Using %d/%d symbols from", "lowercase otherwise. \"\"\" return generate_counting_dataset(n_samples, scale_variation=0, seed=seed, **kwargs) def generate_counting_dataset_crowded(n_samples, seed=None, **kwargs): \"\"\"Generate", "ImagePattern(seed=rand_seed(rng)), is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples,", "# for segmentation, detection, counting # ------------------------------------- def generate_segmentation_dataset(n_samples, language=\"english\", resolution=(128, 128), seed=None,", "Gradient(seed=rand_seed(_rng)) foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, )", "basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(), background=bg, foreground=fg) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_natural_images_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Same", "def generate_plain_gradient_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols. The only", "# for few-shot learning # --------------------- def all_chars(n_samples, seed=None, **kwarg): \"\"\"Combines the symbols", "len(fonts))) logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] *", "alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), background=bg, foreground=fg, is_bold=False, is_slant=False, scale=1, resolution=(8, 8), is_gray=True, ) return dataset_generator(attr_sampler, n_samples,", "SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(), background=bg, foreground=fg) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "= basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), background=lambda rng: ImagePattern(seed=rand_seed(rng)), foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), ) return dataset_generator(attr_sampler, n_samples,", "fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg = Camouflage(stroke_angle=angle + np.pi / 2,", "* np.exp(rng.randn() * 0.1), translation=lambda rng: tuple(rng.rand(2) * 6 - 3), ) return", "rotation=rotation, scale=0.7, translation=translation, inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet_onlygrad(n_samples, chars,", "generate_many_small_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add small occlusions on all images. Number of occlusions", "'a' with prob 70% or a latin lowercase otherwise. \"\"\" if n_symbols is", "seed=seed, **kwargs) def generate_counting_dataset_crowded(n_samples, seed=None, **kwargs): \"\"\"Generate 30-50 symbols at fixed scale. Samples", "logging.info(\"Using %d/%d fonts from alphabet %s\", len(fonts), len(alphabet.fonts), alphabet.name) font_list.extend(zip(fonts, [alphabet] * len(fonts)))", "10))) attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols, ) return dataset_generator(attr_generator, n_samples,", "to \"english\". seed ([type], optional): [description]. Defaults to None. \"\"\" if alphabet is", "all fonts (max 200 per alphabet) or uniformly from all symbols (max 200", "is_bold=True, is_slant=False, scale=scale, )(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_non_camou_bw_dataset(n_samples, language=\"english\", seed=None, **kwargs):", "variations in scale and rotations. Also, no bold and no italic. This makes", "camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"shade\", seed=seed, **kwargs) # for segmentation, detection,", "(no bold). \"\"\" def scale(rng): return 0.1 * np.exp(rng.randn() * 0.4) def n_symbols(rng):", "n_samples, dataset_seed=seed) def generate_default_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate the default dataset, using gradiant", "if texture == \"camouflage\": angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0)", "alphabet.symbols[:1000] fonts = alphabet.fonts attr_sampler = basic_attribute_sampler(char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(fonts)) return", "the same attribute distribution as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"bw\",", "rng: rng.choice(fonts)) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_camouflage_dataset(n_samples, language=\"english\", texture=\"camouflage\", seed=None, **kwarg): \"\"\"Generate", "pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_tiny_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate a", "np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) elif texture == \"shade\": fg, bg =", "attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False,", "tuple(rng.rand(2) * 6 - 3), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_many_small_occlusions(n_samples,", "more accessible font classification task. \"\"\" attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), is_bold=False, is_slant=False, scale=lambda", "a cropping effect. Scale is fixed to 0.5. \"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(),", "pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_natural_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white", "4 - 2) ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def missing_symbol_dataset(n_samples, language=\"english\", seed=None, **kwarg):", "if set == 'rotation': rotation = (lambda rng: rng.uniform(low=0, high=1)*math.pi) elif set ==", "various scale and rotation and translation (no bold). \"\"\" def scale(rng): return 0.1", "seed=None, **kwarg): \"\"\"Samples uniformly from all fonts (max 200 per alphabet) or uniformly", "scale. Samples 'a' with prob 70% or a latin lowercase otherwise. \"\"\" return", "no symbols are drawn\"\"\" def background(rng): return MultiGradient(alpha=0.5, n_gradients=2, types=(\"linear\", \"radial\"), seed=rand_seed(rng)) def", "set = \"plain\", seed=None, **kwargs): \"\"\"[summary] Args: n_samples ([type]): [description] language (str, optional):", "**kwarg): \"\"\"Generate a dataset of 8x8 resolution in gray scale with scale of", "seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda", "1000 korean symbols\"\"\" alphabet = LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True) chars = alphabet.symbols[:1000] fonts = alphabet.fonts attr_sampler", "scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet(n_samples, chars,", "to 0.5. \"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), scale=0.5, translation=lambda rng: tuple(rng.rand(2) * 4", "some fonts may appear rarely. \"\"\" symbols_list = [] for language in LANGUAGE_MAP.values():", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_italic_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on", "inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet_onlygrad(n_samples, chars, seed=None, **kwargs): \"\"\"", "return 0 attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=n_occlusion, scale=lambda rng: 0.6 * np.exp(rng.randn() *", "on all images. Number of occlusions are sampled uniformly in [0,5). \"\"\" attr_sampler", "\"some-large-occlusion\": generate_some_large_occlusions, \"many-small-occlusion\": generate_many_small_occlusions, \"large-translation\": generate_large_translation, \"tiny\": generate_tiny_dataset, \"balanced-font-chars\": generate_balanced_font_chars_dataset, \"all-chars\": all_chars, \"less-variations\":", "def generate_default_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate the default dataset, using gradiant as foreground", "classification task. \"\"\" attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), is_bold=False, is_slant=False, scale=lambda rng: 0.5 *", "np.random.rand() > 0.5: font, alphabet = font_list[np.random.choice(len(font_list))] symbol = np.random.choice(alphabet.symbols[:200]) else: symbol, alphabet", "n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset( n_samples, language=\"english\", resolution=(128, 128), n_symbols=None, scale_variation=0.5, seed=None, **kwarg", "= SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False),", "0)) attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), background=bg, foreground=fg, is_bold=False, is_slant=False, scale=1, resolution=(8, 8), is_gray=True,", "languages (up to 200 per languages). Note: some fonts may appear rarely. \"\"\"", "**kwarg): \"\"\"Generate a dataset where the pixel distribution is the same for the", "rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_camouflage_dataset(n_samples,", "**kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=True) fg = SolidColor((1, 1, 1)) bg =", "The only factors of variations are font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False)", "\"default\": generate_default_dataset, \"default-bw\": generate_solid_bg_dataset, \"korean-1k\": generate_korean_1k_dataset, \"camouflage\": generate_camouflage_dataset, \"non-camou-bw\": generate_non_camou_bw_dataset, \"non-camou-shade\": generate_non_camou_shade_dataset, \"segmentation\":", "all symbols (max 200 per alphabet) with probability 50%. \"\"\" font_list = []", "generate_balanced_font_chars_dataset(n_samples, seed=None, **kwarg): \"\"\"Samples uniformly from all fonts (max 200 per alphabet) or", "\"camouflage\": generate_camouflage_dataset, \"non-camou-bw\": generate_non_camou_bw_dataset, \"non-camou-shade\": generate_non_camou_shade_dataset, \"segmentation\": generate_segmentation_dataset, \"counting\": generate_counting_dataset, \"counting-fix-scale\": generate_counting_dataset_scale_fix, \"counting-crowded\":", "elif set == 'gradient': fg = None bg = None attr_sampler = basic_attribute_sampler(", "are font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, background=lambda", "def generate_counting_dataset( n_samples, language=\"english\", resolution=(128, 128), n_symbols=None, scale_variation=0.5, seed=None, **kwarg ): \"\"\"Generate 3-10", "is_slant=False, is_bold=False, background= lambda rng:rng.choice(bg), foreground= lambda rng:rng.choice(fg), rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False,", ".generate import ( dataset_generator, basic_attribute_sampler, flatten_mask, flatten_mask_except_first, add_occlusion, rand_seed, ) def generate_i(n_samples, alphabet", "foreground and background dataset with same attribute distribution as the camouflage dataset. \"\"\"", "stroke_width=0.1, stroke_length=0.6, stroke_noise=0) scale = 0.7 * np.exp(np.random.randn() * 0.1) attr_sampler = basic_attribute_sampler(", "translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_camouflage_dataset(n_samples, language=\"english\", seed=None,", "is_slant=False, scale=lambda rng: 0.5 * np.exp(rng.randn() * 0.1), rotation=lambda rng: rng.randn() * 0.1,", "SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=True,", "attr_sampler(seed=None): char, alphabet = symbols_list[np.random.choice(len(symbols_list))] return basic_attribute_sampler(alphabet=alphabet, char=char)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "\"\"\"Less variations in scale and rotations. Also, no bold and no italic. This", "def n_occlusion(rng): if rng.rand() < 0.2: return 1 else: return 0 attr_sampler =", "attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), background=lambda rng: ImagePattern(seed=rand_seed(rng)), foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), ) return dataset_generator(attr_sampler,", "scale(rng): return 0.1 * np.exp(rng.randn() * scale_variation) def char_sampler(rng): if rng.rand() < 0.3:", "the pixel distribution is the same for the foreground and background. \"\"\" def", "minimal variations. \"\"\" fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0))", "len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) logging.info(\"Total n_fonts: %d, n_symbols: %d.\", len(font_list), len(symbols_list))", "= 0 translation = (0.0,0.0) if set == 'rotation': rotation = (lambda rng:", "from all symbols (max 200 per alphabet) with probability 50%. \"\"\" font_list =", "learning # ------------------- def generate_large_translation(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Synbols are translated beyond the", "return generate_camouflage_dataset(n_samples, language=language, texture=\"shade\", seed=seed, **kwargs) # for segmentation, detection, counting # -------------------------------------", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_camouflage_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet", "for font classification # ----------------------- def less_variations(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Less variations in", "1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(), background=bg, foreground=fg) return dataset_generator(attr_sampler,", "alphabet = language.get_alphabet() fonts = alphabet.fonts[:200] symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d fonts from", "translation=translation, inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet_onlygrad(n_samples, chars, seed=None, **kwargs):", "< 0.2: return 1 else: return 0 attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=n_occlusion, scale=lambda", "[alphabet] * len(symbols))) def attr_sampler(seed=None): char, alphabet = symbols_list[np.random.choice(len(symbols_list))] return basic_attribute_sampler(alphabet=alphabet, char=char)(seed) return", "return dataset_generator(attr_generator, n_samples, dataset_seed=seed) def generate_some_large_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With probability 20%, add", "): \"\"\"Generate 3-10 symbols at various scale. Samples 'a' with prob 70% or", "scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_gradient_dataset(n_samples, language=\"english\",", "the border of the image to create a cropping effect. Scale is fixed", "\"\"\"Generate 3-10 symbols of various scale and rotation and translation (no bold). \"\"\"", "#print(alphabet.fonts[:10]) fg = [SolidColor((1, 1, 1)), ImagePattern(seed=123)] bg = [SolidColor((0, 0, 0)), ImagePattern(seed=123)]", "with prob 70% or a latin lowercase otherwise. \"\"\" if n_symbols is None:", "np.exp(np.random.randn() * 0.1) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=scale,", "\"plain\": generate_plain_dataset, \"default\": generate_default_dataset, \"default-bw\": generate_solid_bg_dataset, \"korean-1k\": generate_korean_1k_dataset, \"camouflage\": generate_camouflage_dataset, \"non-camou-bw\": generate_non_camou_bw_dataset, \"non-camou-shade\":", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_bold_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet =", "distribution as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"bw\", seed=seed, **kwargs) def", "= basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols, ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed)", "symbols_list[np.random.choice(len(symbols_list))] return basic_attribute_sampler(alphabet=alphabet, char=char)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_balanced_font_chars_dataset(n_samples, seed=None, **kwarg): \"\"\"Samples", "\"\"\"Generate white on black, centered symbols. The only factors of variations are font", "= SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=True, is_bold=False, background=bg, foreground=fg, rotation=0,", "in gray scale with scale of 1 and minimal variations. \"\"\" fg =", "def attr_sampler(seed=None): if texture == \"camouflage\": angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1,", "attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_solid_bg_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Same", "0.1) return basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True), background=bg, foreground=fg, is_bold=True, is_slant=False, scale=scale, )(seed) return dataset_generator(attr_sampler, n_samples,", "stroke_length=0.6, stroke_noise=0) elif texture == \"shade\": fg, bg = None, None elif texture", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_non_camou_bw_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a black and", "import Camouflage, NoPattern, SolidColor, MultiGradient, ImagePattern, Gradient, Image, Symbol from .fonts import LANGUAGE_MAP", "lambda rng:rng.choice(fg), rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples,", "rng: tuple(rng.uniform(low=-1, high=1, size=2))) elif set == 'gradient': fg = None bg =", "generate_camouflage_dataset, \"non-camou-bw\": generate_non_camou_bw_dataset, \"non-camou-shade\": generate_non_camou_shade_dataset, \"segmentation\": generate_segmentation_dataset, \"counting\": generate_counting_dataset, \"counting-fix-scale\": generate_counting_dataset_scale_fix, \"counting-crowded\": generate_counting_dataset_crowded,", "is_bold=False, background=bg, foreground=fg, rotation=0, scale=scale, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples,", "**kwargs) # for few-shot learning # --------------------- def all_chars(n_samples, seed=None, **kwarg): \"\"\"Combines the", "char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, rotation=0, scale=1.0,", "probability, no symbols are drawn\"\"\" def background(rng): return MultiGradient(alpha=0.5, n_gradients=2, types=(\"linear\", \"radial\"), seed=rand_seed(rng))", "rng: rng.uniform(low=0, high=1)*math.pi) elif set == 'translation': translation= (lambda rng: tuple(rng.uniform(low=-1, high=1, size=2)))", "small occlusions on all images. Number of occlusions are sampled uniformly in [0,5).", "pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet_onlygrad(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\"", "%s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) def attr_sampler(seed=None): char, alphabet =", "\"\"\" if alphabet is None: alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) print(alphabet) fg = SolidColor((1, 1,", "otherwise. \"\"\" if n_symbols is None: def n_symbols(rng): return rng.choice(list(range(3, 10))) def scale(rng):", "\"\"\" def attr_sampler(seed=None): if texture == \"camouflage\": angle = 0 fg = Camouflage(stroke_angle=angle,", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_scaled_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet", "and translation (no bold). \"\"\" def scale(rng): return 0.1 * np.exp(rng.randn() * 0.4)", "font_list[np.random.choice(len(font_list))] symbol = np.random.choice(alphabet.symbols[:200]) else: symbol, alphabet = symbols_list[np.random.choice(len(symbols_list))] font = np.random.choice(alphabet.fonts[:200]) return", "and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg =", "- 1) else: return 10 attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), translation=tr, background=background ) return", "n_samples, dataset_seed=seed) def generate_plain_gradient_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols.", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_rotated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet =", "rng.choice(list(range(3, 10))) def scale(rng): return 0.1 * np.exp(rng.randn() * scale_variation) def char_sampler(rng): if", "stroke_width=0.1, stroke_length=0.6, stroke_noise=0) elif texture == \"shade\": fg, bg = None, None elif", "= None attr_sampler = basic_attribute_sampler( alphabet=alphabet, font = font, is_slant=False, is_bold=False, background=bg, foreground=fg,", "scale of 1 and minimal variations. \"\"\" fg = SolidColor((1, 1, 1)) bg", "def generate_non_camou_bw_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a black and white dataset with the", "== \"camouflage\": angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg =", "seed=None, **kwarg ): \"\"\"Generate 3-10 symbols at various scale. Samples 'a' with prob", "attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, background=", "generate_counting_dataset_crowded(n_samples, seed=None, **kwargs): \"\"\"Generate 30-50 symbols at fixed scale. Samples 'a' with prob", "seed=None, **kwargs): \"\"\"Generate a gradient foreground and background dataset with same attribute distribution", "\"\"\"Add small occlusions on all images. Number of occlusions are sampled uniformly in", "a dataset of 8x8 resolution in gray scale with scale of 1 and", "0, 0)) attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(), background=bg, foreground=fg) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_natural_images_dataset(n_samples,", "fixed scale. Samples 'a' with prob 70% or a latin lowercase otherwise. \"\"\"", "def generate_plain_translated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate default with translation uniformly b/w (-1,1) \"\"\"", "10 attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), translation=tr, background=background ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) def", "basic_attribute_sampler(char=symbol, font=font, is_bold=False, is_slant=False)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for active learning #", "seed=rand_seed(rng)) def tr(rng): if rng.rand() > 0.1: return tuple(rng.rand(2) * 2 - 1)", "pixel_noise_scale=pixel_noise ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for font classification # ----------------------- def", "\"counting\": generate_counting_dataset, \"counting-fix-scale\": generate_counting_dataset_scale_fix, \"counting-crowded\": generate_counting_dataset_crowded, \"missing-symbol\": missing_symbol_dataset, \"some-large-occlusion\": generate_some_large_occlusions, \"many-small-occlusion\": generate_many_small_occlusions, \"large-translation\":", "uses white on black.\"\"\" fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0,", "rng: 0.6 * np.exp(rng.randn() * 0.1), translation=lambda rng: tuple(rng.rand(2) * 6 - 3),", "0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_italic_dataset(n_samples, language=\"english\", seed=None, **kwargs):", "== 'rotation': rotation = (lambda rng: rng.uniform(low=0, high=1)*math.pi) elif set == 'translation': translation=", "generate_large_translation(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Synbols are translated beyond the border of the image", "inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_tiny_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate", "of occlusions are sampled uniformly in [0,5). \"\"\" attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=lambda", "translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_natural_dataset(n_samples, language=\"english\", seed=None,", "= [SolidColor((1, 1, 1)), ImagePattern(seed=123)] bg = [SolidColor((0, 0, 0)), ImagePattern(seed=123)] attr_sampler =", "inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_natural_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate", "scale=None, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_bold_dataset(n_samples, language=\"english\",", "texture=\"camouflage\", seed=None, **kwarg): \"\"\"Generate a dataset where the pixel distribution is the same", "n_samples, language=\"english\", resolution=(128, 128), n_symbols=None, scale_variation=0.5, seed=None, **kwarg ): \"\"\"Generate 3-10 symbols at", "\"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=True) fg = SolidColor((1, 1, 1)) bg = SolidColor((0,", "\"\"\" def scale(rng): return 0.1 * np.exp(rng.randn() * 0.4) def n_symbols(rng): return rng.choice(list(range(3,", "**kwarg): \"\"\"Uses the first 1000 korean symbols\"\"\" alphabet = LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True) chars = alphabet.symbols[:1000]", "\"\"\"With 10% probability, no symbols are drawn\"\"\" def background(rng): return MultiGradient(alpha=0.5, n_gradients=2, types=(\"linear\",", "alphabet) or uniformly from all symbols (max 200 per alphabet) with probability 50%.", "1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(), background=bg, foreground=fg) return", "scale_variation=0.5, seed=None, **kwarg ): \"\"\"Generate 3-10 symbols at various scale. Samples 'a' with", "seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg", "with scale of 1 and minimal variations. \"\"\" fg = SolidColor((1, 1, 1))", "flatten_mask, dataset_seed=seed) def generate_counting_dataset_scale_fix(n_samples, seed=None, **kwargs): \"\"\"Generate 3-10 symbols at fixed scale. Samples", "2) ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def missing_symbol_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With 10%", "n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10])", "= 0.7 * np.exp(np.random.randn() * 0.1) return basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True), background=bg, foreground=fg, is_bold=True, is_slant=False,", "resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols, ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset( n_samples,", "alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0))", "char=char)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_balanced_font_chars_dataset(n_samples, seed=None, **kwarg): \"\"\"Samples uniformly from all", "dataset_seed=seed) def generate_non_camou_bw_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a black and white dataset with", "[SolidColor((1, 1, 1)), ImagePattern(seed=123)] bg = [SolidColor((0, 0, 0)), ImagePattern(seed=123)] attr_sampler = basic_attribute_sampler(", "alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_translated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate default with", "dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"bw\", seed=seed, **kwargs) def generate_non_camou_shade_dataset(n_samples, language=\"english\", seed=None, **kwargs):", "stroke_noise=0) bg = Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) elif texture", "0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=lambda rng: rng.uniform(low=0, high=1)*math.pi,", "is_bold=False, is_slant=False)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for active learning # ------------------- def", "\"\"\" return generate_counting_dataset(n_samples, scale_variation=0, seed=seed, **kwargs) def generate_counting_dataset_crowded(n_samples, seed=None, **kwargs): \"\"\"Generate 30-50 symbols", "alphabet.fonts attr_sampler = basic_attribute_sampler(char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(fonts)) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "languages). Note: some fonts may appear rarely. \"\"\" symbols_list = [] for language", "generate_counting_dataset_crowded, \"missing-symbol\": missing_symbol_dataset, \"some-large-occlusion\": generate_some_large_occlusions, \"many-small-occlusion\": generate_many_small_occlusions, \"large-translation\": generate_large_translation, \"tiny\": generate_tiny_dataset, \"balanced-font-chars\": generate_balanced_font_chars_dataset,", "\"tiny\": generate_tiny_dataset, \"balanced-font-chars\": generate_balanced_font_chars_dataset, \"all-chars\": all_chars, \"less-variations\": less_variations, \"pixel-noise\": generate_pixel_noise, \"natural-patterns\": generate_natural_images_dataset, }", "LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False,", "alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng:", "from .drawing import Camouflage, NoPattern, SolidColor, MultiGradient, ImagePattern, Gradient, Image, Symbol from .fonts", "generate_counting_dataset_scale_fix, \"counting-crowded\": generate_counting_dataset_crowded, \"missing-symbol\": missing_symbol_dataset, \"some-large-occlusion\": generate_some_large_occlusions, \"many-small-occlusion\": generate_many_small_occlusions, \"large-translation\": generate_large_translation, \"tiny\": generate_tiny_dataset,", "* len(symbols))) logging.info(\"Total n_fonts: %d, n_symbols: %d.\", len(font_list), len(symbols_list)) def attr_sampler(seed=None): if np.random.rand()", "0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_camouflage_dataset(n_samples, language=\"english\", seed=None, **kwargs):", "basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols, ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def", "return 0 else: return 0.3 attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), pixel_noise_scale=pixel_noise ) return dataset_generator(attr_sampler,", "pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_camouflage_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\"", "foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet", "resolution=(128, 128), n_symbols=None, scale_variation=0.5, seed=None, **kwarg ): \"\"\"Generate 3-10 symbols at various scale.", "def char_sampler(rng): if rng.rand() < 0.3: return rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols) else: return \"a\" attr_generator =", "variations. \"\"\" fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler", "pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_rotated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\"", "white on black, centered symbols. The only factors of variations are font and", "per alphabet) with probability 50%. \"\"\" font_list = [] symbols_list = [] for", "n_samples, dataset_seed=seed) def generate_solid_bg_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Same as default datasets, but uses", "and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, rotation=0,", "Samples 'a' with prob 70% or a latin lowercase otherwise. \"\"\" return generate_counting_dataset(n_samples,", "[alphabet] * len(symbols))) logging.info(\"Total n_fonts: %d, n_symbols: %d.\", len(font_list), len(symbols_list)) def attr_sampler(seed=None): if", "alphabet = symbols_list[np.random.choice(len(symbols_list))] font = np.random.choice(alphabet.fonts[:200]) return basic_attribute_sampler(char=symbol, font=font, is_bold=False, is_slant=False)(seed) return dataset_generator(attr_sampler,", "def pixel_noise(rng): if rng.rand() > 0.1: return 0 else: return 0.3 attr_sampler =", "dataset_generator(attr_generator, n_samples, dataset_seed=seed) def generate_some_large_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With probability 20%, add a", "LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) fg = [SolidColor((1, 1, 1)), ImagePattern(seed=123)] bg = [SolidColor((0, 0, 0)),", "language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) angle = 0 fg =", "background=bg, foreground=fg, is_bold=True, is_slant=False, scale=scale, )(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_non_camou_bw_dataset(n_samples, language=\"english\",", "rng: tuple(rng.uniform(low=-1, high=1, size=2)), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_scaled_dataset(n_samples,", "\"korean-1k\": generate_korean_1k_dataset, \"camouflage\": generate_camouflage_dataset, \"non-camou-bw\": generate_non_camou_bw_dataset, \"non-camou-shade\": generate_non_camou_shade_dataset, \"segmentation\": generate_segmentation_dataset, \"counting\": generate_counting_dataset, \"counting-fix-scale\":", "rng: rng.uniform(low=0, high=1)*math.pi, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "\"\"\"Generate a dataset of 8x8 resolution in gray scale with scale of 1", "in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d symbols from alphabet", "bg = SolidColor((0, 0, 0)) else: raise ValueError(\"Unknown texture %s.\" % texture) scale", "{ \"plain\": generate_plain_dataset, \"default\": generate_default_dataset, \"default-bw\": generate_solid_bg_dataset, \"korean-1k\": generate_korean_1k_dataset, \"camouflage\": generate_camouflage_dataset, \"non-camou-bw\": generate_non_camou_bw_dataset,", "attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, )", "add a large occlusion over the existing symbol. \"\"\" def n_occlusion(rng): if rng.rand()", "dataset_seed=seed) def generate_some_large_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With probability 20%, add a large occlusion", "fonts = alphabet.fonts attr_sampler = basic_attribute_sampler(char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(fonts)) return dataset_generator(attr_sampler,", "* 0.1), rotation=lambda rng: rng.randn() * 0.1, ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) DATASET_GENERATOR_MAP", "alphabet = font_list[np.random.choice(len(font_list))] symbol = np.random.choice(alphabet.symbols[:200]) else: symbol, alphabet = symbols_list[np.random.choice(len(symbols_list))] font =", "seed=None, **kwarg): \"\"\"With 10% probability, no symbols are drawn\"\"\" def background(rng): return MultiGradient(alpha=0.5,", "2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) elif texture == \"shade\": fg, bg = None, None", "are drawn\"\"\" def background(rng): return MultiGradient(alpha=0.5, n_gradients=2, types=(\"linear\", \"radial\"), seed=rand_seed(rng)) def tr(rng): if", "1, 1)), ImagePattern(seed=123)] bg = [SolidColor((0, 0, 0)), ImagePattern(seed=123)] attr_sampler = basic_attribute_sampler( alphabet=alphabet,", "a latin lowercase otherwise. \"\"\" def n_symbols(rng): return rng.choice(list(range(30, 50))) return generate_counting_dataset(n_samples, scale_variation=0.1,", "generate_large_translation, \"tiny\": generate_tiny_dataset, \"balanced-font-chars\": generate_balanced_font_chars_dataset, \"all-chars\": all_chars, \"less-variations\": less_variations, \"pixel-noise\": generate_pixel_noise, \"natural-patterns\": generate_natural_images_dataset,", "font=lambda rng: rng.choice(fonts)) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_camouflage_dataset(n_samples, language=\"english\", texture=\"camouflage\", seed=None, **kwarg):", "lowercase otherwise. \"\"\" def n_symbols(rng): return rng.choice(list(range(30, 50))) return generate_counting_dataset(n_samples, scale_variation=0.1, n_symbols=n_symbols, seed=seed,", "seed=seed, **kwargs) def generate_non_camou_shade_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a gradient foreground and background", "dataset_generator(attr_generator, n_samples, dataset_seed=seed) DATASET_GENERATOR_MAP = { \"plain\": generate_plain_dataset, \"default\": generate_default_dataset, \"default-bw\": generate_solid_bg_dataset, \"korean-1k\":", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_italic_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black,", "= np.random.choice(alphabet.symbols[:200]) else: symbol, alphabet = symbols_list[np.random.choice(len(symbols_list))] font = np.random.choice(alphabet.fonts[:200]) return basic_attribute_sampler(char=symbol, font=font,", "= [SolidColor((0, 0, 0)), ImagePattern(seed=123)] attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda", "symbols are drawn\"\"\" def background(rng): return MultiGradient(alpha=0.5, n_gradients=2, types=(\"linear\", \"radial\"), seed=rand_seed(rng)) def tr(rng):", "in [0,5). \"\"\" attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=lambda rng: rng.randint(0, 5), ) return", "is_bold=True, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples,", "rotation=0, scale=scale, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_tiny_dataset(n_samples,", "%d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) def", "'translation': translation= (lambda rng: tuple(rng.uniform(low=-1, high=1, size=2))) elif set == 'gradient': fg =", "return \"a\" attr_generator = basic_attribute_sampler( char=char_sampler, resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols ) return dataset_generator(attr_generator,", "image to create a cropping effect. Scale is fixed to 0.5. \"\"\" attr_sampler", "font classification task. \"\"\" attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), is_bold=False, is_slant=False, scale=lambda rng: 0.5", "first 1000 korean symbols\"\"\" alphabet = LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True) chars = alphabet.symbols[:1000] fonts = alphabet.fonts", "language=language, texture=\"shade\", seed=seed, **kwargs) # for segmentation, detection, counting # ------------------------------------- def generate_segmentation_dataset(n_samples,", "= Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) elif texture == \"shade\":", "generate_default_dataset, \"default-bw\": generate_solid_bg_dataset, \"korean-1k\": generate_korean_1k_dataset, \"camouflage\": generate_camouflage_dataset, \"non-camou-bw\": generate_non_camou_bw_dataset, \"non-camou-shade\": generate_non_camou_shade_dataset, \"segmentation\": generate_segmentation_dataset,", "dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_many_small_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add small occlusions on", "1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), background=bg, foreground=fg,", "basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler,", "scale_variation=0.1, n_symbols=n_symbols, seed=seed, **kwargs) # for few-shot learning # --------------------- def all_chars(n_samples, seed=None,", "from alphabet %s\", len(fonts), len(alphabet.fonts), alphabet.name) font_list.extend(zip(fonts, [alphabet] * len(fonts))) logging.info(\"Using %d/%d symbols", "font = font, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=rotation, scale=0.7, translation=translation, inverse_color=False, pixel_noise_scale=0.0, )", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for font classification # ----------------------- def less_variations(n_samples, language=\"english\", seed=None,", "\"\"\"Same as default dataset, but uses natural images as foreground and background.\"\"\" attr_sampler", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_default_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate the default dataset,", "background=bg, foreground=fg, is_bold=False, is_slant=False, scale=1, resolution=(8, 8), is_gray=True, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "is_slant=False, scale=scale, )(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_non_camou_bw_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate", "def n_symbols(rng): return rng.choice(list(range(3, 10))) attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols,", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_translated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate default with translation uniformly", "= basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), is_bold=False, is_slant=False, scale=lambda rng: 0.5 * np.exp(rng.randn() * 0.1), rotation=lambda", "\"\"\"Generate the default dataset, using gradiant as foreground and background. \"\"\" attr_sampler =", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_gradient_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered", "**kwarg): \"\"\"Samples uniformly from all fonts (max 200 per alphabet) or uniformly from", "probability 20%, add a large occlusion over the existing symbol. \"\"\" def n_occlusion(rng):", "This makes a more accessible font classification task. \"\"\" attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(),", "no bold and no italic. This makes a more accessible font classification task.", "* 0.1) return basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True), background=bg, foreground=fg, is_bold=True, is_slant=False, scale=scale, )(seed) return dataset_generator(attr_sampler,", "== 'translation': translation= (lambda rng: tuple(rng.uniform(low=-1, high=1, size=2))) elif set == 'gradient': fg", "LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler =", "tuple(rng.uniform(low=-1, high=1, size=2))) elif set == 'gradient': fg = None bg = None", "----------------------- def less_variations(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Less variations in scale and rotations. Also,", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for active learning # ------------------- def generate_large_translation(n_samples, language=\"english\",", "0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_translated_dataset(n_samples, language=\"english\", seed=None, **kwargs):", "attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), background=bg, foreground=fg, is_bold=False, is_slant=False, scale=1, resolution=(8, 8), is_gray=True, )", "few-shot learning # --------------------- def all_chars(n_samples, seed=None, **kwarg): \"\"\"Combines the symbols of all", "def generate_many_small_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add small occlusions on all images. Number of", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_bold_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet", "6 - 3), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_many_small_occlusions(n_samples, language=\"english\", seed=None,", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_solid_bg_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Same as default datasets, but", "\"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=True) fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0,", "(lambda rng: tuple(rng.uniform(low=-1, high=1, size=2))) elif set == 'gradient': fg = None bg", "char, alphabet = symbols_list[np.random.choice(len(symbols_list))] return basic_attribute_sampler(alphabet=alphabet, char=char)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_balanced_font_chars_dataset(n_samples,", "images. Number of occlusions are sampled uniformly in [0,5). \"\"\" attr_sampler = add_occlusion(", "200 per languages). Note: some fonts may appear rarely. \"\"\" symbols_list = []", "= basic_attribute_sampler( alphabet=alphabet, is_slant=True, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0,", "background=background ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) def generate_some_large_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With probability", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_natural_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered", "drawn\"\"\" def background(rng): return MultiGradient(alpha=0.5, n_gradients=2, types=(\"linear\", \"radial\"), seed=rand_seed(rng)) def tr(rng): if rng.rand()", "= LANGUAGE_MAP[language].get_alphabet(support_bold=False) print(alphabet) fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0))", "the symbols of all languages (up to 200 per languages). Note: some fonts", "and background.\"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), background=lambda rng: ImagePattern(seed=rand_seed(rng)), foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), )", "1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), background=bg, foreground=fg, is_bold=False,", "flatten_mask_except_first, dataset_seed=seed) def generate_pixel_noise(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add large pixel noise with probability", "alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols, ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset(", "0.4) def n_symbols(rng): return rng.choice(list(range(3, 10))) attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), resolution=resolution, scale=scale, is_bold=False,", "flatten_mask, flatten_mask_except_first, add_occlusion, rand_seed, ) def generate_i(n_samples, alphabet = None, language=\"english\", font =", "0.5: font, alphabet = font_list[np.random.choice(len(font_list))] symbol = np.random.choice(alphabet.symbols[:200]) else: symbol, alphabet = symbols_list[np.random.choice(len(symbols_list))]", "italic. This makes a more accessible font classification task. \"\"\" attr_generator = basic_attribute_sampler(", "\"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars),", "ValueError(\"Unknown texture %s.\" % texture) scale = 0.7 * np.exp(np.random.randn() * 0.1) return", "seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) fg = [SolidColor((1, 1, 1)),", "= basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, rotation=0, scale=0.7,", "generate_non_camou_shade_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a gradient foreground and background dataset with same", "char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg = SolidColor((0,", "dataset_seed=seed) def generate_default_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate the default dataset, using gradiant as", "n_samples, dataset_seed=seed) def generate_plain_bold_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=True) fg", "language=\"english\", seed=None, **kwargs): \"\"\"Generate a gradient foreground and background dataset with same attribute", "translation=lambda rng: tuple(rng.rand(2) * 6 - 3), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed)", "\"\"\"Generate 30-50 symbols at fixed scale. Samples 'a' with prob 70% or a", "rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples,", "default dataset, using gradiant as foreground and background. \"\"\" attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()) return", "0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset(n_samples, language=\"english\", seed=None, **kwargs):", "\"bw\": fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) else: raise", "n_samples, dataset_seed=seed) def generate_balanced_font_chars_dataset(n_samples, seed=None, **kwarg): \"\"\"Samples uniformly from all fonts (max 200", "**kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg =", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_camouflage_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet =", "n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet_onlygrad(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10])", "2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) scale = 0.7 * np.exp(np.random.randn() * 0.1) attr_sampler =", "n_symbols=n_symbols ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset_scale_fix(n_samples, seed=None, **kwargs): \"\"\"Generate 3-10", "rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, background= lambda rng:rng.choice(bg), foreground= lambda rng:rng.choice(fg),", "return 1 else: return 0 attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=n_occlusion, scale=lambda rng: 0.6", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_rotated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False)", "len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) def attr_sampler(seed=None): char, alphabet = symbols_list[np.random.choice(len(symbols_list))]", "is the same for the foreground and background. \"\"\" def attr_sampler(seed=None): if texture", "alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return", "basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, )", "n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_many_small_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add small occlusions on all", "font = 'calibri', set = \"plain\", seed=None, **kwargs): \"\"\"[summary] Args: n_samples ([type]): [description]", "rarely. \"\"\" symbols_list = [] for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() symbols", "symbol = np.random.choice(alphabet.symbols[:200]) else: symbol, alphabet = symbols_list[np.random.choice(len(symbols_list))] font = np.random.choice(alphabet.fonts[:200]) return basic_attribute_sampler(char=symbol,", "attr_sampler(seed=None): if np.random.rand() > 0.5: font, alphabet = font_list[np.random.choice(len(font_list))] symbol = np.random.choice(alphabet.symbols[:200]) else:", "resolution=(128, 128), seed=None, **kwarg): \"\"\"Generate 3-10 symbols of various scale and rotation and", "dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset( n_samples, language=\"english\", resolution=(128, 128), n_symbols=None, scale_variation=0.5, seed=None,", "makes a more accessible font classification task. \"\"\" attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), is_bold=False,", "- 2) ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def missing_symbol_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With", "\"many-small-occlusion\": generate_many_small_occlusions, \"large-translation\": generate_large_translation, \"tiny\": generate_tiny_dataset, \"balanced-font-chars\": generate_balanced_font_chars_dataset, \"all-chars\": all_chars, \"less-variations\": less_variations, \"pixel-noise\":", "stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg = Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0)", "border of the image to create a cropping effect. Scale is fixed to", "import numpy as np import math from .drawing import Camouflage, NoPattern, SolidColor, MultiGradient,", "for active learning # ------------------- def generate_large_translation(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Synbols are translated", "\"\"\"Synbols are translated beyond the border of the image to create a cropping", "0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=0.7, translation=(0.0,", "rng:rng.choice(bg), foreground= lambda rng:rng.choice(fg), rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler,", "return dataset_generator(attr_generator, n_samples, dataset_seed=seed) DATASET_GENERATOR_MAP = { \"plain\": generate_plain_dataset, \"default\": generate_default_dataset, \"default-bw\": generate_solid_bg_dataset,", "0 else: return 0.3 attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), pixel_noise_scale=pixel_noise ) return dataset_generator(attr_sampler, n_samples,", "n_symbols(rng): return rng.choice(list(range(30, 50))) return generate_counting_dataset(n_samples, scale_variation=0.1, n_symbols=n_symbols, seed=seed, **kwargs) # for few-shot", "if rng.rand() < 0.3: return rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols) else: return \"a\" attr_generator = basic_attribute_sampler( char=char_sampler,", "# for active learning # ------------------- def generate_large_translation(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Synbols are", "= symbols_list[np.random.choice(len(symbols_list))] font = np.random.choice(alphabet.fonts[:200]) return basic_attribute_sampler(char=symbol, font=font, is_bold=False, is_slant=False)(seed) return dataset_generator(attr_sampler, n_samples,", "\"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0,", "generate_counting_dataset, \"counting-fix-scale\": generate_counting_dataset_scale_fix, \"counting-crowded\": generate_counting_dataset_crowded, \"missing-symbol\": missing_symbol_dataset, \"some-large-occlusion\": generate_some_large_occlusions, \"many-small-occlusion\": generate_many_small_occlusions, \"large-translation\": generate_large_translation,", "( dataset_generator, basic_attribute_sampler, flatten_mask, flatten_mask_except_first, add_occlusion, rand_seed, ) def generate_i(n_samples, alphabet = None,", "**kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) fg = [SolidColor((1, 1, 1)), ImagePattern(seed=123)]", "generate_some_large_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With probability 20%, add a large occlusion over the", "rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet(n_samples,", "per alphabet) or uniformly from all symbols (max 200 per alphabet) with probability", "+ np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) elif texture == \"shade\": fg, bg", "def generate_natural_images_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Same as default dataset, but uses natural images", "def generate_camouflage_dataset(n_samples, language=\"english\", texture=\"camouflage\", seed=None, **kwarg): \"\"\"Generate a dataset where the pixel distribution", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_tiny_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate a dataset", "else: return \"a\" attr_generator = basic_attribute_sampler( char=char_sampler, resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols ) return", "import math from .drawing import Camouflage, NoPattern, SolidColor, MultiGradient, ImagePattern, Gradient, Image, Symbol", "**kwarg): \"\"\"Add small occlusions on all images. Number of occlusions are sampled uniformly", "def generate_plain_rotated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1,", "n_samples, dataset_seed=seed) def generate_plain_italic_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols.", "from all fonts (max 200 per alphabet) or uniformly from all symbols (max", "return rng.choice(list(range(3, 10))) def scale(rng): return 0.1 * np.exp(rng.randn() * scale_variation) def char_sampler(rng):", "def n_symbols(rng): return rng.choice(list(range(30, 50))) return generate_counting_dataset(n_samples, scale_variation=0.1, n_symbols=n_symbols, seed=seed, **kwargs) # for", "return 0.3 attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), pixel_noise_scale=pixel_noise ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) #", "and background. \"\"\" def attr_sampler(seed=None): if texture == \"camouflage\": angle = 0 fg", "texture %s.\" % texture) scale = 0.7 * np.exp(np.random.randn() * 0.1) return basic_attribute_sampler(", "generate_i(n_samples, alphabet = None, language=\"english\", font = 'calibri', set = \"plain\", seed=None, **kwargs):", "background. \"\"\" attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_solid_bg_dataset(n_samples, language=\"english\", seed=None,", "symbols of all languages (up to 200 per languages). Note: some fonts may", "flatten_mask_except_first, add_occlusion, rand_seed, ) def generate_i(n_samples, alphabet = None, language=\"english\", font = 'calibri',", "\"\"\"Add large pixel noise with probability 0.5.\"\"\" def pixel_noise(rng): if rng.rand() > 0.1:", "70% or a latin lowercase otherwise. \"\"\" def n_symbols(rng): return rng.choice(list(range(30, 50))) return", "distribution as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"shade\", seed=seed, **kwargs) #", "import logging import numpy as np import math from .drawing import Camouflage, NoPattern,", "the existing symbol. \"\"\" def n_occlusion(rng): if rng.rand() < 0.2: return 1 else:", "0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_bold_dataset(n_samples, language=\"english\", seed=None, **kwargs):", "= basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), background=bg, foreground=fg, is_bold=False, is_slant=False, scale=1, resolution=(8, 8), is_gray=True, ) return", "scale and rotation and translation (no bold). \"\"\" def scale(rng): return 0.1 *", "b/w (-1,1) \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg =", "* scale_variation) def char_sampler(rng): if rng.rand() < 0.3: return rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols) else: return \"a\"", "active learning # ------------------- def generate_large_translation(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Synbols are translated beyond", "gradiant as foreground and background. \"\"\" attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "types=(\"linear\", \"radial\"), seed=rand_seed(rng)) def tr(rng): if rng.rand() > 0.1: return tuple(rng.rand(2) * 2", "prob 70% or a latin lowercase otherwise. \"\"\" if n_symbols is None: def", "alphabet is None: alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) print(alphabet) fg = SolidColor((1, 1, 1)) bg", "same attribute distribution as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"shade\", seed=seed,", "probability 0.5.\"\"\" def pixel_noise(rng): if rng.rand() > 0.1: return 0 else: return 0.3", "dataset_seed=seed) def generate_many_small_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add small occlusions on all images. Number", "= Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) scale = 0.7 *", "0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=None, translation=(0.0,", "rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_rotated_dataset(n_samples,", "dataset with same attribute distribution as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language,", "0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet(n_samples, chars, seed=None, **kwargs):", "128), seed=None, **kwarg): \"\"\"Generate 3-10 symbols of various scale and rotation and translation", "high=1, size=2))) elif set == 'gradient': fg = None bg = None attr_sampler", "for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d symbols", "is_slant=False)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for active learning # ------------------- def generate_large_translation(n_samples,", "missing_symbol_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With 10% probability, no symbols are drawn\"\"\" def background(rng):", "# --------------------- def all_chars(n_samples, seed=None, **kwarg): \"\"\"Combines the symbols of all languages (up", ".fonts import LANGUAGE_MAP from .generate import ( dataset_generator, basic_attribute_sampler, flatten_mask, flatten_mask_except_first, add_occlusion, rand_seed,", "* 0.1, ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) DATASET_GENERATOR_MAP = { \"plain\": generate_plain_dataset, \"default\":", "language=\"english\", seed=None, **kwargs): \"\"\"Generate a black and white dataset with the same attribute", "resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset_scale_fix(n_samples, seed=None,", "None: def n_symbols(rng): return rng.choice(list(range(3, 10))) def scale(rng): return 0.1 * np.exp(rng.randn() *", "return basic_attribute_sampler(alphabet=alphabet, char=char)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_balanced_font_chars_dataset(n_samples, seed=None, **kwarg): \"\"\"Samples uniformly", "font classification # ----------------------- def less_variations(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Less variations in scale", "is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=scale, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler,", "alphabet = symbols_list[np.random.choice(len(symbols_list))] return basic_attribute_sampler(alphabet=alphabet, char=char)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_balanced_font_chars_dataset(n_samples, seed=None,", "= None, None elif texture == \"bw\": fg = SolidColor((1, 1, 1)) bg", "generate_counting_dataset(n_samples, scale_variation=0, seed=seed, **kwargs) def generate_counting_dataset_crowded(n_samples, seed=None, **kwargs): \"\"\"Generate 30-50 symbols at fixed", "black and white dataset with the same attribute distribution as the camouflage dataset.", "bg = SolidColor((0, 0, 0)) rotation = 0 translation = (0.0,0.0) if set", "if alphabet is None: alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) print(alphabet) fg = SolidColor((1, 1, 1))", "None: alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) print(alphabet) fg = SolidColor((1, 1, 1)) bg = SolidColor((0,", "rng: ImagePattern(seed=rand_seed(rng)), #lambda rng: Gradient(seed=rand_seed(_rng)) foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0,", "10))) def scale(rng): return 0.1 * np.exp(rng.randn() * scale_variation) def char_sampler(rng): if rng.rand()", "char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, background=lambda rng: ImagePattern(seed=rand_seed(rng)), #lambda", "math from .drawing import Camouflage, NoPattern, SolidColor, MultiGradient, ImagePattern, Gradient, Image, Symbol from", "with the same attribute distribution as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language,", "%s\", len(fonts), len(alphabet.fonts), alphabet.name) font_list.extend(zip(fonts, [alphabet] * len(fonts))) logging.info(\"Using %d/%d symbols from alphabet", "for few-shot learning # --------------------- def all_chars(n_samples, seed=None, **kwarg): \"\"\"Combines the symbols of", "dataset with the same attribute distribution as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples,", "\"english\". seed ([type], optional): [description]. Defaults to None. \"\"\" if alphabet is None:", "foreground= lambda rng:rng.choice(fg), rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples,", "DATASET_GENERATOR_MAP = { \"plain\": generate_plain_dataset, \"default\": generate_default_dataset, \"default-bw\": generate_solid_bg_dataset, \"korean-1k\": generate_korean_1k_dataset, \"camouflage\": generate_camouflage_dataset,", "alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) logging.info(\"Total n_fonts: %d, n_symbols:", "texture) scale = 0.7 * np.exp(np.random.randn() * 0.1) return basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True), background=bg, foreground=fg,", "= font, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=rotation, scale=0.7, translation=translation, inverse_color=False, pixel_noise_scale=0.0, ) return", "symbols at fixed scale. Samples 'a' with prob 70% or a latin lowercase", "generate_korean_1k_dataset(n_samples, seed=None, **kwarg): \"\"\"Uses the first 1000 korean symbols\"\"\" alphabet = LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True) chars", "all_chars(n_samples, seed=None, **kwarg): \"\"\"Combines the symbols of all languages (up to 200 per", "language=\"english\", seed=None, **kwarg): \"\"\"Less variations in scale and rotations. Also, no bold and", "translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_tiny_dataset(n_samples, language=\"english\", seed=None,", "natural images as foreground and background.\"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), background=lambda rng: ImagePattern(seed=rand_seed(rng)),", "foreground=fg, rotation=rotation, scale=0.7, translation=translation, inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet_onlygrad(n_samples,", "0.2: return 1 else: return 0 attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=n_occlusion, scale=lambda rng:", "\"\"\"Same as default datasets, but uses white on black.\"\"\" fg = SolidColor((1, 1,", "return 10 attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), translation=tr, background=background ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed)", "with prob 70% or a latin lowercase otherwise. \"\"\" return generate_counting_dataset(n_samples, scale_variation=0, seed=seed,", "seed=None, **kwarg): \"\"\"Synbols are translated beyond the border of the image to create", "scale_variation=0, seed=seed, **kwargs) def generate_counting_dataset_crowded(n_samples, seed=None, **kwargs): \"\"\"Generate 30-50 symbols at fixed scale.", "tuple(rng.uniform(low=-1, high=1, size=2)), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_scaled_dataset(n_samples, language=\"english\",", "= [] symbols_list = [] for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() fonts", "bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg,", "pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_italic_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white", "\"shade\": fg, bg = None, None elif texture == \"bw\": fg = SolidColor((1,", "\"non-camou-shade\": generate_non_camou_shade_dataset, \"segmentation\": generate_segmentation_dataset, \"counting\": generate_counting_dataset, \"counting-fix-scale\": generate_counting_dataset_scale_fix, \"counting-crowded\": generate_counting_dataset_crowded, \"missing-symbol\": missing_symbol_dataset, \"some-large-occlusion\":", "np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) scale = 0.7 * np.exp(np.random.randn() * 0.1)", "is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=lambda rng: tuple(rng.uniform(low=-1, high=1, size=2)), inverse_color=False, pixel_noise_scale=0.0,", "generate_camouflage_dataset(n_samples, language=\"english\", texture=\"camouflage\", seed=None, **kwarg): \"\"\"Generate a dataset where the pixel distribution is", "rng: Gradient(seed=rand_seed(_rng)) foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0,", "scale=lambda rng: 0.5 * np.exp(rng.randn() * 0.1), rotation=lambda rng: rng.randn() * 0.1, )", "generate_default_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate the default dataset, using gradiant as foreground and", "is_slant=False, is_bold=False, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "def generate_korean_1k_dataset(n_samples, seed=None, **kwarg): \"\"\"Uses the first 1000 korean symbols\"\"\" alphabet = LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True)", "and white dataset with the same attribute distribution as the camouflage dataset. \"\"\"", "1) else: return 10 attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), translation=tr, background=background ) return dataset_generator(attr_generator,", "/ 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) elif texture == \"shade\": fg, bg = None,", "alphabet = LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True) chars = alphabet.symbols[:1000] fonts = alphabet.fonts attr_sampler = basic_attribute_sampler(char=lambda rng:", "Gradient, Image, Symbol from .fonts import LANGUAGE_MAP from .generate import ( dataset_generator, basic_attribute_sampler,", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet =", "seed=None, **kwargs): \"\"\"Generate white on black, centered symbols. The only factors of variations", "chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) attr_sampler = basic_attribute_sampler( alphabet=alphabet,", "rng: rng.randint(0, 5), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_pixel_noise(n_samples, language=\"english\", seed=None,", "stroke_length=0.6, stroke_noise=0) bg = Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) scale", "dataset where the pixel distribution is the same for the foreground and background.", "raise ValueError(\"Unknown texture %s.\" % texture) scale = 0.7 * np.exp(np.random.randn() * 0.1)", "and background dataset with same attribute distribution as the camouflage dataset. \"\"\" return", "stroke_length=0.6, stroke_noise=0) bg = Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) elif", "font_list = [] symbols_list = [] for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet()", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_natural_images_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Same as default dataset,", "ImagePattern(seed=rand_seed(rng)), ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_korean_1k_dataset(n_samples, seed=None, **kwarg): \"\"\"Uses the first", "dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_pixel_noise(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add large pixel noise", "of all languages (up to 200 per languages). Note: some fonts may appear", "inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"", "inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_camouflage_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"", "rng.choice(fonts)) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_camouflage_dataset(n_samples, language=\"english\", texture=\"camouflage\", seed=None, **kwarg): \"\"\"Generate a", ".drawing import Camouflage, NoPattern, SolidColor, MultiGradient, ImagePattern, Gradient, Image, Symbol from .fonts import", "[description]. Defaults to None. \"\"\" if alphabet is None: alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) print(alphabet)", "= language.get_alphabet() symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols),", "0.5.\"\"\" def pixel_noise(rng): if rng.rand() > 0.1: return 0 else: return 0.3 attr_sampler", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet", "alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True), background=bg, foreground=fg, is_bold=True, is_slant=False, scale=scale, )(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_non_camou_bw_dataset(n_samples,", "foreground=fg, rotation=0, scale=1.0, translation=lambda rng: tuple(rng.uniform(low=-1, high=1, size=2)), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler,", "SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=lambda rng:", "is_gray=True, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_default_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate the", "basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=None, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, )", "0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg = Camouflage(stroke_angle=angle + np.pi /", "texture == \"bw\": fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0))", "alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=lambda rng: tuple(rng.uniform(low=-1, high=1, size=2)), inverse_color=False,", "= LANGUAGE_MAP[language].get_alphabet(support_bold=True) fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler", "and background. \"\"\" attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_solid_bg_dataset(n_samples, language=\"english\",", "rng: ImagePattern(seed=rand_seed(rng)), is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler,", "70% or a latin lowercase otherwise. \"\"\" if n_symbols is None: def n_symbols(rng):", "\"camouflage\": angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg = Camouflage(stroke_angle=angle", "alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) logging.info(\"Total n_fonts: %d, n_symbols: %d.\", len(font_list), len(symbols_list)) def", "as np import math from .drawing import Camouflage, NoPattern, SolidColor, MultiGradient, ImagePattern, Gradient,", "def attr_sampler(seed=None): if np.random.rand() > 0.5: font, alphabet = font_list[np.random.choice(len(font_list))] symbol = np.random.choice(alphabet.symbols[:200])", "effect. Scale is fixed to 0.5. \"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), scale=0.5, translation=lambda", "is None: def n_symbols(rng): return rng.choice(list(range(3, 10))) def scale(rng): return 0.1 * np.exp(rng.randn()", "symbols of various scale and rotation and translation (no bold). \"\"\" def scale(rng):", "import ( dataset_generator, basic_attribute_sampler, flatten_mask, flatten_mask_except_first, add_occlusion, rand_seed, ) def generate_i(n_samples, alphabet =", "symbol. \"\"\" def n_occlusion(rng): if rng.rand() < 0.2: return 1 else: return 0", "(max 200 per alphabet) or uniformly from all symbols (max 200 per alphabet)", "background=bg, foreground=fg) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_natural_images_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Same as", "foreground=fg, is_bold=False, is_slant=False, scale=1, resolution=(8, 8), is_gray=True, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "\"missing-symbol\": missing_symbol_dataset, \"some-large-occlusion\": generate_some_large_occlusions, \"many-small-occlusion\": generate_many_small_occlusions, \"large-translation\": generate_large_translation, \"tiny\": generate_tiny_dataset, \"balanced-font-chars\": generate_balanced_font_chars_dataset, \"all-chars\":", "elif texture == \"shade\": fg, bg = None, None elif texture == \"bw\":", "alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) print(alphabet) fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0,", "foreground and background. \"\"\" attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_solid_bg_dataset(n_samples,", "= basic_attribute_sampler( alphabet=alphabet, font = font, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=rotation, scale=0.7, translation=translation,", "dataset_seed=seed) def generate_plain_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg =", "1, 1)) bg = SolidColor((0, 0, 0)) rotation = 0 translation = (0.0,0.0)", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_tiny_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate a dataset of 8x8", "**kwarg): \"\"\"Same as default datasets, but uses white on black.\"\"\" fg = SolidColor((1,", "128), n_symbols=None, scale_variation=0.5, seed=None, **kwarg ): \"\"\"Generate 3-10 symbols at various scale. Samples", "def missing_symbol_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With 10% probability, no symbols are drawn\"\"\" def", "alphabet = None, language=\"english\", font = 'calibri', set = \"plain\", seed=None, **kwargs): \"\"\"[summary]", "alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, rotation=0, scale=0.7, translation=(0.0, 0.0),", "Note: some fonts may appear rarely. \"\"\" symbols_list = [] for language in", ") return dataset_generator(attr_generator, n_samples, dataset_seed=seed) DATASET_GENERATOR_MAP = { \"plain\": generate_plain_dataset, \"default\": generate_default_dataset, \"default-bw\":", "language=\"english\", seed=None, **kwargs): \"\"\"Same as default dataset, but uses natural images as foreground", "SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=True, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0,", "= alphabet.symbols[:1000] fonts = alphabet.fonts attr_sampler = basic_attribute_sampler(char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(fonts))", "dataset_seed=seed) def generate_plain_camouflage_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) angle =", "\"\"\" symbols_list = [] for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() symbols =", "dataset_seed=seed) DATASET_GENERATOR_MAP = { \"plain\": generate_plain_dataset, \"default\": generate_default_dataset, \"default-bw\": generate_solid_bg_dataset, \"korean-1k\": generate_korean_1k_dataset, \"camouflage\":", "font_list.extend(zip(fonts, [alphabet] * len(fonts))) logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name)", "* 4 - 2) ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def missing_symbol_dataset(n_samples, language=\"english\", seed=None,", "attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=None, translation=(0.0, 0.0), inverse_color=False,", "generate_pixel_noise(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add large pixel noise with probability 0.5.\"\"\" def pixel_noise(rng):", "alphabet=LANGUAGE_MAP[language].get_alphabet(), pixel_noise_scale=pixel_noise ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for font classification # -----------------------", "rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols) else: return \"a\" attr_generator = basic_attribute_sampler( char=char_sampler, resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols )", "foreground=fg) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_natural_images_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Same as default", "dataset_seed=seed) def generate_counting_dataset( n_samples, language=\"english\", resolution=(128, 128), n_symbols=None, scale_variation=0.5, seed=None, **kwarg ): \"\"\"Generate", "but uses natural images as foreground and background.\"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), background=lambda", "\"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6,", "seed=None, **kwarg): \"\"\"Add small occlusions on all images. Number of occlusions are sampled", "= symbols_list[np.random.choice(len(symbols_list))] return basic_attribute_sampler(alphabet=alphabet, char=char)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_balanced_font_chars_dataset(n_samples, seed=None, **kwarg):", "None attr_sampler = basic_attribute_sampler( alphabet=alphabet, font = font, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=rotation,", "0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=True, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0,", "symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) def attr_sampler(seed=None): char, alphabet = symbols_list[np.random.choice(len(symbols_list))] return basic_attribute_sampler(alphabet=alphabet, char=char)(seed)", "def generate_tiny_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate a dataset of 8x8 resolution in gray", "n_samples, dataset_seed=seed) # for font classification # ----------------------- def less_variations(n_samples, language=\"english\", seed=None, **kwarg):", "bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), background=bg, foreground=fg, is_bold=False, is_slant=False,", "dataset_seed=seed) def generate_plain_scaled_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg =", "generate_counting_dataset_scale_fix(n_samples, seed=None, **kwargs): \"\"\"Generate 3-10 symbols at fixed scale. Samples 'a' with prob", "LANGUAGE_MAP[language].get_alphabet(support_bold=False) angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg = Camouflage(stroke_angle=angle", "with probability 50%. \"\"\" font_list = [] symbols_list = [] for language in", "dataset, but uses natural images as foreground and background.\"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(),", "def generate_plain_natural_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols. The only", "= LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True) chars = alphabet.symbols[:1000] fonts = alphabet.fonts attr_sampler = basic_attribute_sampler(char=lambda rng: rng.choice(chars),", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_balanced_font_chars_dataset(n_samples, seed=None, **kwarg): \"\"\"Samples uniformly from all fonts", "LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, background=lambda rng: ImagePattern(seed=rand_seed(rng)), #lambda rng: Gradient(seed=rand_seed(_rng)) foreground=lambda rng:", "symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d fonts from alphabet %s\", len(fonts), len(alphabet.fonts), alphabet.name) font_list.extend(zip(fonts,", "else: raise ValueError(\"Unknown texture %s.\" % texture) scale = 0.7 * np.exp(np.random.randn() *", "\"\"\"Samples uniformly from all fonts (max 200 per alphabet) or uniformly from all", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_camouflage_dataset(n_samples, language=\"english\", texture=\"camouflage\", seed=None, **kwarg): \"\"\"Generate a dataset", "* len(symbols))) def attr_sampler(seed=None): char, alphabet = symbols_list[np.random.choice(len(symbols_list))] return basic_attribute_sampler(alphabet=alphabet, char=char)(seed) return dataset_generator(attr_sampler,", "+ np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) scale = 0.7 * np.exp(np.random.randn() *", "\"\"\" attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_solid_bg_dataset(n_samples, language=\"english\", seed=None, **kwarg):", "and minimal variations. \"\"\" fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0,", "various scale. Samples 'a' with prob 70% or a latin lowercase otherwise. \"\"\"", "generate_plain_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1,", "return basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True), background=bg, foreground=fg, is_bold=True, is_slant=False, scale=scale, )(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=n_occlusion, scale=lambda rng: 0.6 * np.exp(rng.randn() * 0.1), translation=lambda", ")(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_non_camou_bw_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a black", "def scale(rng): return 0.1 * np.exp(rng.randn() * 0.4) def n_symbols(rng): return rng.choice(list(range(3, 10)))", "language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols. The only factors of", "seed=seed, **kwargs) # for segmentation, detection, counting # ------------------------------------- def generate_segmentation_dataset(n_samples, language=\"english\", resolution=(128,", "seed=None, **kwarg): \"\"\"Same as default datasets, but uses white on black.\"\"\" fg =", "is_slant=False, scale=1, resolution=(8, 8), is_gray=True, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_default_dataset(n_samples, language=\"english\",", "foreground=fg, rotation=lambda rng: rng.uniform(low=0, high=1)*math.pi, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler,", "= SolidColor((0, 0, 0)) else: raise ValueError(\"Unknown texture %s.\" % texture) scale =", "classification # ----------------------- def less_variations(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Less variations in scale and", "symbols_list = [] for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() fonts = alphabet.fonts[:200]", "else: symbol, alphabet = symbols_list[np.random.choice(len(symbols_list))] font = np.random.choice(alphabet.fonts[:200]) return basic_attribute_sampler(char=symbol, font=font, is_bold=False, is_slant=False)(seed)", "optional): [description]. Defaults to \"english\". seed ([type], optional): [description]. Defaults to None. \"\"\"", "/ 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) scale = 0.7 * np.exp(np.random.randn() * 0.1) attr_sampler", "rng.rand() > 0.1: return 0 else: return 0.3 attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), pixel_noise_scale=pixel_noise", "= [] for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() fonts = alphabet.fonts[:200] symbols", "only factors of variations are font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg", "in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() fonts = alphabet.fonts[:200] symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d", "import LANGUAGE_MAP from .generate import ( dataset_generator, basic_attribute_sampler, flatten_mask, flatten_mask_except_first, add_occlusion, rand_seed, )", "dataset_seed=seed) def generate_plain_dataset_alphabet_onlygrad(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) attr_sampler", "\"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) fg = [SolidColor((1, 1, 1)), ImagePattern(seed=123)] bg =", "alphabet=LANGUAGE_MAP[language].get_alphabet(), translation=tr, background=background ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) def generate_some_large_occlusions(n_samples, language=\"english\", seed=None, **kwarg):", "fonts (max 200 per alphabet) or uniformly from all symbols (max 200 per", "the foreground and background. \"\"\" def attr_sampler(seed=None): if texture == \"camouflage\": angle =", "generate_some_large_occlusions, \"many-small-occlusion\": generate_many_small_occlusions, \"large-translation\": generate_large_translation, \"tiny\": generate_tiny_dataset, \"balanced-font-chars\": generate_balanced_font_chars_dataset, \"all-chars\": all_chars, \"less-variations\": less_variations,", "def generate_large_translation(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Synbols are translated beyond the border of the", "translated beyond the border of the image to create a cropping effect. Scale", "numpy as np import math from .drawing import Camouflage, NoPattern, SolidColor, MultiGradient, ImagePattern,", "= basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), scale=0.5, translation=lambda rng: tuple(rng.rand(2) * 4 - 2) ) return", "seed=None, **kwargs): \"\"\"Generate default with translation uniformly b/w (-1,1) \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False)", "add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=n_occlusion, scale=lambda rng: 0.6 * np.exp(rng.randn() * 0.1), translation=lambda rng: tuple(rng.rand(2)", "**kwargs): \"\"\"Generate white on black, centered symbols. The only factors of variations are", "seed=None, **kwarg): \"\"\"Generate 3-10 symbols of various scale and rotation and translation (no", "prob 70% or a latin lowercase otherwise. \"\"\" def n_symbols(rng): return rng.choice(list(range(30, 50)))", "rotation = (lambda rng: rng.uniform(low=0, high=1)*math.pi) elif set == 'translation': translation= (lambda rng:", "scale=lambda rng: 0.6 * np.exp(rng.randn() * 0.1), translation=lambda rng: tuple(rng.rand(2) * 6 -", "high=1)*math.pi) elif set == 'translation': translation= (lambda rng: tuple(rng.uniform(low=-1, high=1, size=2))) elif set", "0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_gradient_dataset(n_samples, language=\"english\", seed=None, **kwargs):", "seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=True) fg = SolidColor((1, 1, 1)) bg", "np.random.choice(alphabet.fonts[:200]) return basic_attribute_sampler(char=symbol, font=font, is_bold=False, is_slant=False)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for active", "if rng.rand() > 0.1: return 0 else: return 0.3 attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(),", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset_alphabet(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet =", "foreground and background. \"\"\" def attr_sampler(seed=None): if texture == \"camouflage\": angle = 0", "= SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) else: raise ValueError(\"Unknown texture", "factors of variations are font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg =", "the same for the foreground and background. \"\"\" def attr_sampler(seed=None): if texture ==", "dataset_seed=seed) def generate_balanced_font_chars_dataset(n_samples, seed=None, **kwarg): \"\"\"Samples uniformly from all fonts (max 200 per", "foreground and background.\"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), background=lambda rng: ImagePattern(seed=rand_seed(rng)), foreground=lambda rng: ImagePattern(seed=rand_seed(rng)),", "n_symbols=n_symbols, seed=seed, **kwargs) # for few-shot learning # --------------------- def all_chars(n_samples, seed=None, **kwarg):", "may appear rarely. \"\"\" symbols_list = [] for language in LANGUAGE_MAP.values(): alphabet =", "alphabet = language.get_alphabet() symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols),", "default datasets, but uses white on black.\"\"\" fg = SolidColor((1, 1, 1)) bg", "generate_solid_bg_dataset, \"korean-1k\": generate_korean_1k_dataset, \"camouflage\": generate_camouflage_dataset, \"non-camou-bw\": generate_non_camou_bw_dataset, \"non-camou-shade\": generate_non_camou_shade_dataset, \"segmentation\": generate_segmentation_dataset, \"counting\": generate_counting_dataset,", "and no italic. This makes a more accessible font classification task. \"\"\" attr_generator", "inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_gradient_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate", "return 0.1 * np.exp(rng.randn() * 0.4) def n_symbols(rng): return rng.choice(list(range(3, 10))) attr_generator =", "\"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg = SolidColor((0,", "#print(alphabet.fonts[:10]) attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False,", "= LANGUAGE_MAP[language].get_alphabet(support_bold=False) angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg =", "= 0.7 * np.exp(np.random.randn() * 0.1) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg,", "len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) logging.info(\"Total n_fonts: %d, n_symbols: %d.\", len(font_list),", "rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, background= lambda rng:rng.choice(bg), foreground= lambda rng:rng.choice(fg), rotation=0,", "if np.random.rand() > 0.5: font, alphabet = font_list[np.random.choice(len(font_list))] symbol = np.random.choice(alphabet.symbols[:200]) else: symbol,", "white on black.\"\"\" fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0))", "n_samples, dataset_seed=seed) def generate_plain_natural_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols.", "'calibri', set = \"plain\", seed=None, **kwargs): \"\"\"[summary] Args: n_samples ([type]): [description] language (str,", "attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=lambda rng: rng.uniform(low=0, high=1)*math.pi, scale=1.0,", "* np.exp(np.random.randn() * 0.1) return basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True), background=bg, foreground=fg, is_bold=True, is_slant=False, scale=scale, )(seed)", "of 8x8 resolution in gray scale with scale of 1 and minimal variations.", "tr(rng): if rng.rand() > 0.1: return tuple(rng.rand(2) * 2 - 1) else: return", "\"\"\"[summary] Args: n_samples ([type]): [description] language (str, optional): [description]. Defaults to \"english\". seed", "is_bold=False, is_slant=False, scale=1, resolution=(8, 8), is_gray=True, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_default_dataset(n_samples,", "n_fonts: %d, n_symbols: %d.\", len(font_list), len(symbols_list)) def attr_sampler(seed=None): if np.random.rand() > 0.5: font,", "= basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=None, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0,", "%d/%d fonts from alphabet %s\", len(fonts), len(alphabet.fonts), alphabet.name) font_list.extend(zip(fonts, [alphabet] * len(fonts))) logging.info(\"Using", "attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=lambda rng: tuple(rng.uniform(low=-1,", "attr_sampler(seed=None): if texture == \"camouflage\": angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6,", "np.exp(rng.randn() * 0.4) def n_symbols(rng): return rng.choice(list(range(3, 10))) attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), resolution=resolution,", "rng: rng.randn() * 0.1, ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) DATASET_GENERATOR_MAP = { \"plain\":", "= 'calibri', set = \"plain\", seed=None, **kwargs): \"\"\"[summary] Args: n_samples ([type]): [description] language", "symbols. The only factors of variations are font and char. \"\"\" alphabet =", "= SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(), background=bg,", "ImagePattern(seed=rand_seed(rng)), foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_korean_1k_dataset(n_samples, seed=None, **kwarg):", "or a latin lowercase otherwise. \"\"\" def n_symbols(rng): return rng.choice(list(range(30, 50))) return generate_counting_dataset(n_samples,", "basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_solid_bg_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Same as default", "the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"shade\", seed=seed, **kwargs) # for segmentation,", "50%. \"\"\" font_list = [] symbols_list = [] for language in LANGUAGE_MAP.values(): alphabet", "\"\"\"Generate a gradient foreground and background dataset with same attribute distribution as the", "angle = 0 fg = Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg = Camouflage(stroke_angle=angle +", "seed=seed, **kwargs) # for few-shot learning # --------------------- def all_chars(n_samples, seed=None, **kwarg): \"\"\"Combines", "\"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, background=lambda rng: ImagePattern(seed=rand_seed(rng)), #lambda rng:", "tuple(rng.rand(2) * 4 - 2) ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def missing_symbol_dataset(n_samples, language=\"english\",", "on black.\"\"\" fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler", "and rotations. Also, no bold and no italic. This makes a more accessible", "scale=1.0, translation=lambda rng: tuple(rng.uniform(low=-1, high=1, size=2)), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "background=bg, foreground=fg, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0,", "are translated beyond the border of the image to create a cropping effect.", "from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) logging.info(\"Total n_fonts: %d,", "return basic_attribute_sampler(char=symbol, font=font, is_bold=False, is_slant=False)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for active learning", "\"\"\"Generate a dataset where the pixel distribution is the same for the foreground", "= language.get_alphabet() fonts = alphabet.fonts[:200] symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d fonts from alphabet", "* 0.4) def n_symbols(rng): return rng.choice(list(range(3, 10))) attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), resolution=resolution, scale=scale,", "def generate_balanced_font_chars_dataset(n_samples, seed=None, **kwarg): \"\"\"Samples uniformly from all fonts (max 200 per alphabet)", "def generate_counting_dataset_crowded(n_samples, seed=None, **kwargs): \"\"\"Generate 30-50 symbols at fixed scale. Samples 'a' with", "0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=0.7, translation=(0.0, 0.0),", "0, 0)), ImagePattern(seed=123)] attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]),", "generate_plain_bold_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=True) fg = SolidColor((1, 1,", "font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_default_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate the default dataset, using", "accessible font classification task. \"\"\" attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), is_bold=False, is_slant=False, scale=lambda rng:", "- 3), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_many_small_occlusions(n_samples, language=\"english\", seed=None, **kwarg):", "language.get_alphabet() symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name)", "n_samples, dataset_seed=seed) def generate_plain_scaled_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg", "dataset_seed=seed) def generate_pixel_noise(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add large pixel noise with probability 0.5.\"\"\"", "None bg = None attr_sampler = basic_attribute_sampler( alphabet=alphabet, font = font, is_slant=False, is_bold=False,", "0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=lambda", "[description] language (str, optional): [description]. Defaults to \"english\". seed ([type], optional): [description]. Defaults", "attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=True, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False,", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False)", "symbols_list[np.random.choice(len(symbols_list))] font = np.random.choice(alphabet.fonts[:200]) return basic_attribute_sampler(char=symbol, font=font, is_bold=False, is_slant=False)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "a latin lowercase otherwise. \"\"\" if n_symbols is None: def n_symbols(rng): return rng.choice(list(range(3,", "0.7 * np.exp(np.random.randn() * 0.1) return basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True), background=bg, foreground=fg, is_bold=True, is_slant=False, scale=scale,", "= [] for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet() symbols = alphabet.symbols[:200] logging.info(\"Using", "0.1: return tuple(rng.rand(2) * 2 - 1) else: return 10 attr_generator = basic_attribute_sampler(", "font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, background=lambda rng:", "texture=\"bw\", seed=seed, **kwargs) def generate_non_camou_shade_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a gradient foreground and", "bold and no italic. This makes a more accessible font classification task. \"\"\"", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_camouflage_dataset(n_samples, language=\"english\", texture=\"camouflage\", seed=None, **kwarg): \"\"\"Generate a dataset where", "symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) def attr_sampler(seed=None):", "generate_korean_1k_dataset, \"camouflage\": generate_camouflage_dataset, \"non-camou-bw\": generate_non_camou_bw_dataset, \"non-camou-shade\": generate_non_camou_shade_dataset, \"segmentation\": generate_segmentation_dataset, \"counting\": generate_counting_dataset, \"counting-fix-scale\": generate_counting_dataset_scale_fix,", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_translated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate default with translation", "logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols)))", "\"default-bw\": generate_solid_bg_dataset, \"korean-1k\": generate_korean_1k_dataset, \"camouflage\": generate_camouflage_dataset, \"non-camou-bw\": generate_non_camou_bw_dataset, \"non-camou-shade\": generate_non_camou_shade_dataset, \"segmentation\": generate_segmentation_dataset, \"counting\":", "scale = 0.7 * np.exp(np.random.randn() * 0.1) return basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True), background=bg, foreground=fg, is_bold=True,", "len(symbols))) def attr_sampler(seed=None): char, alphabet = symbols_list[np.random.choice(len(symbols_list))] return basic_attribute_sampler(alphabet=alphabet, char=char)(seed) return dataset_generator(attr_sampler, n_samples,", "inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_rotated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"", "pixel distribution is the same for the foreground and background. \"\"\" def attr_sampler(seed=None):", "0)) else: raise ValueError(\"Unknown texture %s.\" % texture) scale = 0.7 * np.exp(np.random.randn()", "generate_tiny_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate a dataset of 8x8 resolution in gray scale", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def missing_symbol_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With 10% probability, no", "'gradient': fg = None bg = None attr_sampler = basic_attribute_sampler( alphabet=alphabet, font =", "is_bold=False, n_symbols=n_symbols, ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset( n_samples, language=\"english\", resolution=(128,", "latin lowercase otherwise. \"\"\" def n_symbols(rng): return rng.choice(list(range(30, 50))) return generate_counting_dataset(n_samples, scale_variation=0.1, n_symbols=n_symbols,", "0.1 * np.exp(rng.randn() * 0.4) def n_symbols(rng): return rng.choice(list(range(3, 10))) attr_generator = basic_attribute_sampler(", "learning # --------------------- def all_chars(n_samples, seed=None, **kwarg): \"\"\"Combines the symbols of all languages", "otherwise. \"\"\" return generate_counting_dataset(n_samples, scale_variation=0, seed=seed, **kwargs) def generate_counting_dataset_crowded(n_samples, seed=None, **kwargs): \"\"\"Generate 30-50", "language=\"english\", font = 'calibri', set = \"plain\", seed=None, **kwargs): \"\"\"[summary] Args: n_samples ([type]):", "= basic_attribute_sampler( alphabet=alphabet, background=lambda rng: ImagePattern(seed=rand_seed(rng)), #lambda rng: Gradient(seed=rand_seed(_rng)) foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), is_slant=False,", "seed=None, **kwargs): \"\"\"Generate 30-50 symbols at fixed scale. Samples 'a' with prob 70%", "0, 0)) attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), background=bg, foreground=fg, is_bold=False, is_slant=False, scale=1, resolution=(8, 8),", "Scale is fixed to 0.5. \"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), scale=0.5, translation=lambda rng:", "SolidColor, MultiGradient, ImagePattern, Gradient, Image, Symbol from .fonts import LANGUAGE_MAP from .generate import", "foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_korean_1k_dataset(n_samples, seed=None, **kwarg): \"\"\"Uses", "'rotation': rotation = (lambda rng: rng.uniform(low=0, high=1)*math.pi) elif set == 'translation': translation= (lambda", "font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False,", "of the image to create a cropping effect. Scale is fixed to 0.5.", "attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=lambda rng: rng.randint(0, 5), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first,", "< 0.3: return rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols) else: return \"a\" attr_generator = basic_attribute_sampler( char=char_sampler, resolution=resolution, scale=scale,", "== 'gradient': fg = None bg = None attr_sampler = basic_attribute_sampler( alphabet=alphabet, font", "return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_many_small_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Add small occlusions", "Args: n_samples ([type]): [description] language (str, optional): [description]. Defaults to \"english\". seed ([type],", "detection, counting # ------------------------------------- def generate_segmentation_dataset(n_samples, language=\"english\", resolution=(128, 128), seed=None, **kwarg): \"\"\"Generate 3-10", "attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), translation=tr, background=background ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) def generate_some_large_occlusions(n_samples,", "alphabet=alphabet, is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples,", "Symbol from .fonts import LANGUAGE_MAP from .generate import ( dataset_generator, basic_attribute_sampler, flatten_mask, flatten_mask_except_first,", "SolidColor((0, 0, 0)) else: raise ValueError(\"Unknown texture %s.\" % texture) scale = 0.7", "def generate_solid_bg_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Same as default datasets, but uses white on", "is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "rng.rand() < 0.3: return rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols) else: return \"a\" attr_generator = basic_attribute_sampler( char=char_sampler, resolution=resolution,", "SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=False), background=bg, foreground=fg, is_bold=False, is_slant=False, scale=1, resolution=(8,", "seed=None, **kwarg): \"\"\"Less variations in scale and rotations. Also, no bold and no", "0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=lambda rng:", "= Camouflage(stroke_angle=angle, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) bg = Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1,", "ImagePattern(seed=rand_seed(rng)), #lambda rng: Gradient(seed=rand_seed(_rng)) foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0),", "def generate_plain_italic_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols. The only", "is_bold=False, background=bg, foreground=fg, rotation=rotation, scale=0.7, translation=translation, inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_gradient_dataset(n_samples,", "generate_plain_natural_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on black, centered symbols. The only factors", "* 6 - 3), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_many_small_occlusions(n_samples, language=\"english\",", "scale(rng): return 0.1 * np.exp(rng.randn() * 0.4) def n_symbols(rng): return rng.choice(list(range(3, 10))) attr_generator", "Defaults to \"english\". seed ([type], optional): [description]. Defaults to None. \"\"\" if alphabet", "2 - 1) else: return 10 attr_generator = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), translation=tr, background=background )", "return rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols) else: return \"a\" attr_generator = basic_attribute_sampler( char=char_sampler, resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols", "3-10 symbols of various scale and rotation and translation (no bold). \"\"\" def", "all languages (up to 200 per languages). Note: some fonts may appear rarely.", "0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=lambda rng: rng.uniform(low=0,", "dataset_seed=seed) def generate_plain_bold_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=True) fg =", "\"\"\" def n_symbols(rng): return rng.choice(list(range(30, 50))) return generate_counting_dataset(n_samples, scale_variation=0.1, n_symbols=n_symbols, seed=seed, **kwargs) #", "SolidColor((0, 0, 0)) rotation = 0 translation = (0.0,0.0) if set == 'rotation':", "for segmentation, detection, counting # ------------------------------------- def generate_segmentation_dataset(n_samples, language=\"english\", resolution=(128, 128), seed=None, **kwarg):", "8x8 resolution in gray scale with scale of 1 and minimal variations. \"\"\"", "rng.choice(list(range(30, 50))) return generate_counting_dataset(n_samples, scale_variation=0.1, n_symbols=n_symbols, seed=seed, **kwargs) # for few-shot learning #", "1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False,", "dataset_seed=seed) def generate_plain_rotated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg =", "existing symbol. \"\"\" def n_occlusion(rng): if rng.rand() < 0.2: return 1 else: return", "Defaults to None. \"\"\" if alphabet is None: alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) print(alphabet) fg", "= basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_solid_bg_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Same as", "alphabet=LANGUAGE_MAP[language].get_alphabet(), background=lambda rng: ImagePattern(seed=rand_seed(rng)), foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "foreground=fg, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "seed=None, **kwarg): \"\"\"Uses the first 1000 korean symbols\"\"\" alphabet = LANGUAGE_MAP[\"korean\"].get_alphabet(support_bold=True) chars =", "a latin lowercase otherwise. \"\"\" return generate_counting_dataset(n_samples, scale_variation=0, seed=seed, **kwargs) def generate_counting_dataset_crowded(n_samples, seed=None,", "0.1), rotation=lambda rng: rng.randn() * 0.1, ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) DATASET_GENERATOR_MAP =", "foreground=fg, is_bold=True, is_slant=False, scale=scale, )(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_non_camou_bw_dataset(n_samples, language=\"english\", seed=None,", "== \"bw\": fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) else:", "over the existing symbol. \"\"\" def n_occlusion(rng): if rng.rand() < 0.2: return 1", "stroke_noise=0) scale = 0.7 * np.exp(np.random.randn() * 0.1) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False,", "alphabet) with probability 50%. \"\"\" font_list = [] symbols_list = [] for language", "occlusions are sampled uniformly in [0,5). \"\"\" attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=lambda rng:", "inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_translated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate", "= LANGUAGE_MAP[language].get_alphabet(support_bold=False) attr_sampler = basic_attribute_sampler( alphabet=alphabet, background=lambda rng: ImagePattern(seed=rand_seed(rng)), #lambda rng: Gradient(seed=rand_seed(_rng)) foreground=lambda", "rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler,", "len(font_list), len(symbols_list)) def attr_sampler(seed=None): if np.random.rand() > 0.5: font, alphabet = font_list[np.random.choice(len(font_list))] symbol", "1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg,", "a large occlusion over the existing symbol. \"\"\" def n_occlusion(rng): if rng.rand() <", "is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler,", "n_occlusion=n_occlusion, scale=lambda rng: 0.6 * np.exp(rng.randn() * 0.1), translation=lambda rng: tuple(rng.rand(2) * 6", "seed=None, **kwargs): \"\"\"[summary] Args: n_samples ([type]): [description] language (str, optional): [description]. Defaults to", "rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, background= lambda rng:rng.choice(bg), foreground= lambda rng:rng.choice(fg), rotation=0, scale=0.7, translation=(0.0,", "1)) bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=True, background=bg,", "from .generate import ( dataset_generator, basic_attribute_sampler, flatten_mask, flatten_mask_except_first, add_occlusion, rand_seed, ) def generate_i(n_samples,", "generate_plain_dataset, \"default\": generate_default_dataset, \"default-bw\": generate_solid_bg_dataset, \"korean-1k\": generate_korean_1k_dataset, \"camouflage\": generate_camouflage_dataset, \"non-camou-bw\": generate_non_camou_bw_dataset, \"non-camou-shade\": generate_non_camou_shade_dataset,", "%s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet] * len(symbols))) logging.info(\"Total n_fonts: %d, n_symbols: %d.\",", "is fixed to 0.5. \"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), scale=0.5, translation=lambda rng: tuple(rng.rand(2)", "attr_sampler = basic_attribute_sampler(char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(fonts)) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0,", "np.exp(np.random.randn() * 0.1) return basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True), background=bg, foreground=fg, is_bold=True, is_slant=False, scale=scale, )(seed) return", "dataset_seed=seed) def generate_plain_dataset_alphabet(n_samples, chars, seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) fg", "of variations are font and char. \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1,", "scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_camouflage_dataset(n_samples, language=\"english\",", "is_bold=False, is_slant=False, scale=lambda rng: 0.5 * np.exp(rng.randn() * 0.1), rotation=lambda rng: rng.randn() *", "= SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(), background=bg, foreground=fg) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_gradient_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on", "n_samples, dataset_seed=seed) def generate_camouflage_dataset(n_samples, language=\"english\", texture=\"camouflage\", seed=None, **kwarg): \"\"\"Generate a dataset where the", "0.1: return 0 else: return 0.3 attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), pixel_noise_scale=pixel_noise ) return", "background.\"\"\" attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), background=lambda rng: ImagePattern(seed=rand_seed(rng)), foreground=lambda rng: ImagePattern(seed=rand_seed(rng)), ) return", "is_bold=False, background=bg, foreground=fg, rotation=0, scale=None, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples,", "basic_attribute_sampler, flatten_mask, flatten_mask_except_first, add_occlusion, rand_seed, ) def generate_i(n_samples, alphabet = None, language=\"english\", font", "alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=scale, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_scaled_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False)", "translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_gradient_dataset(n_samples, language=\"english\", seed=None,", "or a latin lowercase otherwise. \"\"\" if n_symbols is None: def n_symbols(rng): return", ") return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset( n_samples, language=\"english\", resolution=(128, 128), n_symbols=None,", "a gradient foreground and background dataset with same attribute distribution as the camouflage", "= basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), translation=tr, background=background ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) def generate_some_large_occlusions(n_samples, language=\"english\",", "bg = SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(), background=bg, foreground=fg) return dataset_generator(attr_sampler, n_samples,", "bold). \"\"\" def scale(rng): return 0.1 * np.exp(rng.randn() * 0.4) def n_symbols(rng): return", "attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0, scale=scale, translation=(0.0, 0.0), inverse_color=False,", "== \"shade\": fg, bg = None, None elif texture == \"bw\": fg =", "= None, language=\"english\", font = 'calibri', set = \"plain\", seed=None, **kwargs): \"\"\"[summary] Args:", "dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"shade\", seed=seed, **kwargs) # for segmentation, detection, counting", "dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def generate_counting_dataset_scale_fix(n_samples, seed=None, **kwargs): \"\"\"Generate 3-10 symbols at fixed", "the default dataset, using gradiant as foreground and background. \"\"\" attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet())", "dataset_seed=seed) def missing_symbol_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With 10% probability, no symbols are drawn\"\"\"", "rng.randint(0, 5), ) return dataset_generator(attr_sampler, n_samples, flatten_mask_except_first, dataset_seed=seed) def generate_pixel_noise(n_samples, language=\"english\", seed=None, **kwarg):", "'a' with prob 70% or a latin lowercase otherwise. \"\"\" return generate_counting_dataset(n_samples, scale_variation=0,", "generate_natural_images_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Same as default dataset, but uses natural images as", "= np.random.choice(alphabet.fonts[:200]) return basic_attribute_sampler(char=symbol, font=font, is_bold=False, is_slant=False)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for", "dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for active learning # ------------------- def generate_large_translation(n_samples, language=\"english\", seed=None,", "\"\"\" fg = SolidColor((1, 1, 1)) bg = SolidColor((0, 0, 0)) attr_sampler =", "default dataset, but uses natural images as foreground and background.\"\"\" attr_sampler = basic_attribute_sampler(", "dataset_generator, basic_attribute_sampler, flatten_mask, flatten_mask_except_first, add_occlusion, rand_seed, ) def generate_i(n_samples, alphabet = None, language=\"english\",", "basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=True, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, )", "> 0.5: font, alphabet = font_list[np.random.choice(len(font_list))] symbol = np.random.choice(alphabet.symbols[:200]) else: symbol, alphabet =", "scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset(n_samples, language=\"english\",", "0)) attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet(), background=bg, foreground=fg) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_natural_images_dataset(n_samples, language=\"english\",", "MultiGradient(alpha=0.5, n_gradients=2, types=(\"linear\", \"radial\"), seed=rand_seed(rng)) def tr(rng): if rng.rand() > 0.1: return tuple(rng.rand(2)", "stroke_noise=0) bg = Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) scale =", "ImagePattern(seed=123)] attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False,", "appear rarely. \"\"\" symbols_list = [] for language in LANGUAGE_MAP.values(): alphabet = language.get_alphabet()", "LANGUAGE_MAP from .generate import ( dataset_generator, basic_attribute_sampler, flatten_mask, flatten_mask_except_first, add_occlusion, rand_seed, ) def", "language=language, texture=\"bw\", seed=seed, **kwargs) def generate_non_camou_shade_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a gradient foreground", "= basic_attribute_sampler( char=char_sampler, resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed)", "basic_attribute_sampler( char=char_sampler, resolution=resolution, scale=scale, is_bold=False, n_symbols=n_symbols ) return dataset_generator(attr_generator, n_samples, flatten_mask, dataset_seed=seed) def", "dataset_seed=seed) def generate_tiny_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Generate a dataset of 8x8 resolution in", "20%, add a large occlusion over the existing symbol. \"\"\" def n_occlusion(rng): if", "or a latin lowercase otherwise. \"\"\" return generate_counting_dataset(n_samples, scale_variation=0, seed=seed, **kwargs) def generate_counting_dataset_crowded(n_samples,", "rng.choice(chars), font=lambda rng: rng.choice(alphabet.fonts[50:55]), is_slant=False, is_bold=False, rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, )", "rng:rng.choice(fg), rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "= alphabet.fonts attr_sampler = basic_attribute_sampler(char=lambda rng: rng.choice(chars), font=lambda rng: rng.choice(fonts)) return dataset_generator(attr_sampler, n_samples,", "def generate_counting_dataset_scale_fix(n_samples, seed=None, **kwargs): \"\"\"Generate 3-10 symbols at fixed scale. Samples 'a' with", "char_sampler(rng): if rng.rand() < 0.3: return rng.choice(LANGUAGE_MAP[language].get_alphabet(support_bold=False).symbols) else: return \"a\" attr_generator = basic_attribute_sampler(", "**kwarg): \"\"\"With probability 20%, add a large occlusion over the existing symbol. \"\"\"", "n_samples, dataset_seed=seed) def missing_symbol_dataset(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With 10% probability, no symbols are", "rand_seed, ) def generate_i(n_samples, alphabet = None, language=\"english\", font = 'calibri', set =", "generate_segmentation_dataset, \"counting\": generate_counting_dataset, \"counting-fix-scale\": generate_counting_dataset_scale_fix, \"counting-crowded\": generate_counting_dataset_crowded, \"missing-symbol\": missing_symbol_dataset, \"some-large-occlusion\": generate_some_large_occlusions, \"many-small-occlusion\": generate_many_small_occlusions,", "rng: rng.choice(chars), font=lambda rng: rng.choice(fonts)) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_camouflage_dataset(n_samples, language=\"english\", texture=\"camouflage\",", "and rotation and translation (no bold). \"\"\" def scale(rng): return 0.1 * np.exp(rng.randn()", "scale=1, resolution=(8, 8), is_gray=True, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_default_dataset(n_samples, language=\"english\", seed=None,", "fonts = alphabet.fonts[:200] symbols = alphabet.symbols[:200] logging.info(\"Using %d/%d fonts from alphabet %s\", len(fonts),", "\"\"\" attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=lambda rng: rng.randint(0, 5), ) return dataset_generator(attr_sampler, n_samples,", "is_slant=False, is_bold=False, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed)", "% texture) scale = 0.7 * np.exp(np.random.randn() * 0.1) return basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(support_bold=True), background=bg,", "with probability 0.5.\"\"\" def pixel_noise(rng): if rng.rand() > 0.1: return 0 else: return", "translation=lambda rng: tuple(rng.rand(2) * 4 - 2) ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def", "= basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=True, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0,", "def n_symbols(rng): return rng.choice(list(range(3, 10))) def scale(rng): return 0.1 * np.exp(rng.randn() * scale_variation)", "generate_non_camou_bw_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate a black and white dataset with the same", "font=font, is_bold=False, is_slant=False)(seed) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) # for active learning # -------------------", "bg = Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) scale = 0.7", "bg = None attr_sampler = basic_attribute_sampler( alphabet=alphabet, font = font, is_slant=False, is_bold=False, background=bg,", "n_gradients=2, types=(\"linear\", \"radial\"), seed=rand_seed(rng)) def tr(rng): if rng.rand() > 0.1: return tuple(rng.rand(2) *", "basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), translation=tr, background=background ) return dataset_generator(attr_generator, n_samples, dataset_seed=seed) def generate_some_large_occlusions(n_samples, language=\"english\", seed=None,", "def generate_segmentation_dataset(n_samples, language=\"english\", resolution=(128, 128), seed=None, **kwarg): \"\"\"Generate 3-10 symbols of various scale", "centered symbols. The only factors of variations are font and char. \"\"\" alphabet", "seed=None, **kwargs): \"\"\"Same as default dataset, but uses natural images as foreground and", "basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), is_bold=False, is_slant=False, scale=lambda rng: 0.5 * np.exp(rng.randn() * 0.1), rotation=lambda rng:", "\"counting-crowded\": generate_counting_dataset_crowded, \"missing-symbol\": missing_symbol_dataset, \"some-large-occlusion\": generate_some_large_occlusions, \"many-small-occlusion\": generate_many_small_occlusions, \"large-translation\": generate_large_translation, \"tiny\": generate_tiny_dataset, \"balanced-font-chars\":", "alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) fg = [SolidColor((1, 1, 1)), ImagePattern(seed=123)] bg = [SolidColor((0,", ") def generate_i(n_samples, alphabet = None, language=\"english\", font = 'calibri', set = \"plain\",", "MultiGradient, ImagePattern, Gradient, Image, Symbol from .fonts import LANGUAGE_MAP from .generate import (", "def less_variations(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"Less variations in scale and rotations. Also, no", "1, 1)) bg = SolidColor((0, 0, 0)) else: raise ValueError(\"Unknown texture %s.\" %", "pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\"", "attr_sampler = basic_attribute_sampler( alphabet=LANGUAGE_MAP[language].get_alphabet(), scale=0.5, translation=lambda rng: tuple(rng.rand(2) * 4 - 2) )", "no italic. This makes a more accessible font classification task. \"\"\" attr_generator =", "seed=None, **kwarg): \"\"\"Generate a dataset where the pixel distribution is the same for", "= alphabet.symbols[:200] logging.info(\"Using %d/%d symbols from alphabet %s\", len(symbols), len(alphabet.symbols), alphabet.name) symbols_list.extend(zip(symbols, [alphabet]", "= (0.0,0.0) if set == 'rotation': rotation = (lambda rng: rng.uniform(low=0, high=1)*math.pi) elif", "return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_scaled_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet =", "pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_bold_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\"", "to None. \"\"\" if alphabet is None: alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) print(alphabet) fg =", "attribute distribution as the camouflage dataset. \"\"\" return generate_camouflage_dataset(n_samples, language=language, texture=\"bw\", seed=seed, **kwargs)", "**kwargs): \"\"\"Generate 3-10 symbols at fixed scale. Samples 'a' with prob 70% or", "\"segmentation\": generate_segmentation_dataset, \"counting\": generate_counting_dataset, \"counting-fix-scale\": generate_counting_dataset_scale_fix, \"counting-crowded\": generate_counting_dataset_crowded, \"missing-symbol\": missing_symbol_dataset, \"some-large-occlusion\": generate_some_large_occlusions, \"many-small-occlusion\":", "basic_attribute_sampler( alphabet=alphabet, font = font, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=rotation, scale=0.7, translation=translation, inverse_color=False,", "= SolidColor((0, 0, 0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=False, is_bold=False, background=bg, foreground=fg, rotation=0,", "np.random.choice(alphabet.symbols[:200]) else: symbol, alphabet = symbols_list[np.random.choice(len(symbols_list))] font = np.random.choice(alphabet.fonts[:200]) return basic_attribute_sampler(char=symbol, font=font, is_bold=False,", "rotation=0, scale=0.7, translation=(0.0, 0.0), inverse_color=False, pixel_noise_scale=0.0, ) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_dataset(n_samples,", "Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) elif texture == \"shade\": fg,", "generate_counting_dataset(n_samples, scale_variation=0.1, n_symbols=n_symbols, seed=seed, **kwargs) # for few-shot learning # --------------------- def all_chars(n_samples,", "create a cropping effect. Scale is fixed to 0.5. \"\"\" attr_sampler = basic_attribute_sampler(", "same for the foreground and background. \"\"\" def attr_sampler(seed=None): if texture == \"camouflage\":", ") return dataset_generator(attr_generator, n_samples, dataset_seed=seed) def generate_some_large_occlusions(n_samples, language=\"english\", seed=None, **kwarg): \"\"\"With probability 20%,", "0)) attr_sampler = basic_attribute_sampler( alphabet=alphabet, is_slant=True, is_bold=False, background=bg, foreground=fg, rotation=0, scale=1.0, translation=(0.0, 0.0),", "(-1,1) \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) fg = SolidColor((1, 1, 1)) bg = SolidColor((0,", "10% probability, no symbols are drawn\"\"\" def background(rng): return MultiGradient(alpha=0.5, n_gradients=2, types=(\"linear\", \"radial\"),", "dataset of 8x8 resolution in gray scale with scale of 1 and minimal", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_natural_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\"Generate white on", "on black, centered symbols. The only factors of variations are font and char.", "\"\"\" \"\"\" alphabet = LANGUAGE_MAP['english'].get_alphabet(support_bold=False) #print(alphabet.fonts[:10]) fg = [SolidColor((1, 1, 1)), ImagePattern(seed=123)] bg", "Camouflage(stroke_angle=angle + np.pi / 2, stroke_width=0.1, stroke_length=0.6, stroke_noise=0) scale = 0.7 * np.exp(np.random.randn()", "as default datasets, but uses white on black.\"\"\" fg = SolidColor((1, 1, 1))", "seed=None, **kwarg): \"\"\"Generate the default dataset, using gradiant as foreground and background. \"\"\"", "0.6 * np.exp(rng.randn() * 0.1), translation=lambda rng: tuple(rng.rand(2) * 6 - 3), )", "= add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()), n_occlusion=n_occlusion, scale=lambda rng: 0.6 * np.exp(rng.randn() * 0.1), translation=lambda rng:", "[SolidColor((0, 0, 0)), ImagePattern(seed=123)] attr_sampler = basic_attribute_sampler( alphabet=alphabet, char=lambda rng: rng.choice(chars), font=lambda rng:", "def generate_plain_camouflage_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet = LANGUAGE_MAP[language].get_alphabet(support_bold=False) angle = 0", "return generate_counting_dataset(n_samples, scale_variation=0.1, n_symbols=n_symbols, seed=seed, **kwargs) # for few-shot learning # --------------------- def", ") return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def generate_plain_rotated_dataset(n_samples, language=\"english\", seed=None, **kwargs): \"\"\" \"\"\" alphabet", "Number of occlusions are sampled uniformly in [0,5). \"\"\" attr_sampler = add_occlusion( basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()),", "as foreground and background. \"\"\" attr_sampler = basic_attribute_sampler(alphabet=LANGUAGE_MAP[language].get_alphabet()) return dataset_generator(attr_sampler, n_samples, dataset_seed=seed) def" ]
[ "= self.wrapped_env.step(act) params = self._params_as_tensor() obs = np.concatenate((obs, params)) return obs, reward, done,", "self.nominal['dt'] = 1 / 100. # TODO ATTENTION! THIS CAN BE DEADLY! @Robin,", "reset(self, init_state: np.ndarray = None, domain_param: dict = None): obs = self.wrapped_env.reset(init_state, domain_param)", "fixed def _params_as_tensor(self): if self.fixed: return self._nominal else: return np.array([inner_env(self.wrapped_env).domain_param[k] for k in", "zip(self._params, params): newp[key] = value.item() inner_env(self.wrapped_env).domain_param = newp def set_adv(self, params): for key,", "value.item() inner_env(self.wrapped_env).domain_param = newp def set_adv(self, params): for key, value in zip(self._params, params):", "import Serializable from pyrado.environment_wrappers.base import EnvWrapper from pyrado.environment_wrappers.utils import inner_env from pyrado.environments.base import", "np.concatenate((obs, params)) return obs @property def mask(self): return np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim), np.ones(len(self._params)))) @property def offset(self):", "def _params_as_tensor(self): if self.fixed: return self._nominal else: return np.array([inner_env(self.wrapped_env).domain_param[k] for k in self._params])", "params = self._params_as_tensor() obs = np.concatenate((obs, params)) return obs @property def mask(self): return", "self._params]) @property def obs_space(self): outer_space = self.wrapped_env.obs_space augmented_space = BoxSpace(0.5 * self._nominal, 1.5", "self.wrapped_env.obs_space augmented_space = BoxSpace(0.5 * self._nominal, 1.5 * self._nominal, [self._nominal.shape[0]], self._params) return BoxSpace.cat((outer_space,", "def set_param(self, params): newp = dict() for key, value in zip(self._params, params): newp[key]", "= np.array([self._nominal[k] for k in self._params]) self.fixed = fixed def _params_as_tensor(self): if self.fixed:", "__init__(self, wrapped_env: Env, params=None, fixed=False): \"\"\" Constructor TODO :param wrapped_env: :param params: :param", "None: self._params = params else: self._params = list(inner_env(self.wrapped_env).domain_param.keys()) self._nominal = inner_env(self.wrapped_env).get_nominal_domain_param() self.nominal['dt'] =", "in zip(self._params, params): newp[key] = value.item() inner_env(self.wrapped_env).domain_param = newp def set_adv(self, params): for", "else: self._params = list(inner_env(self.wrapped_env).domain_param.keys()) self._nominal = inner_env(self.wrapped_env).get_nominal_domain_param() self.nominal['dt'] = 1 / 100. #", "from pyrado.environment_wrappers.base import EnvWrapper from pyrado.environment_wrappers.utils import inner_env from pyrado.environments.base import Env from", "TODO ATTENTION! THIS CAN BE DEADLY! @Robin, why are you doing this? self._nominal", "if self.fixed: return self._nominal else: return np.array([inner_env(self.wrapped_env).domain_param[k] for k in self._params]) @property def", "= np.concatenate((obs, params)) return obs, reward, done, info def reset(self, init_state: np.ndarray =", "self._nominal else: return np.array([inner_env(self.wrapped_env).domain_param[k] for k in self._params]) @property def obs_space(self): outer_space =", "in zip(self._params, params): inner_env(self.wrapped_env).domain_param[key] = self._nominal[key] + value @property def nominal(self): return self._nominal", "for k in self._params]) self.fixed = fixed def _params_as_tensor(self): if self.fixed: return self._nominal", "self._params = params else: self._params = list(inner_env(self.wrapped_env).domain_param.keys()) self._nominal = inner_env(self.wrapped_env).get_nominal_domain_param() self.nominal['dt'] = 1", "return np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim), np.ones(len(self._params)))) @property def offset(self): return self.wrapped_env.obs_space.flat_dim def set_param(self, params): newp =", "np.ndarray): obs, reward, done, info = self.wrapped_env.step(act) params = self._params_as_tensor() obs = np.concatenate((obs,", "BoxSpace class StateAugmentationWrapper(EnvWrapper, Serializable): \"\"\" TODO \"\"\" def __init__(self, wrapped_env: Env, params=None, fixed=False):", "= None, domain_param: dict = None): obs = self.wrapped_env.reset(init_state, domain_param) params = self._params_as_tensor()", "/ 100. # TODO ATTENTION! THIS CAN BE DEADLY! @Robin, why are you", "set_param(self, params): newp = dict() for key, value in zip(self._params, params): newp[key] =", "as np from init_args_serializer import Serializable from pyrado.environment_wrappers.base import EnvWrapper from pyrado.environment_wrappers.utils import", "if params is not None: self._params = params else: self._params = list(inner_env(self.wrapped_env).domain_param.keys()) self._nominal", "= newp def set_adv(self, params): for key, value in zip(self._params, params): inner_env(self.wrapped_env).domain_param[key] =", "Constructor TODO :param wrapped_env: :param params: :param fixed: \"\"\" Serializable._init(self, locals()) EnvWrapper.__init__(self, wrapped_env)", "list(inner_env(self.wrapped_env).domain_param.keys()) self._nominal = inner_env(self.wrapped_env).get_nominal_domain_param() self.nominal['dt'] = 1 / 100. # TODO ATTENTION! THIS", "np.ndarray = None, domain_param: dict = None): obs = self.wrapped_env.reset(init_state, domain_param) params =", "self._nominal = inner_env(self.wrapped_env).get_nominal_domain_param() self.nominal['dt'] = 1 / 100. # TODO ATTENTION! THIS CAN", "BE DEADLY! @Robin, why are you doing this? self._nominal = np.array([self._nominal[k] for k", "TODO \"\"\" def __init__(self, wrapped_env: Env, params=None, fixed=False): \"\"\" Constructor TODO :param wrapped_env:", ":param wrapped_env: :param params: :param fixed: \"\"\" Serializable._init(self, locals()) EnvWrapper.__init__(self, wrapped_env) if params", "why are you doing this? self._nominal = np.array([self._nominal[k] for k in self._params]) self.fixed", "self._nominal, 1.5 * self._nominal, [self._nominal.shape[0]], self._params) return BoxSpace.cat((outer_space, augmented_space)) def step(self, act: np.ndarray):", "augmented_space = BoxSpace(0.5 * self._nominal, 1.5 * self._nominal, [self._nominal.shape[0]], self._params) return BoxSpace.cat((outer_space, augmented_space))", "obs, reward, done, info = self.wrapped_env.step(act) params = self._params_as_tensor() obs = np.concatenate((obs, params))", "= self.wrapped_env.reset(init_state, domain_param) params = self._params_as_tensor() obs = np.concatenate((obs, params)) return obs @property", "newp[key] = value.item() inner_env(self.wrapped_env).domain_param = newp def set_adv(self, params): for key, value in", "numpy as np from init_args_serializer import Serializable from pyrado.environment_wrappers.base import EnvWrapper from pyrado.environment_wrappers.utils", "pyrado.environment_wrappers.base import EnvWrapper from pyrado.environment_wrappers.utils import inner_env from pyrado.environments.base import Env from pyrado.utils.data_types", "\"\"\" Constructor TODO :param wrapped_env: :param params: :param fixed: \"\"\" Serializable._init(self, locals()) EnvWrapper.__init__(self,", "= params else: self._params = list(inner_env(self.wrapped_env).domain_param.keys()) self._nominal = inner_env(self.wrapped_env).get_nominal_domain_param() self.nominal['dt'] = 1 /", "def reset(self, init_state: np.ndarray = None, domain_param: dict = None): obs = self.wrapped_env.reset(init_state,", "<reponame>jacarvalho/SimuRLacra import numpy as np from init_args_serializer import Serializable from pyrado.environment_wrappers.base import EnvWrapper", "pyrado.spaces.box import BoxSpace class StateAugmentationWrapper(EnvWrapper, Serializable): \"\"\" TODO \"\"\" def __init__(self, wrapped_env: Env,", "newp = dict() for key, value in zip(self._params, params): newp[key] = value.item() inner_env(self.wrapped_env).domain_param", "def mask(self): return np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim), np.ones(len(self._params)))) @property def offset(self): return self.wrapped_env.obs_space.flat_dim def set_param(self, params):", "key, value in zip(self._params, params): inner_env(self.wrapped_env).domain_param[key] = self._nominal[key] + value @property def nominal(self):", "= fixed def _params_as_tensor(self): if self.fixed: return self._nominal else: return np.array([inner_env(self.wrapped_env).domain_param[k] for k", "params=None, fixed=False): \"\"\" Constructor TODO :param wrapped_env: :param params: :param fixed: \"\"\" Serializable._init(self,", "are you doing this? self._nominal = np.array([self._nominal[k] for k in self._params]) self.fixed =", "np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim), np.ones(len(self._params)))) @property def offset(self): return self.wrapped_env.obs_space.flat_dim def set_param(self, params): newp = dict()", "locals()) EnvWrapper.__init__(self, wrapped_env) if params is not None: self._params = params else: self._params", "ATTENTION! THIS CAN BE DEADLY! @Robin, why are you doing this? self._nominal =", "self._params]) self.fixed = fixed def _params_as_tensor(self): if self.fixed: return self._nominal else: return np.array([inner_env(self.wrapped_env).domain_param[k]", "pyrado.environments.base import Env from pyrado.utils.data_types import EnvSpec from pyrado.spaces.box import BoxSpace class StateAugmentationWrapper(EnvWrapper,", "return BoxSpace.cat((outer_space, augmented_space)) def step(self, act: np.ndarray): obs, reward, done, info = self.wrapped_env.step(act)", "from init_args_serializer import Serializable from pyrado.environment_wrappers.base import EnvWrapper from pyrado.environment_wrappers.utils import inner_env from", "from pyrado.environment_wrappers.utils import inner_env from pyrado.environments.base import Env from pyrado.utils.data_types import EnvSpec from", "self._params_as_tensor() obs = np.concatenate((obs, params)) return obs @property def mask(self): return np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim), np.ones(len(self._params))))", "value in zip(self._params, params): newp[key] = value.item() inner_env(self.wrapped_env).domain_param = newp def set_adv(self, params):", "for key, value in zip(self._params, params): newp[key] = value.item() inner_env(self.wrapped_env).domain_param = newp def", "fixed: \"\"\" Serializable._init(self, locals()) EnvWrapper.__init__(self, wrapped_env) if params is not None: self._params =", "= self._params_as_tensor() obs = np.concatenate((obs, params)) return obs, reward, done, info def reset(self,", "params): for key, value in zip(self._params, params): inner_env(self.wrapped_env).domain_param[key] = self._nominal[key] + value @property", "= BoxSpace(0.5 * self._nominal, 1.5 * self._nominal, [self._nominal.shape[0]], self._params) return BoxSpace.cat((outer_space, augmented_space)) def", "info def reset(self, init_state: np.ndarray = None, domain_param: dict = None): obs =", "StateAugmentationWrapper(EnvWrapper, Serializable): \"\"\" TODO \"\"\" def __init__(self, wrapped_env: Env, params=None, fixed=False): \"\"\" Constructor", "info = self.wrapped_env.step(act) params = self._params_as_tensor() obs = np.concatenate((obs, params)) return obs, reward,", "init_state: np.ndarray = None, domain_param: dict = None): obs = self.wrapped_env.reset(init_state, domain_param) params", "self._params) return BoxSpace.cat((outer_space, augmented_space)) def step(self, act: np.ndarray): obs, reward, done, info =", "np.concatenate((obs, params)) return obs, reward, done, info def reset(self, init_state: np.ndarray = None,", "TODO :param wrapped_env: :param params: :param fixed: \"\"\" Serializable._init(self, locals()) EnvWrapper.__init__(self, wrapped_env) if", "import EnvWrapper from pyrado.environment_wrappers.utils import inner_env from pyrado.environments.base import Env from pyrado.utils.data_types import", "import Env from pyrado.utils.data_types import EnvSpec from pyrado.spaces.box import BoxSpace class StateAugmentationWrapper(EnvWrapper, Serializable):", "= 1 / 100. # TODO ATTENTION! THIS CAN BE DEADLY! @Robin, why", "this? self._nominal = np.array([self._nominal[k] for k in self._params]) self.fixed = fixed def _params_as_tensor(self):", "@property def obs_space(self): outer_space = self.wrapped_env.obs_space augmented_space = BoxSpace(0.5 * self._nominal, 1.5 *", "value in zip(self._params, params): inner_env(self.wrapped_env).domain_param[key] = self._nominal[key] + value @property def nominal(self): return", "Serializable): \"\"\" TODO \"\"\" def __init__(self, wrapped_env: Env, params=None, fixed=False): \"\"\" Constructor TODO", "k in self._params]) self.fixed = fixed def _params_as_tensor(self): if self.fixed: return self._nominal else:", "for k in self._params]) @property def obs_space(self): outer_space = self.wrapped_env.obs_space augmented_space = BoxSpace(0.5", "from pyrado.utils.data_types import EnvSpec from pyrado.spaces.box import BoxSpace class StateAugmentationWrapper(EnvWrapper, Serializable): \"\"\" TODO", "obs_space(self): outer_space = self.wrapped_env.obs_space augmented_space = BoxSpace(0.5 * self._nominal, 1.5 * self._nominal, [self._nominal.shape[0]],", "\"\"\" def __init__(self, wrapped_env: Env, params=None, fixed=False): \"\"\" Constructor TODO :param wrapped_env: :param", "inner_env(self.wrapped_env).domain_param = newp def set_adv(self, params): for key, value in zip(self._params, params): inner_env(self.wrapped_env).domain_param[key]", "obs = self.wrapped_env.reset(init_state, domain_param) params = self._params_as_tensor() obs = np.concatenate((obs, params)) return obs", "return obs @property def mask(self): return np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim), np.ones(len(self._params)))) @property def offset(self): return self.wrapped_env.obs_space.flat_dim", "import numpy as np from init_args_serializer import Serializable from pyrado.environment_wrappers.base import EnvWrapper from", "for key, value in zip(self._params, params): inner_env(self.wrapped_env).domain_param[key] = self._nominal[key] + value @property def", "params)) return obs, reward, done, info def reset(self, init_state: np.ndarray = None, domain_param:", "wrapped_env: Env, params=None, fixed=False): \"\"\" Constructor TODO :param wrapped_env: :param params: :param fixed:", "DEADLY! @Robin, why are you doing this? self._nominal = np.array([self._nominal[k] for k in", "inner_env from pyrado.environments.base import Env from pyrado.utils.data_types import EnvSpec from pyrado.spaces.box import BoxSpace", "* self._nominal, [self._nominal.shape[0]], self._params) return BoxSpace.cat((outer_space, augmented_space)) def step(self, act: np.ndarray): obs, reward,", "domain_param: dict = None): obs = self.wrapped_env.reset(init_state, domain_param) params = self._params_as_tensor() obs =", "params = self._params_as_tensor() obs = np.concatenate((obs, params)) return obs, reward, done, info def", "[self._nominal.shape[0]], self._params) return BoxSpace.cat((outer_space, augmented_space)) def step(self, act: np.ndarray): obs, reward, done, info", "def __init__(self, wrapped_env: Env, params=None, fixed=False): \"\"\" Constructor TODO :param wrapped_env: :param params:", "domain_param) params = self._params_as_tensor() obs = np.concatenate((obs, params)) return obs @property def mask(self):", "@property def offset(self): return self.wrapped_env.obs_space.flat_dim def set_param(self, params): newp = dict() for key,", "obs = np.concatenate((obs, params)) return obs @property def mask(self): return np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim), np.ones(len(self._params)))) @property", "# TODO ATTENTION! THIS CAN BE DEADLY! @Robin, why are you doing this?", "inner_env(self.wrapped_env).get_nominal_domain_param() self.nominal['dt'] = 1 / 100. # TODO ATTENTION! THIS CAN BE DEADLY!", "self.fixed: return self._nominal else: return np.array([inner_env(self.wrapped_env).domain_param[k] for k in self._params]) @property def obs_space(self):", "obs, reward, done, info def reset(self, init_state: np.ndarray = None, domain_param: dict =", "set_adv(self, params): for key, value in zip(self._params, params): inner_env(self.wrapped_env).domain_param[key] = self._nominal[key] + value", "doing this? self._nominal = np.array([self._nominal[k] for k in self._params]) self.fixed = fixed def", "you doing this? self._nominal = np.array([self._nominal[k] for k in self._params]) self.fixed = fixed", "offset(self): return self.wrapped_env.obs_space.flat_dim def set_param(self, params): newp = dict() for key, value in", "Serializable from pyrado.environment_wrappers.base import EnvWrapper from pyrado.environment_wrappers.utils import inner_env from pyrado.environments.base import Env", "\"\"\" Serializable._init(self, locals()) EnvWrapper.__init__(self, wrapped_env) if params is not None: self._params = params", "np from init_args_serializer import Serializable from pyrado.environment_wrappers.base import EnvWrapper from pyrado.environment_wrappers.utils import inner_env", "import inner_env from pyrado.environments.base import Env from pyrado.utils.data_types import EnvSpec from pyrado.spaces.box import", "else: return np.array([inner_env(self.wrapped_env).domain_param[k] for k in self._params]) @property def obs_space(self): outer_space = self.wrapped_env.obs_space", "def offset(self): return self.wrapped_env.obs_space.flat_dim def set_param(self, params): newp = dict() for key, value", "pyrado.environment_wrappers.utils import inner_env from pyrado.environments.base import Env from pyrado.utils.data_types import EnvSpec from pyrado.spaces.box", "= list(inner_env(self.wrapped_env).domain_param.keys()) self._nominal = inner_env(self.wrapped_env).get_nominal_domain_param() self.nominal['dt'] = 1 / 100. # TODO ATTENTION!", "* self._nominal, 1.5 * self._nominal, [self._nominal.shape[0]], self._params) return BoxSpace.cat((outer_space, augmented_space)) def step(self, act:", "= np.concatenate((obs, params)) return obs @property def mask(self): return np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim), np.ones(len(self._params)))) @property def", ":param fixed: \"\"\" Serializable._init(self, locals()) EnvWrapper.__init__(self, wrapped_env) if params is not None: self._params", "k in self._params]) @property def obs_space(self): outer_space = self.wrapped_env.obs_space augmented_space = BoxSpace(0.5 *", "100. # TODO ATTENTION! THIS CAN BE DEADLY! @Robin, why are you doing", "from pyrado.spaces.box import BoxSpace class StateAugmentationWrapper(EnvWrapper, Serializable): \"\"\" TODO \"\"\" def __init__(self, wrapped_env:", "in self._params]) @property def obs_space(self): outer_space = self.wrapped_env.obs_space augmented_space = BoxSpace(0.5 * self._nominal,", "augmented_space)) def step(self, act: np.ndarray): obs, reward, done, info = self.wrapped_env.step(act) params =", "class StateAugmentationWrapper(EnvWrapper, Serializable): \"\"\" TODO \"\"\" def __init__(self, wrapped_env: Env, params=None, fixed=False): \"\"\"", "Serializable._init(self, locals()) EnvWrapper.__init__(self, wrapped_env) if params is not None: self._params = params else:", "Env, params=None, fixed=False): \"\"\" Constructor TODO :param wrapped_env: :param params: :param fixed: \"\"\"", "EnvWrapper.__init__(self, wrapped_env) if params is not None: self._params = params else: self._params =", "in self._params]) self.fixed = fixed def _params_as_tensor(self): if self.fixed: return self._nominal else: return", "CAN BE DEADLY! @Robin, why are you doing this? self._nominal = np.array([self._nominal[k] for", "self.wrapped_env.obs_space.flat_dim def set_param(self, params): newp = dict() for key, value in zip(self._params, params):", "outer_space = self.wrapped_env.obs_space augmented_space = BoxSpace(0.5 * self._nominal, 1.5 * self._nominal, [self._nominal.shape[0]], self._params)", "= inner_env(self.wrapped_env).get_nominal_domain_param() self.nominal['dt'] = 1 / 100. # TODO ATTENTION! THIS CAN BE", "self.fixed = fixed def _params_as_tensor(self): if self.fixed: return self._nominal else: return np.array([inner_env(self.wrapped_env).domain_param[k] for", "_params_as_tensor(self): if self.fixed: return self._nominal else: return np.array([inner_env(self.wrapped_env).domain_param[k] for k in self._params]) @property", "1.5 * self._nominal, [self._nominal.shape[0]], self._params) return BoxSpace.cat((outer_space, augmented_space)) def step(self, act: np.ndarray): obs,", "= self._params_as_tensor() obs = np.concatenate((obs, params)) return obs @property def mask(self): return np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim),", "@property def mask(self): return np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim), np.ones(len(self._params)))) @property def offset(self): return self.wrapped_env.obs_space.flat_dim def set_param(self,", "return obs, reward, done, info def reset(self, init_state: np.ndarray = None, domain_param: dict", "Env from pyrado.utils.data_types import EnvSpec from pyrado.spaces.box import BoxSpace class StateAugmentationWrapper(EnvWrapper, Serializable): \"\"\"", "dict() for key, value in zip(self._params, params): newp[key] = value.item() inner_env(self.wrapped_env).domain_param = newp", "params): newp[key] = value.item() inner_env(self.wrapped_env).domain_param = newp def set_adv(self, params): for key, value", "not None: self._params = params else: self._params = list(inner_env(self.wrapped_env).domain_param.keys()) self._nominal = inner_env(self.wrapped_env).get_nominal_domain_param() self.nominal['dt']", "fixed=False): \"\"\" Constructor TODO :param wrapped_env: :param params: :param fixed: \"\"\" Serializable._init(self, locals())", "self._params = list(inner_env(self.wrapped_env).domain_param.keys()) self._nominal = inner_env(self.wrapped_env).get_nominal_domain_param() self.nominal['dt'] = 1 / 100. # TODO", "self.wrapped_env.step(act) params = self._params_as_tensor() obs = np.concatenate((obs, params)) return obs, reward, done, info", "obs = np.concatenate((obs, params)) return obs, reward, done, info def reset(self, init_state: np.ndarray", "return self.wrapped_env.obs_space.flat_dim def set_param(self, params): newp = dict() for key, value in zip(self._params,", "import EnvSpec from pyrado.spaces.box import BoxSpace class StateAugmentationWrapper(EnvWrapper, Serializable): \"\"\" TODO \"\"\" def", "= value.item() inner_env(self.wrapped_env).domain_param = newp def set_adv(self, params): for key, value in zip(self._params,", "\"\"\" TODO \"\"\" def __init__(self, wrapped_env: Env, params=None, fixed=False): \"\"\" Constructor TODO :param", "wrapped_env: :param params: :param fixed: \"\"\" Serializable._init(self, locals()) EnvWrapper.__init__(self, wrapped_env) if params is", "done, info def reset(self, init_state: np.ndarray = None, domain_param: dict = None): obs", "pyrado.utils.data_types import EnvSpec from pyrado.spaces.box import BoxSpace class StateAugmentationWrapper(EnvWrapper, Serializable): \"\"\" TODO \"\"\"", "self.wrapped_env.reset(init_state, domain_param) params = self._params_as_tensor() obs = np.concatenate((obs, params)) return obs @property def", "key, value in zip(self._params, params): newp[key] = value.item() inner_env(self.wrapped_env).domain_param = newp def set_adv(self,", "reward, done, info = self.wrapped_env.step(act) params = self._params_as_tensor() obs = np.concatenate((obs, params)) return", "dict = None): obs = self.wrapped_env.reset(init_state, domain_param) params = self._params_as_tensor() obs = np.concatenate((obs,", "from pyrado.environments.base import Env from pyrado.utils.data_types import EnvSpec from pyrado.spaces.box import BoxSpace class", "BoxSpace.cat((outer_space, augmented_space)) def step(self, act: np.ndarray): obs, reward, done, info = self.wrapped_env.step(act) params", "np.ones(len(self._params)))) @property def offset(self): return self.wrapped_env.obs_space.flat_dim def set_param(self, params): newp = dict() for", "= self.wrapped_env.obs_space augmented_space = BoxSpace(0.5 * self._nominal, 1.5 * self._nominal, [self._nominal.shape[0]], self._params) return", "return np.array([inner_env(self.wrapped_env).domain_param[k] for k in self._params]) @property def obs_space(self): outer_space = self.wrapped_env.obs_space augmented_space", "np.array([inner_env(self.wrapped_env).domain_param[k] for k in self._params]) @property def obs_space(self): outer_space = self.wrapped_env.obs_space augmented_space =", "None): obs = self.wrapped_env.reset(init_state, domain_param) params = self._params_as_tensor() obs = np.concatenate((obs, params)) return", "wrapped_env) if params is not None: self._params = params else: self._params = list(inner_env(self.wrapped_env).domain_param.keys())", "1 / 100. # TODO ATTENTION! THIS CAN BE DEADLY! @Robin, why are", "return self._nominal else: return np.array([inner_env(self.wrapped_env).domain_param[k] for k in self._params]) @property def obs_space(self): outer_space", "import BoxSpace class StateAugmentationWrapper(EnvWrapper, Serializable): \"\"\" TODO \"\"\" def __init__(self, wrapped_env: Env, params=None,", "self._params_as_tensor() obs = np.concatenate((obs, params)) return obs, reward, done, info def reset(self, init_state:", "EnvSpec from pyrado.spaces.box import BoxSpace class StateAugmentationWrapper(EnvWrapper, Serializable): \"\"\" TODO \"\"\" def __init__(self,", "= None): obs = self.wrapped_env.reset(init_state, domain_param) params = self._params_as_tensor() obs = np.concatenate((obs, params))", "is not None: self._params = params else: self._params = list(inner_env(self.wrapped_env).domain_param.keys()) self._nominal = inner_env(self.wrapped_env).get_nominal_domain_param()", "self._nominal, [self._nominal.shape[0]], self._params) return BoxSpace.cat((outer_space, augmented_space)) def step(self, act: np.ndarray): obs, reward, done,", "params is not None: self._params = params else: self._params = list(inner_env(self.wrapped_env).domain_param.keys()) self._nominal =", "params)) return obs @property def mask(self): return np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim), np.ones(len(self._params)))) @property def offset(self): return", "init_args_serializer import Serializable from pyrado.environment_wrappers.base import EnvWrapper from pyrado.environment_wrappers.utils import inner_env from pyrado.environments.base", "def step(self, act: np.ndarray): obs, reward, done, info = self.wrapped_env.step(act) params = self._params_as_tensor()", "step(self, act: np.ndarray): obs, reward, done, info = self.wrapped_env.step(act) params = self._params_as_tensor() obs", "BoxSpace(0.5 * self._nominal, 1.5 * self._nominal, [self._nominal.shape[0]], self._params) return BoxSpace.cat((outer_space, augmented_space)) def step(self,", "done, info = self.wrapped_env.step(act) params = self._params_as_tensor() obs = np.concatenate((obs, params)) return obs,", ":param params: :param fixed: \"\"\" Serializable._init(self, locals()) EnvWrapper.__init__(self, wrapped_env) if params is not", "params: :param fixed: \"\"\" Serializable._init(self, locals()) EnvWrapper.__init__(self, wrapped_env) if params is not None:", "newp def set_adv(self, params): for key, value in zip(self._params, params): inner_env(self.wrapped_env).domain_param[key] = self._nominal[key]", "np.array([self._nominal[k] for k in self._params]) self.fixed = fixed def _params_as_tensor(self): if self.fixed: return", "act: np.ndarray): obs, reward, done, info = self.wrapped_env.step(act) params = self._params_as_tensor() obs =", "obs @property def mask(self): return np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim), np.ones(len(self._params)))) @property def offset(self): return self.wrapped_env.obs_space.flat_dim def", "def obs_space(self): outer_space = self.wrapped_env.obs_space augmented_space = BoxSpace(0.5 * self._nominal, 1.5 * self._nominal,", "reward, done, info def reset(self, init_state: np.ndarray = None, domain_param: dict = None):", "mask(self): return np.concatenate((np.zeros(self.wrapped_env.obs_space.flat_dim), np.ones(len(self._params)))) @property def offset(self): return self.wrapped_env.obs_space.flat_dim def set_param(self, params): newp", "params): newp = dict() for key, value in zip(self._params, params): newp[key] = value.item()", "= dict() for key, value in zip(self._params, params): newp[key] = value.item() inner_env(self.wrapped_env).domain_param =", "self._nominal = np.array([self._nominal[k] for k in self._params]) self.fixed = fixed def _params_as_tensor(self): if", "def set_adv(self, params): for key, value in zip(self._params, params): inner_env(self.wrapped_env).domain_param[key] = self._nominal[key] +", "params else: self._params = list(inner_env(self.wrapped_env).domain_param.keys()) self._nominal = inner_env(self.wrapped_env).get_nominal_domain_param() self.nominal['dt'] = 1 / 100.", "THIS CAN BE DEADLY! @Robin, why are you doing this? self._nominal = np.array([self._nominal[k]", "None, domain_param: dict = None): obs = self.wrapped_env.reset(init_state, domain_param) params = self._params_as_tensor() obs", "EnvWrapper from pyrado.environment_wrappers.utils import inner_env from pyrado.environments.base import Env from pyrado.utils.data_types import EnvSpec", "@Robin, why are you doing this? self._nominal = np.array([self._nominal[k] for k in self._params])" ]
[ "potential principle is matched in all subsequent attempts # This covers the intermediate", "if a['perservative']: totalPerserverative +=1 if not a['perservative']: totalNonPerserverative +=1 if (not a['perservative'] and", "False if ( test[a]['sandwiched'] and 'NOT perservative per 2c' not in test[a]['reasoning'] ):", "Principle checkFirstSetPers(test, attempt['attemptNum']) for attempt in test: # 5. Heaton's rule 3: Find", "sandwichBefore == False: return False # Next we check forwards. y = attemptNum", "return False # if test[x]['sandwiched']: return False if (test[x]['ambiguous'] == False and test[x]['perservative']", "totalPerserverative +=1 if not a['perservative']: totalNonPerserverative +=1 if (not a['perservative'] and not a['correct']):", "2b. Marking perservative.' return True x-=1 def isChainedSandwich(test, attemptNum): if not isSandwiched(test, attemptNum):", "+= 1 # print('Holy shit, we found one on attempt ', attemptNum) #", "saveResults(test): with open('ANALYSIS_' + test[0]['file'] + '.csv', 'w', newline='') as csvfile: cw =", "the rule was not established this attempt (on the first set). # We", "the category changer run after this? ##################################### # Set all the rest, up", "# print (str(attemptNum) + ' Sandwiched After by attempt ' + str(y)) break", "'match' : attempt[MATCH], 'stimulus' : splitStim(attempt[STIMULUS]), 'response' : splitStim(attempt[RESPONSE]), 'testNum' : testNum, '2c'", "cw.writerow(['Class', 'Subject', 'Sets Attempted', 'Correct', 'Errors', 'Non-Perserverative', 'Non-Perserverative Errors', 'Perserverative', 'Trials', '% Perserverative'])", "if not isSandwiched(test, attemptNum): return False if isFirstSandwich(test, attemptNum): return False x =", "' - Attempt is chain sandwich perservative per 2c' test[a]['perservative'] = True return", "# including the second response) as unscorable x = unambiguousMatches[0] while x <", "was an unambiguous error matching the perservative-to rule, AND # the rule was", "if 'ANALYSIS' in filename: continue # Skip any generated analysis files # if", "per 2c' not in test[a]['reasoning'] ): test[a]['reasoning'] += ' - Sandwiched attempt is", "if test[attemptNum]['response'][k] == v: test[attemptNum]['currentPerservativeTo'] = k test[attemptNum]['set1PrincipleEstablished'] = True test[attemptNum]['reasoning'] += '", "is a first sandwich, matching 2a and 2b. Marking perservative.' return True x-=1", "= 0 totalNonPerserverativeErrors = 0 totalPerserverative = 0 totalTrials = 0 for a", "test[0]['file'])) def splitStim(stim): x = re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)', stim) return { 'color' : x.group(1), 'form'", "prin else: prin = '' if a['correct']: corr = '+ ' else: corr", "classNum): test = [] # Open the file and read it into memory", "== test[attemptNum]['currentPerservativeTo'] ): sandwichAfter = True # print (str(attemptNum) + ' Sandwiched After", "incorrect answer. Skip the answer # in which the Principle principle was established", "sure it's an error match = matches[0] # If we get here, then", "pers + ')' return True else: return False def getMatches(test, a): matches =", "a['match'] def printTest(test): x = PrettyTable() # x.padding_width = 10 x.left_padding_width = 1", "True else: return False def checkFirstSetPers(test, attemptNum): # Break out if this is", "False def checkSelfPerserveration(test, a): # 1. The client must make 3 unambiguous errors", "'Non-Perserverative Errors', 'Perserverative', 'Trials', '% Perserverative']) cw.writerow([ t[0]['classNum'], t[0]['subject'], totalSetsAttempted, totalCorrect, totalError, totalNonPerserverative,", "following are all boolean 'correct' : False, 'perservative' : False, 'ambiguous' : False,", "the principle the same as last attempt.The current # principle will be the", "(in our example, Color as defined by # > the previous sorting category)", "'iqdat' in filename: continue fullpath = os.path.join(path, filename) # Get the filename for", "testNum, classNum)) for t in allTests: totalCorrect = 0 totalError = 0 totalSetsAttempted", "isCorrect(test, a): return False # Make sure it's an error match = matches[0]", "our example, Color as defined by # > the previous sorting category) #", "Sandwiched After by attempt ' + str(y)) break y += 1 if sandwichAfter", "continue # Not currently pers # It's a match! unambiguousMatches.append(test[x]['attemptNum']) if len(unambiguousMatches) ==", "all boolean 'correct' : False, 'perservative' : False, 'ambiguous' : False, 'sandwiched' :", "fullpath) lineCount += 1 # First pass: Analyze the data with a set", "stimulus on the match criteria match = test[a]['match'] if test[a]['stimulus'][match] == test[a]['response'][match]: return", "k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: matchQuotient += 1 # Mark", "test[attemptNum]['set']: return False if isSandwiched(test, x): return False # if test[x]['sandwiched']: return False", "test[unambiguousMatches[2]]['reasoning'] += ' - Rule 3: Final unambiguous self-perserveration' # Set all responses", "'Reasoning']) prevMatch = '' prevPrin = '' for a in test: response =", "Contains plaintext reasoning to help verify results # The following are all boolean", "tests, so we finish the loop this way and then loop again checkUnambiguousPerserveration(test,", "2. All responses between the first and third unambiguous response must # match", "matching the perservative-to rule, AND # the rule was not established this attempt", "as unscorable x = unambiguousMatches[0] while x < unambiguousMatches[1]: test[x]['currentPerservativeTo'] = None test[x]['reasoning']", "= prin else: prin = '' if a['correct']: corr = '+ ' else:", "v: matchQuotient += 1 # Mark whether the attempt is ambiguous if matchQuotient", "Attempt is a first sandwich, matching 2a and 2b. Marking perservative.' return True", "= '' for a in test: response = '' if a['stimulus']['color'] == a['response']['color']:", "' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']), '\\n', unambiguousMatches, '\\n') test[unambiguousMatches[0]]['rule_3_1'] = True", "previous pattern.' return True else: test[attemptNum]['reasoning'] += 'Principle is none due to start", "change to true if the principle changed this attempt in the first set", "x+=1 # Make sure the potential principle is matched in all subsequent attempts", "test[x]['currentPerservativeTo'] = None test[x]['reasoning'] += ' - Rule 3: Set to unscorable for", "always clean. try: attempt = line.split() test.append({ 'file' : os.path.basename(fullpath), 'attemptNum' : lineCount,", "First pass: Analyze the data with a set of rules for attempt in", "totalSetsAttempted = 0 totalNonPerserverative = 0 totalNonPerserverativeErrors = 0 totalPerserverative = 0 totalTrials", "satisfies Heaton rule 2a: # > The ambiguous response must match the #", "error handling because the text files aren't always clean. try: attempt = line.split()", "not sandwiched' in test[attemptNum]['reasoning']: test[attemptNum]['reasoning'] += ' - Attempt is not sandwiched.' return", "has not been determined (first set) then the first unambiguous # incorrect answer", "== a['response']['form']: response += 'F* ' else: response += 'F ' if a['stimulus']['number']", "x.group(2), 'number' : x.group(3) } def continuePreviousPresTo(test, attemptNum): if attemptNum > 0: test[attemptNum]['currentPerservativeTo']", "Make sure it's an error match = matches[0] # If we get here,", "array of Dicts # Added some error handling because the text files aren't", "Now we start looking for ambiguous perserverations. Here we check the # \"sandwich", "'' if a['currentPerservativeTo'] != prevPrin: prin = a['currentPerservativeTo'] prevPrin = prin else: prin", "attemptNum + 1 sandwichAfter = False while y < len(test): if test[y]['set'] !=", "per 2c' test[a]['perservative'] = True return True else: test[a]['2c'] = False if (", "All responses between the first and third unambiguous response must # match this", "path, dirs, files in os.walk(PATH): if path == PATH: continue # Skip the", "+ '.csv').st_size == 0: cw.writerow(['Class', 'Subject', 'Sets Attempted', 'Correct', 'Errors', 'Non-Perserverative', 'Non-Perserverative Errors',", "getMatches(test, a): matches = [] for k, v in test[a]['stimulus'].items(): if test[a]['response'][k] ==", "currently pers # It's a match! unambiguousMatches.append(test[x]['attemptNum']) if len(unambiguousMatches) == 3: break if", "response matches the stimulus on the current Perserveration principle. # This would suggest", "on to the more complicated # tests, so we finish the loop this", "# Split the test report into an array of Dicts # Added some", "for attempt in test: # 5. Heaton's rule 3: Find self-made perserverations checkSelfPerserveration(test,", "True def checkChainedSandwich(test, a): if isChainedSandwich(test, a): test[a]['2c'] = True test[a]['reasoning'] += '", "(test[attemptNum]) # print (test[y]) # wait = input('') return True else: if not", "2c for chained perserverations checkChainedSandwich(test, attempt['attemptNum']) # Return the fully populated and analyzed", "is perserverating if test[attemptNum]['stimulus'][pers] == test[attemptNum]['response'][pers]: # test[attemptNum]['reasoning'] += ' - Attempt has", "isCorrect(test, attemptNum): test[attemptNum]['correct'] = True else: test[attemptNum]['correct'] = False def isCorrect(test, a): #", "response += 'F ' if a['stimulus']['number'] == a['response']['number']: response += 'N* ' else:", "- 1 while x > 0: if test[x]['set'] != test[attemptNum]['set']: return False #", "False, # Will change to true if the principle changed this attempt in", "+=1 if not a['perservative']: totalNonPerserverative +=1 if (not a['perservative'] and not a['correct']): totalNonPerserverativeErrors", "str(y)) break y += 1 if sandwichAfter and sandwichBefore: #Mark the sandwich if", "analyzed test object # printTest(test) saveResults(test) return test # Iterate through each file", "a['firstSandwich']: sw= '+' else: sw = '' if a['2c']: chain = '+' else:", "= False while x > 0: if test[x]['set'] != test[attemptNum]['set']: break if (test[x]['ambiguous']", "False def getMatches(test, a): matches = [] for k, v in test[a]['stimulus'].items(): if", "', ' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']), '\\n', unambiguousMatches, '\\n') test[unambiguousMatches[0]]['rule_3_1'] =", "we start looking for ambiguous perserverations. Here we check the # \"sandwich rule.\"", "folder which contains the tests PATH = os.getcwd() # r\"C:\\Users\\wyko.terhaar\\Downloads\\Map voor Wyko\\raw\" #", "+ ' Sandwiched Before by attempt ' + str(x)) break x -= 1", "a subsequent rule. continuePreviousPresTo(test, attempt['attemptNum']) # 2. Check if we just moved into", "0: return None if test[attemptNum]['set'] != test[attemptNum-1]['set']: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['match'] test[attemptNum]['reasoning'] += '", "it's an error match = matches[0] # If we get here, then we", "a['set'] # Will end up being the final set if a['perservative']: totalPerserverative +=1", "lineCount = 0 for line in lines: # Split the test report into", "Other category, Principle isn't set. test[attemptNum]['reasoning'] += ' - Client perserverated to Other", "We need 3 to confirm self-perserveration # print{'Added first', x) while x <", "Will end up being the final set if a['perservative']: totalPerserverative +=1 if not", "2. Check if we just moved into a new set, and adjust the", "print(x.get_string(title= str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']) + ',", "False # One match for an unambiguous result if test[a]['currentPerservativeTo'] in matches: return", "Final unambiguous self-perserveration' # Set all responses from the first untill the second", "principle that is currently in # > effect (in our example, Color as", "not test[attemptNum]['ambiguous']: return False # First we look backwards to find if an", "if test[attemptNum]['set'] != test[attemptNum-1]['set']: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['match'] test[attemptNum]['reasoning'] += ' - Principle was", "# > effect (in our example, Color as defined by # > the", "Let's look ahead for more indicators! x = a unambiguousMatches = [x,] #", "if a['perservative'] else '', '+' if a['ambiguous'] else '', sw, chain, 'X' if", "not been determined (first set) then the first unambiguous # incorrect answer determines", "test[attemptNum]['perservative'] = True return True else: return False def isSandwiched(test, attemptNum): # It", "Skip any python files if 'ANALYSIS' in filename: continue # Skip any generated", "the first untill the second response (not # including the second response) as", "test: # 8. Check if the sandwiched ambiguous answers are the first ones", "len(test): if test[y]['set'] != test[attemptNum]['set']: return False # Check to see if we", "attempt had an unambiguous incorrect answer. # If so, set the Principle whichever", "= match test[x]['reasoning'] += ' - Rule 3: Principle set to ' +", "False and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichAfter = True", "checkFirstSetPers(test, attemptNum): # Break out if this is not the first set if", "test[attemptNum]['sandwiched'] = True # print (str(attemptNum) + ' Sandwiched Before by attempt '", "corr = ' ' if a['firstSandwich']: sw= '+' else: sw = '' if", "No Principle set.' return None def containsPrincipleMatch(test, attemptNum): # Helper function which satisfies", "all if not containsPrincipleMatch(test, attemptNum): return False # It has to be ambiguous", "x -= 1 # Next we check forwards. y = attemptNum + 1", "else: chain = '' cw.writerow([a['attemptNum'], a['match'], #n, response, '+' if a['correct'] else '',", "+ t[0]['classNum'] + '.csv').st_size == 0: cw.writerow(['Class', 'Subject', 'Sets Attempted', 'Correct', 'Errors', 'Non-Perserverative',", "+ ' to continue previous pattern.' return True else: test[attemptNum]['reasoning'] += 'Principle is", "files if 'ANALYSIS' in filename: continue # Skip any generated analysis files #", "the same as last attempt.The current # principle will be the same as", "not match in tempMatches: return False # Now we look for the last", "2c' test[a]['perservative'] = True return True else: test[a]['2c'] = False if ( test[a]['sandwiched']", "True # print (str(attemptNum) + ' Sandwiched After by attempt ' + str(y))", "0 for a in t: if a['correct']: totalCorrect +=1 if not a['correct']: totalError", "# Iterate through each file in each folder in the PATH variable allTests", "Heaton's rule 3: Find self-made perserverations checkSelfPerserveration(test, attempt['attemptNum']) for attempt in test: #", "continue # Skip the root for filename in files: if '.py' in filename:", "= '' cw.writerow([a['attemptNum'], a['match'], #n, response, '+' if a['correct'] else '', a['currentPerservativeTo'], #prin,", "+= ' - Principle was set to ' + str(test[attemptNum]['currentPerservativeTo']) + ' (last", "print (test[x]) x+=1 ################################# # Principle is not set for future attempts. Maybe", "test report into an array of Dicts # Added some error handling because", "currently active Pres-To Principle 'reasoning' : '', # Contains plaintext reasoning to help", "by attempt ' + str(x)) # print (str(attemptNum) + ' Sandwiched After by", "x < unambiguousMatches[1]: test[x]['currentPerservativeTo'] = None test[x]['reasoning'] += ' - Rule 3: Set", "rule was not established this attempt (on the first set). # We have", "def isChainedSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return False if isFirstSandwich(test, attemptNum): return", "> effect (in our example, Color as defined by # > the previous", "attempt (on the first set). # We have to know this for every", "None and test[attemptNum]['set1PrincipleEstablished'] == False and containsPrincipleMatch(test, attemptNum) ): test[attemptNum]['reasoning'] += ' -", "unambiguous incorrect answer. Skip the answer # in which the Principle principle was", "the # \"sandwich rule.\" isSandwiched(test, attempt['attemptNum']) for attempt in test: # 8. Check", "see if we found the bread if (test[x]['ambiguous'] == False and test[x]['perservative'] ==", "open('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv', 'a', newline='') as csvfile:", "answer determines the first-set's Principle checkFirstSetPers(test, attempt['attemptNum']) for attempt in test: # 5.", "Determine if the answer is correct if isCorrect(test, attemptNum): test[attemptNum]['correct'] = True else:", "- Rule 3: Principle set to ' + match + ' due to", "'ambiguous' : False, 'sandwiched' : False, 'firstSandwich' : False, 'set1PrincipleEstablished' : False, #", "1 # Mark whether the attempt is ambiguous if matchQuotient > 1: test[attemptNum]['ambiguous']", "True test[a]['reasoning'] += ' - Attempt is chain sandwich perservative per 2c' test[a]['perservative']", "(' + test[attemptNum]['response'][pers] + ') which matches the principle (' + pers +", "for the same principle x = attemptNum - 1 sandwichBefore = False while", "STIMULUS = 9 RESPONSE = 10 def saveResults(test): with open('ANALYSIS_' + test[0]['file'] +", "test[attemptNum]['set'] != 1: return None # Break out if this was not an", "# First, we check to see if this is an unambiguous error #", "Check if we just moved into a new set, and adjust the principle", "test[unambiguousMatches[0]]['rule_3_1'] = True test[unambiguousMatches[0]]['reasoning'] += ' - Rule 3: First unambiguous self-perserveration' test[unambiguousMatches[1]]['rule_3_2']", "x): return False x -= 1 # Next we check forwards. y =", "line ' + str(lineCount) + ' in file: \\n' + fullpath) lineCount +=", "rule 3 'rule_3_2' : False, # for self perserverations 'rule_3_3' : False, })", "len(unambiguousMatches) != 3: return False # print(str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ',", "# 3. The new principle becomes active to register perserverations only # after", "def isCorrect(test, a): # Determine if a response matches the stimulus on the", "+= 'Principle was set to ' + str(test[attemptNum]['currentPerservativeTo']) + ' to continue previous", "print(\"Test \", x, \" principle set to \", match) x+=1 def analyzeTest(fullpath, testNum,", "Before by attempt ' + str(x)) # print (str(attemptNum) + ' Sandwiched After", "see if we found the bread if (test[y]['ambiguous'] == False and test[y]['perservative'] ==", "have a principle match to be considered perservative at all if not containsPrincipleMatch(test,", "a in test: response = '' if a['stimulus']['color'] == a['response']['color']: response += 'C*", "the client perserverated to the Other category, Principle isn't set. test[attemptNum]['reasoning'] += '", "answer if test[attemptNum]['correct'] == True: return None if test[attemptNum]['currentPerservativeTo'] is not None: test[attemptNum]['reasoning']", "(test[y]['ambiguous'] == False and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichAfter", "return False # Check to see if we found the bread if (test[x]['ambiguous']", "from first unambiguous error.' return True # If the client perserverated to the", "would suggest that this response is perserverating if test[attemptNum]['stimulus'][pers] == test[attemptNum]['response'][pers]: # test[attemptNum]['reasoning']", "test[attemptNum]['currentPerservativeTo'] is not None and test[attemptNum]['set1PrincipleEstablished'] == False and containsPrincipleMatch(test, attemptNum) ): test[attemptNum]['reasoning']", "return True else: if not 'Attempt is not sandwiched' in test[attemptNum]['reasoning']: test[attemptNum]['reasoning'] +=", "(str(attemptNum) + ' Sandwiched After by attempt ' + str(y)) # print (test[x])", "7. Now we start looking for ambiguous perserverations. Here we check the #", "test[attemptNum]['ambiguous']: return False # First we look backwards to find if an ambiguous,", "isSandwiched(test, attemptNum): # It has to have a principle match to be considered", "first untill the second response (not # including the second response) as unscorable", "+ ' and ' + str(y) test[attemptNum]['sandwiched'] = True # print (str(attemptNum) +", "set if a['perservative']: totalPerserverative +=1 if not a['perservative']: totalNonPerserverative +=1 if (not a['perservative']", "lineCount += 1 # First pass: Analyze the data with a set of", "the data with a set of rules for attempt in test: # 1.", "else: test[a]['2c'] = False if ( test[a]['sandwiched'] and 'NOT perservative per 2c' not", "it is an unambiguous result if isCorrect(test, x): continue # Make sure it's", "we look for the last two unambiguous errors to the new, not currently", "== False): for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: test[attemptNum]['currentPerservativeTo'] =", "test[attemptNum]['ambiguous'] = False # Determine if the answer is correct if isCorrect(test, attemptNum):", "the last two unambiguous errors to the new, not currently # perserverative principle", "== test[a]['response'][match]: return True else: return False def checkFirstSetPers(test, attemptNum): # Break out", "= f.readlines() # Iterate through the test and format it for analysis. Skip", "input('') return True else: if not 'Attempt is not sandwiched' in test[attemptNum]['reasoning']: test[attemptNum]['reasoning']", "the first set. if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False and test[attemptNum]['currentPerservativeTo']", "0 totalNonPerserverative = 0 totalNonPerserverativeErrors = 0 totalPerserverative = 0 totalTrials = 0", "if isSandwiched(test, x): return False # if test[x]['sandwiched']: return False if (test[x]['ambiguous'] ==", "= 5 SET = 6 STIMULUS = 9 RESPONSE = 10 def saveResults(test):", "to ' + str(test[attemptNum]['currentPerservativeTo']) + ' to continue previous pattern.' return True else:", "test[unambiguousMatches[0]]['reasoning'] += ' - Rule 3: First unambiguous self-perserveration' test[unambiguousMatches[1]]['rule_3_2'] = True test[unambiguousMatches[1]]['reasoning']", "x > 0: if test[x]['set'] != test[attemptNum]['set']: break if (test[x]['ambiguous'] == False and", "If the client perserverated to the Other category, Principle isn't set. test[attemptNum]['reasoning'] +=", "new set, and adjust the principle accordingly checkNewSet(test, attempt['attemptNum']) # 3. Check if", "- 1 while x > 0: if test[x]['set'] != test[attemptNum]['set']: return False if", "return False # First we look backwards to find if an ambiguous, potentially", "x = attemptNum - 1 sandwichBefore = False while x > 0: if", "Errors', 'Perserverative', 'Trials', '% Perserverative']) cw.writerow([ t[0]['classNum'], t[0]['subject'], totalSetsAttempted, totalCorrect, totalError, totalNonPerserverative, totalNonPerserverativeErrors,", "the first unambiguous # incorrect answer determines the first-set's Principle checkFirstSetPers(test, attempt['attemptNum']) for", "current principle and nothing else.' test[attemptNum]['perservative'] = True return True else: return False", "# Helper function which satisfies Heaton rule 2a: # > The ambiguous response", "if the principle changed this attempt in the first set 'rule_3_1' : False,", "been set yet. if test[attemptNum]['currentPerservativeTo'] is None: return False pers = test[attemptNum]['currentPerservativeTo'] #", "test[a]['response'][k] == v: matches.append(k) return matches def checkUnambiguousPerserveration(test, attemptNum): # Check if the", "current principle matches = getMatches(test, a) if len(matches) != 1: return False #", "test[attemptNum-1]['set']: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['match'] test[attemptNum]['reasoning'] += ' - Principle was set to '", "= p[len(p)-2] allTests.append(analyzeTest(fullpath, testNum, classNum)) for t in allTests: totalCorrect = 0 totalError", "' - Rule 3: Set to unscorable for first to second responses' #", "a['2c']: chain = '+' else: chain = '' x.add_row([a['attemptNum'], a['match'], #n, corr +", "on the current Perserveration principle. # This would suggest that this response is", "the answer # in which the Principle principle was established in the first", "+= ' - Attempt ' + str(attemptNum) + ' is \"sandwiched\" between '", "test[a]['reasoning'] += ' - Sandwiched attempt is NOT perservative per 2c' return False", "checkAnswer(test, attempt['attemptNum']) # 4. If Principle has not been determined (first set) then", "= input('') return True else: if not 'Attempt is not sandwiched' in test[attemptNum]['reasoning']:", "chain = '+' else: chain = '' cw.writerow([a['attemptNum'], a['match'], #n, response, '+' if", "os.path.basename(fullpath), 'attemptNum' : lineCount, 'subject' : int(attempt[SUBJECT]), 'set' : int(attempt[SET]), 'match' : attempt[MATCH],", "was an error checkAnswer(test, attempt['attemptNum']) # 4. If Principle has not been determined", "matched in all subsequent attempts # This covers the intermediate results tempMatches =", "principle the client matched if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False): for", "test[attemptNum]['stimulus'][pers] == test[attemptNum]['response'][pers]: # test[attemptNum]['reasoning'] += ' - Attempt has a response ('", "continue fullpath = os.path.join(path, filename) # Get the filename for each file #", "'', '+' if a['ambiguous'] else '', sw, chain, 'X' if a['rule_3_1'] else '',", "return True x-=1 def isChainedSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return False if", "in filename: continue fullpath = os.path.join(path, filename) # Get the filename for each", "'Correct', 'Pres-To', 'Perserverative', 'Ambiguous', \"2b (1st Sandwich)\", '2c (Chained Sandwich)', '3.1 (Self-Perserveration)', '3.2',", "> 0: if test[x]['set'] != test[attemptNum]['set']: break if (test[x]['ambiguous'] == False and test[x]['perservative']", "2c' return False def checkSelfPerserveration(test, a): # 1. The client must make 3", "3: return False # print(str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ', ' +", "return { 'color' : x.group(1), 'form' : x.group(2), 'number' : x.group(3) } def", "first set 'rule_3_1' : False, # These are to show matches for Heaton's", "Color as defined by # > the previous sorting category) # False if", "' if a['perservative'] and a['ambiguous']: pers = 'A-Pers' elif a['perservative']: pers = 'U-Pers'", "know the attempt is a candidate for the first indicator. # Let's look", "not established this attempt (on the first set). # We have to know", "else '', 'X' if a['rule_3_3'] else '', ]) prevMatch = a['match'] print(x.get_string(title= str(test[0]['classNum'])", "'_' + t[0]['classNum'] + '.csv').st_size == 0: cw.writerow(['Class', 'Subject', 'Sets Attempted', 'Correct', 'Errors',", "files # if not 'iqdat' in filename: continue fullpath = os.path.join(path, filename) #", "x < len(test)-1: x+=1 # Make sure the potential principle is matched in", "' - Rule 3: First unambiguous self-perserveration' test[unambiguousMatches[1]]['rule_3_2'] = True test[unambiguousMatches[1]]['reasoning'] += '", "rule, AND # the rule was not established this attempt (on the first", "unambiguousMatches[0] while x < unambiguousMatches[1]: test[x]['currentPerservativeTo'] = None test[x]['reasoning'] += ' - Rule", "sandwichBefore: #Mark the sandwich if it hasn't already been done if not test[attemptNum]['sandwiched']:", "matches for Heaton's rule 3 'rule_3_2' : False, # for self perserverations 'rule_3_3'", "checkChainedSandwich(test, attempt['attemptNum']) # Return the fully populated and analyzed test object # printTest(test)", "after attempt ' + str(test[unambiguousMatches[0]]['attemptNum']) test[unambiguousMatches[2]]['rule_3_3'] = True test[unambiguousMatches[2]]['reasoning'] += ' - Rule", "' + str(x)) # print (str(attemptNum) + ' Sandwiched After by attempt '", "established in the first set. if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False", "incorrect answer. # If so, set the Principle whichever principle the client matched", "the principle (' + pers + ')' return True else: return False def", "' - Principle was established as ' + k + ' from first", "# in which the Principle principle was established in the first set. if", "for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: test[attemptNum]['currentPerservativeTo'] = k test[attemptNum]['set1PrincipleEstablished']", "to be considered for sandwich perseveration if not test[attemptNum]['ambiguous']: return False # First", "str(test[unambiguousMatches[0]]['attemptNum']) test[unambiguousMatches[2]]['rule_3_3'] = True test[unambiguousMatches[2]]['reasoning'] += ' - Rule 3: Final unambiguous self-perserveration'", "this was not an incorrect answer if test[attemptNum]['correct'] == True: return None if", "if a['correct']: totalCorrect +=1 if not a['correct']: totalError +=1 totalSetsAttempted = a['set'] #", "x.padding_width = 10 x.left_padding_width = 1 x.right_padding_width = 1 x.field_names = ['#', \"Match\",", "to ' + str(test[attemptNum]['currentPerservativeTo']) + ' (last set match clause) because set was", "test: # 5. Heaton's rule 3: Find self-made perserverations checkSelfPerserveration(test, attempt['attemptNum']) for attempt", "3. Check if the attempt was an error checkAnswer(test, attempt['attemptNum']) # 4. If", "up being the final set if a['perservative']: totalPerserverative +=1 if not a['perservative']: totalNonPerserverative", "- Sandwiched attempt is NOT perservative per 2c' return False def checkSelfPerserveration(test, a):", "' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']) + ', ' + test[0]['file'])) def", "10 x.left_padding_width = 1 x.right_padding_width = 1 x.field_names = ['#', \"Match\", \"Matched\", 'Pres-To',", "sure it's an error if test[x]['currentPerservativeTo'] in tempMatches: continue # Not currently pers", "if a['rule_3_2'] else '', 'X' if a['rule_3_3'] else '', a['reasoning'] ]) prevMatch =", "and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): test[attemptNum]['firstSandwich'] = True test[attemptNum]['perservative'] = True test[attemptNum]['reasoning'] +=", "< len(test): if test[y]['set'] != test[attemptNum]['set']: break if (test[y]['ambiguous'] == False and test[y]['perservative']", "return False pers = test[attemptNum]['currentPerservativeTo'] # Check to see if the response matches", "not a['correct']: totalError +=1 totalSetsAttempted = a['set'] # Will end up being the", "attempt['attemptNum']) for attempt in test: # 6. If this was an unambiguous error", "Principle whichever principle the client matched if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] ==", "have a Principle if attemptNum == 0: return None if test[attemptNum]['set'] != test[attemptNum-1]['set']:", "category changer run after this? ##################################### # Set all the rest, up to", "dirs, files in os.walk(PATH): if path == PATH: continue # Skip the root", "+ str(test[0]['subject']) + ', ' + test[0]['file'])) def splitStim(stim): x = re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)', stim)", "False, 'sandwiched' : False, 'firstSandwich' : False, 'set1PrincipleEstablished' : False, # Will change", "totalCorrect = 0 totalError = 0 totalSetsAttempted = 0 totalNonPerserverative = 0 totalNonPerserverativeErrors", "else: response += 'N ' if a['perservative'] and a['ambiguous']: pers = 'A-Pers' elif", "= True test[unambiguousMatches[1]]['reasoning'] += ' - Rule 3: Second unambiguous self-perserveration after attempt", "Analyze the data with a set of rules for attempt in test: #", "principle and nothing else.' test[attemptNum]['perservative'] = True return True else: return False def", "determines the first-set's Principle checkFirstSetPers(test, attempt['attemptNum']) for attempt in test: # 5. Heaton's", "n = a['match'] else: n = '' if a['currentPerservativeTo'] != prevPrin: prin =", "by attempt ' + str(y)) break y += 1 if sandwichAfter and sandwichBefore:", "it into memory with open (fullpath) as f: lines = f.readlines() # Iterate", "test: response = '' if a['stimulus']['color'] == a['response']['color']: response += 'C* ' else:", "response, a['currentPerservativeTo'], #prin, pers, sw, chain, 'X' if a['rule_3_1'] else '', 'X' if", "False while x > 0: if test[x]['set'] != test[attemptNum]['set']: break if (test[x]['ambiguous'] ==", "accordingly checkNewSet(test, attempt['attemptNum']) # 3. Check if the attempt was an error checkAnswer(test,", "csv.writer(csvfile) cw.writerow(['#', 'Match', \"Response\", 'Correct', 'Pres-To', 'Perserverative', 'Ambiguous', \"2b (1st Sandwich)\", '2c (Chained", "' + test[0]['file'])) def splitStim(stim): x = re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)', stim) return { 'color' :", "if this is not the first set if test[attemptNum]['set'] != 1: return None", "2a and 2b. Marking perservative.' return True x-=1 def isChainedSandwich(test, attemptNum): if not", "'subject' : int(attempt[SUBJECT]), 'set' : int(attempt[SET]), 'match' : attempt[MATCH], 'stimulus' : splitStim(attempt[STIMULUS]), 'response'", "attempt in test: # 8. Check if the sandwiched ambiguous answers are the", "== test[attemptNum]['response'][pers]: # test[attemptNum]['reasoning'] += ' - Attempt has a response (' +", "+ ' Sandwiched After by attempt ' + str(y)) break y += 1", "attemptNum): return False x = attemptNum - 1 while x > 0: if", "x = a unambiguousMatches = [x,] # We need 3 to confirm self-perserveration", "return True def checkChainedSandwich(test, a): if isChainedSandwich(test, a): test[a]['2c'] = True test[a]['reasoning'] +=", "except: print ('There was an error reading line ' + str(lineCount) + '", "(test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): test[attemptNum]['firstSandwich']", "== True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): test[attemptNum]['firstSandwich'] = True test[attemptNum]['perservative'] = True", "def continuePreviousPresTo(test, attemptNum): if attemptNum > 0: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['currentPerservativeTo'] test[attemptNum]['reasoning'] += 'Principle", "2c doesn't apply if not isSandwiched(test, x): return False x -= 1 #", "(str(attemptNum) + ' Sandwiched Before by attempt ' + str(x)) break x -=", ": False, # for self perserverations 'rule_3_3' : False, }) except: print ('There", "8. Check if the sandwiched ambiguous answers are the first ones isFirstSandwich(test, attempt['attemptNum'])", "x, \" principle set to \", match) x+=1 def analyzeTest(fullpath, testNum, classNum): test", "# the rule was not established this attempt (on the first set). #", "x.right_padding_width = 1 x.field_names = ['#', \"Match\", \"Matched\", 'Pres-To', 'Pers', \"2b\", '2c', '3.1',", "# to something other than the current principle matches = getMatches(test, a) if", "and then loop again checkUnambiguousPerserveration(test, attempt['attemptNum']) for attempt in test: # 7. Now", "# If any of the preceeding attempts before the \"bread\" aren't also #", "False x -= 1 # Next we check forwards. y = attemptNum +", "# Make sure it's an error match = matches[0] # If we get", "if a['currentPerservativeTo'] != prevPrin: prin = a['currentPerservativeTo'] prevPrin = prin else: prin =", "the first set 'rule_3_1' : False, # These are to show matches for", "for attempt in test: # 8. Check if the sandwiched ambiguous answers are", "voor Wyko\\raw\" # Variables which contain the column numbers, used for readability SUBJECT", "set of rules for attempt in test: # 1. Set the principle the", "= [] for k, v in test[a]['stimulus'].items(): if test[a]['response'][k] == v: matches.append(k) return", "else: prin = '' if a['correct']: corr = '+ ' else: corr =", "first set. if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False and test[attemptNum]['currentPerservativeTo'] is", "one on attempt ', attemptNum) # print (test[attemptNum]) return True def checkChainedSandwich(test, a):", "response = '' if a['stimulus']['color'] == a['response']['color']: response += 'C* ' else: response", "'Match', \"Response\", 'Correct', 'Pres-To', 'Perserverative', 'Ambiguous', \"2b (1st Sandwich)\", '2c (Chained Sandwich)', '3.1", "number of ways the response matches the answer for k, v in test[attemptNum]['stimulus'].items():", "+= ' - Attempt is unambiguously perservative due to matching the current principle", "know this for every rule before we can go on to the more", "then we know the attempt is a candidate for the first indicator. #", "csvfile: cw = csv.writer(csvfile) cw.writerow(['#', 'Match', \"Response\", 'Correct', 'Pres-To', 'Perserverative', 'Ambiguous', \"2b (1st", "Marking perservative.' return True x-=1 def isChainedSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return", "is the number of ways the response matches the answer for k, v", "0 for line in lines: # Split the test report into an array", "sw= '+' else: sw = '' if a['2c']: chain = '+' else: chain", "this is an unambiguous error # to something other than the current principle", "test[attemptNum]['correct'] = False def isCorrect(test, a): # Determine if a response matches the", "= '' if a['currentPerservativeTo'] != prevPrin: prin = a['currentPerservativeTo'] prevPrin = prin else:", "1 x.field_names = ['#', \"Match\", \"Matched\", 'Pres-To', 'Pers', \"2b\", '2c', '3.1', '3.2', '3.3']", ": False, # Will change to true if the principle changed this attempt", "x = PrettyTable() # x.padding_width = 10 x.left_padding_width = 1 x.right_padding_width = 1", "and class number from the directory names p = path.split('\\\\') classNum = p[len(p)-1]", "True else: test[a]['2c'] = False if ( test[a]['sandwiched'] and 'NOT perservative per 2c'", "set was changed.' return True def checkAnswer(test, attemptNum): # Determine how ambiguous the", "Check if the attempt had an unambiguous incorrect answer. # If so, set", "for self perserverations 'rule_3_3' : False, }) except: print ('There was an error", "else '', ]) prevMatch = a['match'] print(x.get_string(title= str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+", "- Attempt has a response (' + test[attemptNum]['response'][pers] + ') which matches the", "if the response matches the stimulus on the current Perserveration principle. # This", "the perservative-to rule, AND # the rule was not established this attempt (on", "that is currently in # > effect (in our example, Color as defined", "results # The following are all boolean 'correct' : False, 'perservative' : False,", "+= ' - Principle was established as ' + k + ' from", "responses between the first and third unambiguous response must # match this sorting", "None, # Stores the currently active Pres-To Principle 'reasoning' : '', # Contains", "' - Attempt is a first sandwich, matching 2a and 2b. Marking perservative.'", "if a['stimulus']['color'] == a['response']['color']: response += 'C* ' else: response += 'C '", "test[a]['reasoning'] ): test[a]['reasoning'] += ' - Sandwiched attempt is NOT perservative per 2c'", "True else: return False def isSandwiched(test, attemptNum): # It has to have a", "test[attemptNum]['ambiguous'] == False and test[attemptNum]['currentPerservativeTo'] is not None and test[attemptNum]['set1PrincipleEstablished'] == False and", ": False, 'ambiguous' : False, 'sandwiched' : False, 'firstSandwich' : False, 'set1PrincipleEstablished' :", "= os.path.join(path, filename) # Get the filename for each file # Get the", "test number and class number from the directory names p = path.split('\\\\') classNum", "this is not the first set if test[attemptNum]['set'] != 1: return None #", "an unambiguous error # to something other than the current principle matches =", "indicator. # Let's look ahead for more indicators! x = a unambiguousMatches =", "and a['ambiguous']: pers = 'A-Pers' elif a['perservative']: pers = 'U-Pers' else: pers =", "attempt ' + str(y)) break y += 1 if sandwichAfter and sandwichBefore: #Mark", "+= 'Principle is none due to start of test.' return None def checkNewSet(test,", "= 0 for line in lines: # Split the test report into an", "else: response += 'F ' if a['stimulus']['number'] == a['response']['number']: response += 'N* '", "in test: # 7. Now we start looking for ambiguous perserverations. Here we", "response matches the answer for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v:", "last attempt.The current # principle will be the same as the last attempt,", "attempts. Maybe we also need to have the category changer run after this?", "the second response (not # including the second response) as unscorable x =", "if the attempt had an unambiguous incorrect answer. Skip the answer # in", "True # If the client perserverated to the Other category, Principle isn't set.", "= unambiguousMatches[1] while (x < len(test) and test[x]['set'] == test[unambiguousMatches[1]]['set']): test[x]['currentPerservativeTo'] = match", "True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If any of the preceeding", "test[attemptNum]['set']: return False # Check to see if we found the bread if", "isCorrect(test, x): continue # Make sure it's an error if test[x]['currentPerservativeTo'] in tempMatches:", "): test[a]['reasoning'] += ' - Sandwiched attempt is NOT perservative per 2c' return", "test[attemptNum]['currentPerservativeTo'] is None: return False pers = test[attemptNum]['currentPerservativeTo'] # Check to see if", "'+' if a['perservative'] else '', '+' if a['ambiguous'] else '', sw, chain, 'X'", "attemptNum): # The very first attempt will never have a Principle if attemptNum", "the potential principle is matched in all subsequent attempts # This covers the", "the response matches the answer for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] ==", "!= prevPrin: prin = a['currentPerservativeTo'] prevPrin = prin else: prin = '' if", "False if isCorrect(test, a): return False # Make sure it's an error match", "+ pers + ')' return True else: return False def getMatches(test, a): matches", "# Check if the attempt had an unambiguous incorrect answer. # If so,", "test: # 6. If this was an unambiguous error matching the perservative-to rule,", "perserverations. Here we check the # \"sandwich rule.\" isSandwiched(test, attempt['attemptNum']) for attempt in", "this sorting principle. # # 3. The new principle becomes active to register", "established as ' + k + ' from first unambiguous error.' return True", "error if test[x]['currentPerservativeTo'] in tempMatches: continue # Not currently pers # It's a", "!= 1: continue # Ensure it is an unambiguous result if isCorrect(test, x):", "was sandwiched by an unambiguous response for the same principle x = attemptNum", "corr + response, a['currentPerservativeTo'], #prin, pers, sw, chain, 'X' if a['rule_3_1'] else '',", "= attemptNum + 1 while y < len(test): if test[y]['set'] != test[attemptNum]['set']: return", "sandwiched' in test[attemptNum]['reasoning']: test[attemptNum]['reasoning'] += ' - Attempt is not sandwiched.' return False", "a set of rules for attempt in test: # 1. Set the principle", "populated and analyzed test object # printTest(test) saveResults(test) return test # Iterate through", "First, we check to see if this is an unambiguous error # to", "print (test[x]) # print (test[attemptNum]) # print (test[y]) # wait = input('') return", "attempt[MATCH], 'stimulus' : splitStim(attempt[STIMULUS]), 'response' : splitStim(attempt[RESPONSE]), 'testNum' : testNum, '2c' : '',", "return False x -= 1 # Next we check forwards. y = attemptNum", "if it hasn't already been done if not test[attemptNum]['sandwiched']: test[attemptNum]['reasoning'] += ' -", "is \"sandwiched\" between ' + str(x) + ' and ' + str(y) test[attemptNum]['sandwiched']", "- Attempt is not sandwiched.' return False def isFirstSandwich(test, attemptNum): if not isSandwiched(test,", "some error handling because the text files aren't always clean. try: attempt =", "matchQuotient += 1 # Mark whether the attempt is ambiguous if matchQuotient >", "unambiguousMatches.append(test[x]['attemptNum']) if len(unambiguousMatches) == 3: break if len(unambiguousMatches) != 3: return False #", "+ t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv').st_size == 0: cw.writerow(['Class', 'Subject', 'Sets", "more complicated # tests, so we finish the loop this way and then", "else '', sw, chain, 'X' if a['rule_3_1'] else '', 'X' if a['rule_3_2'] else", "'Non-Perserverative', 'Non-Perserverative Errors', 'Perserverative', 'Trials', '% Perserverative']) cw.writerow([ t[0]['classNum'], t[0]['subject'], totalSetsAttempted, totalCorrect, totalError,", "path == PATH: continue # Skip the root for filename in files: if", "3 unambiguous errors to a sorting principle # which is neither correct nor", "'X' if a['rule_3_3'] else '', ]) prevMatch = a['match'] print(x.get_string(title= str(test[0]['classNum']) + ',", "current # principle will be the same as the last attempt, unless #", "contains the tests PATH = os.getcwd() # r\"C:\\Users\\wyko.terhaar\\Downloads\\Map voor Wyko\\raw\" # Variables which", "aren't also # sandwiches, then 2c doesn't apply if not isSandwiched(test, x): return", "the test report into an array of Dicts # Added some error handling", "False # Next we check forwards. y = attemptNum + 1 sandwichAfter =", "if we just moved into a new set, and adjust the principle accordingly", "PrettyTable # The top level folder which contains the tests PATH = os.getcwd()", "= path.split('\\\\') classNum = p[len(p)-1] testNum = p[len(p)-2] allTests.append(analyzeTest(fullpath, testNum, classNum)) for t", "test: # 7. Now we start looking for ambiguous perserverations. Here we check", "for filename in files: if '.py' in filename: continue # Skip any python", "perserverative principle if len(tempMatches) != 1: continue # Ensure it is an unambiguous", "for a in t: if a['correct']: totalCorrect +=1 if not a['correct']: totalError +=1", "AND # the rule was not established this attempt (on the first set).", "'% Perserverative']) cw.writerow([ t[0]['classNum'], t[0]['subject'], totalSetsAttempted, totalCorrect, totalError, totalNonPerserverative, totalNonPerserverativeErrors, totalPerserverative, totalTrials, str(round((totalPerserverative", "the sandwiched ambiguous answers are the first ones isFirstSandwich(test, attempt['attemptNum']) for attempt in", "test[attemptNum]['firstSandwich'] = True test[attemptNum]['perservative'] = True test[attemptNum]['reasoning'] += ' - Attempt is a", "fullpath = os.path.join(path, filename) # Get the filename for each file # Get", "next set change, to the new principle x = unambiguousMatches[1] while (x <", "test[unambiguousMatches[2]]['rule_3_3'] = True test[unambiguousMatches[2]]['reasoning'] += ' - Rule 3: Final unambiguous self-perserveration' #", "to true if the principle changed this attempt in the first set 'rule_3_1'", "category, Principle isn't set. test[attemptNum]['reasoning'] += ' - Client perserverated to Other category.", "+ ' due to self-perserveration' # print(\"Test \", x, \" principle set to", "False # if test[x]['sandwiched']: return False if (test[x]['ambiguous'] == False and test[x]['perservative'] ==", "else: response += 'C ' if a['stimulus']['form'] == a['response']['form']: response += 'F* '", "print(str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']), '\\n', unambiguousMatches, '\\n')", "attempt ' + str(test[unambiguousMatches[0]]['attemptNum']) test[unambiguousMatches[2]]['rule_3_3'] = True test[unambiguousMatches[2]]['reasoning'] += ' - Rule 3:", "!= test[attemptNum]['set']: return False # Check to see if we found the bread", "# It's a match! unambiguousMatches.append(test[x]['attemptNum']) if len(unambiguousMatches) == 3: break if len(unambiguousMatches) !=", "as csvfile: cw = csv.writer(csvfile) if os.stat('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum']", "def analyzeTest(fullpath, testNum, classNum): test = [] # Open the file and read", "not containsPrincipleMatch(test, attemptNum): return False # It has to be ambiguous to be", "+ '.csv', 'w', newline='') as csvfile: cw = csv.writer(csvfile) cw.writerow(['#', 'Match', \"Response\", 'Correct',", "printTest(test): x = PrettyTable() # x.padding_width = 10 x.left_padding_width = 1 x.right_padding_width =", "previous sorting category) # False if not principle has been set yet. if", "as f: lines = f.readlines() # Iterate through the test and format it", "5. Heaton's rule 3: Find self-made perserverations checkSelfPerserveration(test, attempt['attemptNum']) for attempt in test:", "if len(matches) != 1: return False # One match for an unambiguous result", "for Heaton's rule 3 'rule_3_2' : False, # for self perserverations 'rule_3_3' :", "Principle if attemptNum == 0: return None if test[attemptNum]['set'] != test[attemptNum-1]['set']: test[attemptNum]['currentPerservativeTo'] =", "'' prevPrin = '' for a in test: response = '' if a['stimulus']['color']", "by attempt ' + str(x)) break x -= 1 if sandwichBefore == False:", "x > 0: if test[x]['set'] != test[attemptNum]['set']: return False if isSandwiched(test, x): return", "attemptNum): # Helper function which satisfies Heaton rule 2a: # > The ambiguous", "number from the directory names p = path.split('\\\\') classNum = p[len(p)-1] testNum =", "# Ensure it is an unambiguous result if isCorrect(test, x): continue # Make", "a['stimulus']['form'] == a['response']['form']: response += 'F* ' else: response += 'F ' if", "is NOT perservative per 2c' return False def checkSelfPerserveration(test, a): # 1. The", "= True else: test[attemptNum]['correct'] = False def isCorrect(test, a): # Determine if a", "just moved into a new set, and adjust the principle accordingly checkNewSet(test, attempt['attemptNum'])", "self-made perserverations checkSelfPerserveration(test, attempt['attemptNum']) for attempt in test: # 6. If this was", "second unambiguous error. # First, we check to see if this is an", "match = matches[0] # If we get here, then we know the attempt", "a['correct']: totalCorrect +=1 if not a['correct']: totalError +=1 totalSetsAttempted = a['set'] # Will", "and nothing else.' test[attemptNum]['perservative'] = True return True else: return False def isSandwiched(test,", "principle is matched in all subsequent attempts # This covers the intermediate results", "handling because the text files aren't always clean. try: attempt = line.split() test.append({", "len(test)-1: x+=1 # Make sure the potential principle is matched in all subsequent", "if sandwichAfter and sandwichBefore: #Mark the sandwich if it hasn't already been done", "fully populated and analyzed test object # printTest(test) saveResults(test) return test # Iterate", "# Next we check forwards. y = attemptNum + 1 while y <", "set). # We have to know this for every rule before we can", "a['perservative']: totalNonPerserverative +=1 if (not a['perservative'] and not a['correct']): totalNonPerserverativeErrors +=1 totalTrials+=1 with", "if test[attemptNum]['currentPerservativeTo'] is None: return False pers = test[attemptNum]['currentPerservativeTo'] # Check to see", "Wyko\\raw\" # Variables which contain the column numbers, used for readability SUBJECT =", "= getMatches(test, a) if len(matches) != 1: return False # One match for", "it for analysis. Skip the headers. lines.pop(0) lineCount = 0 for line in", "return False x = attemptNum - 1 while x > 0: if test[x]['set']", "as the last attempt, unless # it changes in a subsequent rule. continuePreviousPresTo(test,", "the currently active Pres-To Principle 'reasoning' : '', # Contains plaintext reasoning to", "as last attempt.The current # principle will be the same as the last", "a['response']['form']: response += 'F* ' else: response += 'F ' if a['stimulus']['number'] ==", "to matching the current principle and nothing else.' test[attemptNum]['perservative'] = True return True", "str(test[0]['testNum'])+ ', ' + str(test[0]['subject']), '\\n', unambiguousMatches, '\\n') test[unambiguousMatches[0]]['rule_3_1'] = True test[unambiguousMatches[0]]['reasoning'] +=", "for a in test: response = '' if a['stimulus']['color'] == a['response']['color']: response +=", "break if len(unambiguousMatches) != 3: return False # print(str(test[0]['classNum']) + ', ' +", "lineCount, 'subject' : int(attempt[SUBJECT]), 'set' : int(attempt[SET]), 'match' : attempt[MATCH], 'stimulus' : splitStim(attempt[STIMULUS]),", "this was an unambiguous error matching the perservative-to rule, AND # the rule", "with_statement import re, csv, os from prettytable import PrettyTable # The top level", "be considered for sandwich perseveration if not test[attemptNum]['ambiguous']: return False # First we", "not None: test[attemptNum]['reasoning'] += ' - Principle already set. No change for unambiguous", "test[attemptNum]['reasoning'] += ' - Attempt ' + str(attemptNum) + ' is \"sandwiched\" between", "for chained perserverations checkChainedSandwich(test, attempt['attemptNum']) # Return the fully populated and analyzed test", "a sorting principle # which is neither correct nor currently perserverative. # #", "return False # One match for an unambiguous result if test[a]['currentPerservativeTo'] in matches:", "x-=1 def isChainedSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return False if isFirstSandwich(test, attemptNum):", "self perserverations 'rule_3_3' : False, }) except: print ('There was an error reading", "the PATH variable allTests = [] for path, dirs, files in os.walk(PATH): if", "3: Find self-made perserverations checkSelfPerserveration(test, attempt['attemptNum']) for attempt in test: # 6. If", "checkUnambiguousPerserveration(test, attemptNum): # Check if the attempt had an unambiguous incorrect answer. Skip", "t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv', 'a', newline='') as csvfile: cw =", "filename: continue # Skip any generated analysis files # if not 'iqdat' in", "had an unambiguous incorrect answer. # If so, set the Principle whichever principle", "(Self-Perserveration)', '3.2', '3.3', 'Reasoning']) prevMatch = '' prevPrin = '' for a in", "yet. if test[attemptNum]['currentPerservativeTo'] is None: return False pers = test[attemptNum]['currentPerservativeTo'] # Check to", "to the more complicated # tests, so we finish the loop this way", "then loop again checkUnambiguousPerserveration(test, attempt['attemptNum']) for attempt in test: # 7. Now we", "= True test[unambiguousMatches[2]]['reasoning'] += ' - Rule 3: Final unambiguous self-perserveration' # Set", "PATH variable allTests = [] for path, dirs, files in os.walk(PATH): if path", "corr = '+ ' else: corr = ' ' if a['firstSandwich']: sw= '+'", "errors to the new, not currently # perserverative principle if len(tempMatches) != 1:", "# for self perserverations 'rule_3_3' : False, }) except: print ('There was an", "the rest, up to the next set change, to the new principle x", "level folder which contains the tests PATH = os.getcwd() # r\"C:\\Users\\wyko.terhaar\\Downloads\\Map voor Wyko\\raw\"", ": classNum, 'currentPerservativeTo' : None, # Stores the currently active Pres-To Principle 'reasoning'", "for each file # Get the test number and class number from the", "isn't set. test[attemptNum]['reasoning'] += ' - Client perserverated to Other category. No Principle", "in file: \\n' + fullpath) lineCount += 1 # First pass: Analyze the", "+ 1 sandwichAfter = False while y < len(test): if test[y]['set'] != test[attemptNum]['set']:", "+= ' - Attempt is a first sandwich, matching 2a and 2b. Marking", "[x,] # We need 3 to confirm self-perserveration # print{'Added first', x) while", "get here, then we know the attempt is a candidate for the first", "file in each folder in the PATH variable allTests = [] for path,", "a['match'] print(x.get_string(title= str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']) +", "f: lines = f.readlines() # Iterate through the test and format it for", "answer. Skip the answer # in which the Principle principle was established in", "to find if an ambiguous, potentially perservative # response was sandwiched by an", "sandwich if it hasn't already been done if not test[attemptNum]['sandwiched']: test[attemptNum]['reasoning'] += '", "this attempt in the first set 'rule_3_1' : False, # These are to", "number and class number from the directory names p = path.split('\\\\') classNum =", "False while y < len(test): if test[y]['set'] != test[attemptNum]['set']: break if (test[y]['ambiguous'] ==", "attemptNum) # print (test[attemptNum]) return True def checkChainedSandwich(test, a): if isChainedSandwich(test, a): test[a]['2c']", "correct nor currently perserverative. # # 2. All responses between the first and", "in filename: continue # Skip any generated analysis files # if not 'iqdat'", "Principle 'reasoning' : '', # Contains plaintext reasoning to help verify results #", "= re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)', stim) return { 'color' : x.group(1), 'form' : x.group(2), 'number' :", "'perservative' : False, 'ambiguous' : False, 'sandwiched' : False, 'firstSandwich' : False, 'set1PrincipleEstablished'", "test[x]['set'] != test[attemptNum]['set']: return False # Check to see if we found the", "considered for sandwich perseveration if not test[attemptNum]['ambiguous']: return False # First we look", "print (test[y]) # wait = input('') return True else: if not 'Attempt is", "(test[attemptNum]) return True def checkChainedSandwich(test, a): if isChainedSandwich(test, a): test[a]['2c'] = True test[a]['reasoning']", "if a['correct']: corr = '+ ' else: corr = ' ' if a['firstSandwich']:", "preceeding attempts before the \"bread\" aren't also # sandwiches, then 2c doesn't apply", "been done if not test[attemptNum]['sandwiched']: test[attemptNum]['reasoning'] += ' - Attempt ' + str(attemptNum)", "first unambiguous error.' return True # If the client perserverated to the Other", "= getMatches(test, x) if not match in tempMatches: return False # Now we", "a['match'] else: n = '' if a['currentPerservativeTo'] != prevPrin: prin = a['currentPerservativeTo'] prevPrin", "test[attemptNum]['reasoning'] += ' - Attempt is a first sandwich, matching 2a and 2b.", "return None def containsPrincipleMatch(test, attemptNum): # Helper function which satisfies Heaton rule 2a:", "continue previous pattern.' return True else: test[attemptNum]['reasoning'] += 'Principle is none due to", "Second unambiguous self-perserveration after attempt ' + str(test[unambiguousMatches[0]]['attemptNum']) test[unambiguousMatches[2]]['rule_3_3'] = True test[unambiguousMatches[2]]['reasoning'] +=", "true if the principle changed this attempt in the first set 'rule_3_1' :", "'3.2', '3.3', 'Reasoning']) prevMatch = '' prevPrin = '' for a in test:", "os.getcwd() # r\"C:\\Users\\wyko.terhaar\\Downloads\\Map voor Wyko\\raw\" # Variables which contain the column numbers, used", "True test[attemptNum]['reasoning'] += ' - Attempt is a first sandwich, matching 2a and", "totalError = 0 totalSetsAttempted = 0 totalNonPerserverative = 0 totalNonPerserverativeErrors = 0 totalPerserverative", "Rule 3: Second unambiguous self-perserveration after attempt ' + str(test[unambiguousMatches[0]]['attemptNum']) test[unambiguousMatches[2]]['rule_3_3'] = True", "= 0 totalSetsAttempted = 0 totalNonPerserverative = 0 totalNonPerserverativeErrors = 0 totalPerserverative =", "return False y += 1 # print('Holy shit, we found one on attempt", "a['currentPerservativeTo'] prevPrin = prin else: prin = '' if a['correct']: corr = '+", "and 'NOT perservative per 2c' not in test[a]['reasoning'] ): test[a]['reasoning'] += ' -", "['#', \"Match\", \"Matched\", 'Pres-To', 'Pers', \"2b\", '2c', '3.1', '3.2', '3.3'] prevMatch = ''", "test[attemptNum]['reasoning'] += ' - Attempt is unambiguously perservative due to matching the current", "if test[x]['currentPerservativeTo'] in tempMatches: continue # Not currently pers # It's a match!", "False if isFirstSandwich(test, attemptNum): return False x = attemptNum - 1 while x", "True else: return False def getMatches(test, a): matches = [] for k, v", "not test[attemptNum]['sandwiched']: test[attemptNum]['reasoning'] += ' - Attempt ' + str(attemptNum) + ' is", "client perserverated to the Other category, Principle isn't set. test[attemptNum]['reasoning'] += ' -", "error matching the perservative-to rule, AND # the rule was not established this", "the next set change, to the new principle x = unambiguousMatches[1] while (x", "the final set if a['perservative']: totalPerserverative +=1 if not a['perservative']: totalNonPerserverative +=1 if", "' due to self-perserveration' # print(\"Test \", x, \" principle set to \",", "a['response']['number']: response += 'N* ' else: response += 'N ' if a['perservative'] and", "'+' else: sw = '' if a['2c']: chain = '+' else: chain =", "# The following are all boolean 'correct' : False, 'perservative' : False, 'ambiguous'", "if not test[attemptNum]['ambiguous']: return False # First we look backwards to find if", "per 2c' return False def checkSelfPerserveration(test, a): # 1. The client must make", "' from first unambiguous error.' return True # If the client perserverated to", "before we can go on to the more complicated # tests, so we", "Check rule 2c for chained perserverations checkChainedSandwich(test, attempt['attemptNum']) # Return the fully populated", "False def checkFirstSetPers(test, attemptNum): # Break out if this is not the first", "attempt ', attemptNum) # print (test[attemptNum]) return True def checkChainedSandwich(test, a): if isChainedSandwich(test,", "generated analysis files # if not 'iqdat' in filename: continue fullpath = os.path.join(path,", "9. Check rule 2c for chained perserverations checkChainedSandwich(test, attempt['attemptNum']) # Return the fully", "prevMatch = '' prevPrin = '' for a in test: response = ''", "return False # It has to be ambiguous to be considered for sandwich", "to be considered perservative at all if not containsPrincipleMatch(test, attemptNum): return False #", "self-perserveration # print{'Added first', x) while x < len(test)-1: x+=1 # Make sure", "current Perserveration principle. # This would suggest that this response is perserverating if", "= 'U-Pers' else: pers = '' if a['match'] != prevMatch: n = a['match']", "perservative per 2c' test[a]['perservative'] = True return True else: test[a]['2c'] = False if", "matches = [] for k, v in test[a]['stimulus'].items(): if test[a]['response'][k] == v: matches.append(k)", "none due to start of test.' return None def checkNewSet(test, attemptNum): # The", "'Errors', 'Non-Perserverative', 'Non-Perserverative Errors', 'Perserverative', 'Trials', '% Perserverative']) cw.writerow([ t[0]['classNum'], t[0]['subject'], totalSetsAttempted, totalCorrect,", "the attempt is a candidate for the first indicator. # Let's look ahead", "perservative per 2c' not in test[a]['reasoning'] ): test[a]['reasoning'] += ' - Sandwiched attempt", "set, and adjust the principle accordingly checkNewSet(test, attempt['attemptNum']) # 3. Check if the", "# 8. Check if the sandwiched ambiguous answers are the first ones isFirstSandwich(test,", "candidate for the first indicator. # Let's look ahead for more indicators! x", "+ ' from first unambiguous error.' return True # If the client perserverated", "try: attempt = line.split() test.append({ 'file' : os.path.basename(fullpath), 'attemptNum' : lineCount, 'subject' :", "'', ]) prevMatch = a['match'] print(x.get_string(title= str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ',", "if test[a]['stimulus'][match] == test[a]['response'][match]: return True else: return False def checkFirstSetPers(test, attemptNum): #", "This is the number of ways the response matches the answer for k,", "attemptNum): return False # It has to be ambiguous to be considered for", "' + str(test[attemptNum]['currentPerservativeTo']) + ' (last set match clause) because set was changed.'", "must make 3 unambiguous errors to a sorting principle # which is neither", "# print (test[y]) # wait = input('') return True else: if not 'Attempt", "3: First unambiguous self-perserveration' test[unambiguousMatches[1]]['rule_3_2'] = True test[unambiguousMatches[1]]['reasoning'] += ' - Rule 3:", "'X' if a['rule_3_1'] else '', 'X' if a['rule_3_2'] else '', 'X' if a['rule_3_3']", "reading line ' + str(lineCount) + ' in file: \\n' + fullpath) lineCount", "isFirstSandwich(test, attemptNum): return False x = attemptNum - 1 while x > 0:", "for the last two unambiguous errors to the new, not currently # perserverative", "False, # for self perserverations 'rule_3_3' : False, }) except: print ('There was", "a response matches the stimulus on the match criteria match = test[a]['match'] if", "getMatches(test, a) if len(matches) != 1: return False # One match for an", "# Get the filename for each file # Get the test number and", "checkNewSet(test, attemptNum): # The very first attempt will never have a Principle if", "prevMatch = a['match'] print(x.get_string(title= str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ', ' +", "if a['2c']: chain = '+' else: chain = '' x.add_row([a['attemptNum'], a['match'], #n, corr", "the tests PATH = os.getcwd() # r\"C:\\Users\\wyko.terhaar\\Downloads\\Map voor Wyko\\raw\" # Variables which contain", "return None def checkNewSet(test, attemptNum): # The very first attempt will never have", "as defined by # > the previous sorting category) # False if not", "# incorrect answer determines the first-set's Principle checkFirstSetPers(test, attempt['attemptNum']) for attempt in test:", "# We have to know this for every rule before we can go", "1 # First pass: Analyze the data with a set of rules for", "' if a['stimulus']['form'] == a['response']['form']: response += 'F* ' else: response += 'F", "= PrettyTable() # x.padding_width = 10 x.left_padding_width = 1 x.right_padding_width = 1 x.field_names", "v in test[a]['stimulus'].items(): if test[a]['response'][k] == v: matches.append(k) return matches def checkUnambiguousPerserveration(test, attemptNum):", "+ str(test[attemptNum]['currentPerservativeTo']) + ' (last set match clause) because set was changed.' return", "\"Response\", 'Correct', 'Pres-To', 'Perserverative', 'Ambiguous', \"2b (1st Sandwich)\", '2c (Chained Sandwich)', '3.1 (Self-Perserveration)',", "Principle set.' return None def containsPrincipleMatch(test, attemptNum): # Helper function which satisfies Heaton", "+= 'F* ' else: response += 'F ' if a['stimulus']['number'] == a['response']['number']: response", "return test # Iterate through each file in each folder in the PATH", "register perserverations only # after the second unambiguous error. # First, we check", "potentially perservative # response was sandwiched by an unambiguous response for the same", "First we look backwards to find if an ambiguous, potentially perservative # response", "chain = '' x.add_row([a['attemptNum'], a['match'], #n, corr + response, a['currentPerservativeTo'], #prin, pers, sw,", "True # print (str(attemptNum) + ' Sandwiched Before by attempt ' + str(x))", "match = test[a]['match'] if test[a]['stimulus'][match] == test[a]['response'][match]: return True else: return False def", "splitStim(stim): x = re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)', stim) return { 'color' : x.group(1), 'form' : x.group(2),", "test[attemptNum-1]['match'] test[attemptNum]['reasoning'] += ' - Principle was set to ' + str(test[attemptNum]['currentPerservativeTo']) +", "return matches def checkUnambiguousPerserveration(test, attemptNum): # Check if the attempt had an unambiguous", "chain = '+' else: chain = '' x.add_row([a['attemptNum'], a['match'], #n, corr + response,", "x+=1 def analyzeTest(fullpath, testNum, classNum): test = [] # Open the file and", "from prettytable import PrettyTable # The top level folder which contains the tests", "prettytable import PrettyTable # The top level folder which contains the tests PATH", "+= ' - Attempt is chain sandwich perservative per 2c' test[a]['perservative'] = True", "else: chain = '' x.add_row([a['attemptNum'], a['match'], #n, corr + response, a['currentPerservativeTo'], #prin, pers,", "# Principle is not set for future attempts. Maybe we also need to", "str(x)) break x -= 1 if sandwichBefore == False: return False # Next", "= '+ ' else: corr = ' ' if a['firstSandwich']: sw= '+' else:", "if not principle has been set yet. if test[attemptNum]['currentPerservativeTo'] is None: return False", "= os.getcwd() # r\"C:\\Users\\wyko.terhaar\\Downloads\\Map voor Wyko\\raw\" # Variables which contain the column numbers,", "currently # perserverative principle if len(tempMatches) != 1: continue # Ensure it is", "test[attemptNum]['set']: break if (test[y]['ambiguous'] == False and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] ==", "test: # 1. Set the principle the same as last attempt.The current #", "def checkNewSet(test, attemptNum): # The very first attempt will never have a Principle", "and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): test[attemptNum]['firstSandwich'] = True test[attemptNum]['perservative']", "y < len(test): if test[y]['set'] != test[attemptNum]['set']: break if (test[y]['ambiguous'] == False and", "the second response) as unscorable x = unambiguousMatches[0] while x < unambiguousMatches[1]: test[x]['currentPerservativeTo']", "False def isFirstSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return False x = attemptNum", "= '' x.add_row([a['attemptNum'], a['match'], #n, corr + response, a['currentPerservativeTo'], #prin, pers, sw, chain,", "has been set yet. if test[attemptNum]['currentPerservativeTo'] is None: return False pers = test[attemptNum]['currentPerservativeTo']", "(test[y]) # wait = input('') return True else: if not 'Attempt is not", "True test[unambiguousMatches[2]]['reasoning'] += ' - Rule 3: Final unambiguous self-perserveration' # Set all", "== 0: cw.writerow(['Class', 'Subject', 'Sets Attempted', 'Correct', 'Errors', 'Non-Perserverative', 'Non-Perserverative Errors', 'Perserverative', 'Trials',", "# sandwiches, then 2c doesn't apply if not isSandwiched(test, y): return False y", "is not sandwiched.' return False def isFirstSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return", "'rule_3_2' : False, # for self perserverations 'rule_3_3' : False, }) except: print", "RESPONSE = 10 def saveResults(test): with open('ANALYSIS_' + test[0]['file'] + '.csv', 'w', newline='')", "doesn't apply if not isSandwiched(test, y): return False y += 1 # print('Holy", "y): return False y += 1 # print('Holy shit, we found one on", "test[attemptNum]['correct'] = True else: test[attemptNum]['correct'] = False def isCorrect(test, a): # Determine if", "3: break if len(unambiguousMatches) != 3: return False # print(str(test[0]['classNum']) + ', '", "The following are all boolean 'correct' : False, 'perservative' : False, 'ambiguous' :", "an array of Dicts # Added some error handling because the text files", "Check if the sandwiched ambiguous answers are the first ones isFirstSandwich(test, attempt['attemptNum']) for", "totalSetsAttempted, totalCorrect, totalError, totalNonPerserverative, totalNonPerserverativeErrors, totalPerserverative, totalTrials, str(round((totalPerserverative / totalTrials)*100, 2)) + '%',", "True def checkAnswer(test, attemptNum): # Determine how ambiguous the answer is matchQuotient =", "+ ', ' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']), '\\n', unambiguousMatches, '\\n') test[unambiguousMatches[0]]['rule_3_1']", "' + str(x) + ' and ' + str(y) test[attemptNum]['sandwiched'] = True #", "# It has to be ambiguous to be considered for sandwich perseveration if", "str(test[attemptNum]['currentPerservativeTo']) + ' (last set match clause) because set was changed.' return True", "3: Final unambiguous self-perserveration' # Set all responses from the first untill the", "Principle has not been determined (first set) then the first unambiguous # incorrect", "being the final set if a['perservative']: totalPerserverative +=1 if not a['perservative']: totalNonPerserverative +=1", "Added some error handling because the text files aren't always clean. try: attempt", "else: if not 'Attempt is not sandwiched' in test[attemptNum]['reasoning']: test[attemptNum]['reasoning'] += ' -", "Check to see if the response matches the stimulus on the current Perserveration", "Attempt is unambiguously perservative due to matching the current principle and nothing else.'", "\", match) x+=1 def analyzeTest(fullpath, testNum, classNum): test = [] # Open the", "example, Color as defined by # > the previous sorting category) # False", "test[y]['set'] != test[attemptNum]['set']: break if (test[y]['ambiguous'] == False and test[y]['perservative'] == True and", "attempt was an error checkAnswer(test, attempt['attemptNum']) # 4. If Principle has not been", "Pres-To Principle 'reasoning' : '', # Contains plaintext reasoning to help verify results", "= '' prevPrin = '' for a in test: response = '' if", "not currently # perserverative principle if len(tempMatches) != 1: continue # Ensure it", "Next we check forwards. y = attemptNum + 1 sandwichAfter = False while", "chain = '' cw.writerow([a['attemptNum'], a['match'], #n, response, '+' if a['correct'] else '', a['currentPerservativeTo'],", "set the Principle whichever principle the client matched if (test[attemptNum]['correct'] == False and", "principle has been set yet. if test[attemptNum]['currentPerservativeTo'] is None: return False pers =", "= a['match'] def printTest(test): x = PrettyTable() # x.padding_width = 10 x.left_padding_width =", "y += 1 # print('Holy shit, we found one on attempt ', attemptNum)", "the file and read it into memory with open (fullpath) as f: lines", "saveResults(test) return test # Iterate through each file in each folder in the", "in test[a]['stimulus'].items(): if test[a]['response'][k] == v: matches.append(k) return matches def checkUnambiguousPerserveration(test, attemptNum): #", "to have a principle match to be considered perservative at all if not", "2c doesn't apply if not isSandwiched(test, y): return False y += 1 #", "lines = f.readlines() # Iterate through the test and format it for analysis.", "a): matches = [] for k, v in test[a]['stimulus'].items(): if test[a]['response'][k] == v:", "attempt ' + str(y)) # print (test[x]) # print (test[attemptNum]) # print (test[y])", "not isSandwiched(test, attemptNum): return False if isFirstSandwich(test, attemptNum): return False x = attemptNum", "= 10 def saveResults(test): with open('ANALYSIS_' + test[0]['file'] + '.csv', 'w', newline='') as", "If this was an unambiguous error matching the perservative-to rule, AND # the", "file and read it into memory with open (fullpath) as f: lines =", "Sandwiched Before by attempt ' + str(x)) break x -= 1 if sandwichBefore", "look ahead for more indicators! x = a unambiguousMatches = [x,] # We", "\"bread\" aren't also # sandwiches, then 2c doesn't apply if not isSandwiched(test, y):", "for attempt in test: # 1. Set the principle the same as last", "'Sets Attempted', 'Correct', 'Errors', 'Non-Perserverative', 'Non-Perserverative Errors', 'Perserverative', 'Trials', '% Perserverative']) cw.writerow([ t[0]['classNum'],", "test[a]['response'][match]: return True else: return False def checkFirstSetPers(test, attemptNum): # Break out if", "')' return True else: return False def getMatches(test, a): matches = [] for", "- Attempt ' + str(attemptNum) + ' is \"sandwiched\" between ' + str(x)", "== False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichBefore =", "= True return True else: test[a]['2c'] = False if ( test[a]['sandwiched'] and 'NOT", "files in os.walk(PATH): if path == PATH: continue # Skip the root for", "checkFirstSetPers(test, attempt['attemptNum']) for attempt in test: # 5. Heaton's rule 3: Find self-made", "test[attemptNum]['reasoning'] += ' - Principle was established as ' + k + '", "a['perservative'] and a['ambiguous']: pers = 'A-Pers' elif a['perservative']: pers = 'U-Pers' else: pers", "be the same as the last attempt, unless # it changes in a", "the bread if (test[y]['ambiguous'] == False and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] ==", "(test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False and test[attemptNum]['currentPerservativeTo'] is not None and", "between the first and third unambiguous response must # match this sorting principle.", "\", x, \" principle set to \", match) x+=1 def analyzeTest(fullpath, testNum, classNum):", "+= ' - Sandwiched attempt is NOT perservative per 2c' return False def", "a['rule_3_1'] else '', 'X' if a['rule_3_2'] else '', 'X' if a['rule_3_3'] else '',", "continue # Skip any python files if 'ANALYSIS' in filename: continue # Skip", "= 3 MATCH = 5 SET = 6 STIMULUS = 9 RESPONSE =", "category) # False if not principle has been set yet. if test[attemptNum]['currentPerservativeTo'] is", "principle match to be considered perservative at all if not containsPrincipleMatch(test, attemptNum): return", "= True # print (str(attemptNum) + ' Sandwiched After by attempt ' +", "to ' + match + ' due to self-perserveration' # print(\"Test \", x,", "# 3. Check if the attempt was an error checkAnswer(test, attempt['attemptNum']) # 4.", "# > the previous sorting category) # False if not principle has been", "== test[unambiguousMatches[1]]['set']): test[x]['currentPerservativeTo'] = match test[x]['reasoning'] += ' - Rule 3: Principle set", ": splitStim(attempt[STIMULUS]), 'response' : splitStim(attempt[RESPONSE]), 'testNum' : testNum, '2c' : '', 'classNum' :", "3 to confirm self-perserveration # print{'Added first', x) while x < len(test)-1: x+=1", "sorting principle. # # 3. The new principle becomes active to register perserverations", "apply if not isSandwiched(test, y): return False y += 1 # print('Holy shit,", "'set1PrincipleEstablished' : False, # Will change to true if the principle changed this", "# Will end up being the final set if a['perservative']: totalPerserverative +=1 if", "not isSandwiched(test, y): return False y += 1 # print('Holy shit, we found", "by an unambiguous response for the same principle x = attemptNum - 1", "= True return True else: return False def isSandwiched(test, attemptNum): # It has", "# perserverative principle if len(tempMatches) != 1: continue # Ensure it is an", "so we finish the loop this way and then loop again checkUnambiguousPerserveration(test, attempt['attemptNum'])", "the first indicator. # Let's look ahead for more indicators! x = a", "test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichBefore = True # print (str(attemptNum) + ' Sandwiched", "is not None: test[attemptNum]['reasoning'] += ' - Principle already set. No change for", "# print (test[attemptNum]) return True def checkChainedSandwich(test, a): if isChainedSandwich(test, a): test[a]['2c'] =", "in test: # 1. Set the principle the same as last attempt.The current", "a['stimulus']['color'] == a['response']['color']: response += 'C* ' else: response += 'C ' if", "response (' + test[attemptNum]['response'][pers] + ') which matches the principle (' + pers", "): sandwichAfter = True # print (str(attemptNum) + ' Sandwiched After by attempt", "else: n = '' if a['currentPerservativeTo'] != prevPrin: prin = a['currentPerservativeTo'] prevPrin =", "# print(\"Test \", x, \" principle set to \", match) x+=1 def analyzeTest(fullpath,", "because set was changed.' return True def checkAnswer(test, attemptNum): # Determine how ambiguous", "pers = test[attemptNum]['currentPerservativeTo'] # Check to see if the response matches the stimulus", "to see if the response matches the stimulus on the current Perserveration principle.", "print (test[attemptNum]) # print (test[y]) # wait = input('') return True else: if", "first set if test[attemptNum]['set'] != 1: return None # Break out if this", "', ' + str(test[0]['subject']), '\\n', unambiguousMatches, '\\n') test[unambiguousMatches[0]]['rule_3_1'] = True test[unambiguousMatches[0]]['reasoning'] += '", "test[attemptNum]['reasoning'] += ' - Attempt is not sandwiched.' return False def isFirstSandwich(test, attemptNum):", "tempMatches: return False # Now we look for the last two unambiguous errors", "sandwiches, then 2c doesn't apply if not isSandwiched(test, x): return False x -=", "'' if a['stimulus']['color'] == a['response']['color']: response += 'C* ' else: response += 'C", "- Client perserverated to Other category. No Principle set.' return None def containsPrincipleMatch(test,", "# Check to see if the response matches the stimulus on the current", "False and containsPrincipleMatch(test, attemptNum) ): test[attemptNum]['reasoning'] += ' - Attempt is unambiguously perservative", "ambiguous, potentially perservative # response was sandwiched by an unambiguous response for the", "the client matched if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False): for k,", "cw.writerow([a['attemptNum'], a['match'], #n, response, '+' if a['correct'] else '', a['currentPerservativeTo'], #prin, '+' if", "Principle principle was established in the first set. if (test[attemptNum]['correct'] == False and", "Check if the attempt was an error checkAnswer(test, attempt['attemptNum']) # 4. If Principle", "how ambiguous the answer is matchQuotient = 0 # This is the number", "== False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break #", "# print (str(attemptNum) + ' Sandwiched Before by attempt ' + str(x)) break", "numbers, used for readability SUBJECT = 3 MATCH = 5 SET = 6", "p[len(p)-2] allTests.append(analyzeTest(fullpath, testNum, classNum)) for t in allTests: totalCorrect = 0 totalError =", "str(x) + ' and ' + str(y) test[attemptNum]['sandwiched'] = True # print (str(attemptNum)", "classNum)) for t in allTests: totalCorrect = 0 totalError = 0 totalSetsAttempted =", "was an error reading line ' + str(lineCount) + ' in file: \\n'", "# Set all responses from the first untill the second response (not #", "+ str(attemptNum) + ' is \"sandwiched\" between ' + str(x) + ' and", "{ 'color' : x.group(1), 'form' : x.group(2), 'number' : x.group(3) } def continuePreviousPresTo(test,", "to see if this is an unambiguous error # to something other than", "+ test[0]['file'] + '.csv', 'w', newline='') as csvfile: cw = csv.writer(csvfile) cw.writerow(['#', 'Match',", "attemptNum): # Break out if this is not the first set if test[attemptNum]['set']", "= 'A-Pers' elif a['perservative']: pers = 'U-Pers' else: pers = '' if a['match']", "if test[x]['set'] != test[attemptNum]['set']: return False if isSandwiched(test, x): return False # if", "through the test and format it for analysis. Skip the headers. lines.pop(0) lineCount", "= '' if a['2c']: chain = '+' else: chain = '' x.add_row([a['attemptNum'], a['match'],", "= False if ( test[a]['sandwiched'] and 'NOT perservative per 2c' not in test[a]['reasoning']", "set. if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False and test[attemptNum]['currentPerservativeTo'] is not", "# Added some error handling because the text files aren't always clean. try:", "loop this way and then loop again checkUnambiguousPerserveration(test, attempt['attemptNum']) for attempt in test:", "if a['match'] != prevMatch: n = a['match'] else: n = '' if a['currentPerservativeTo']", "while x < unambiguousMatches[1]: test[x]['currentPerservativeTo'] = None test[x]['reasoning'] += ' - Rule 3:", "= 0 # This is the number of ways the response matches the", "a): test[a]['2c'] = True test[a]['reasoning'] += ' - Attempt is chain sandwich perservative", "tempMatches = getMatches(test, x) if not match in tempMatches: return False # Now", "test[x]['reasoning'] += ' - Rule 3: Principle set to ' + match +", "== True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichBefore = True # print (str(attemptNum)", "continue # Make sure it's an error if test[x]['currentPerservativeTo'] in tempMatches: continue #", "else '', '+' if a['ambiguous'] else '', sw, chain, 'X' if a['rule_3_1'] else", "if test[attemptNum]['correct'] == True: return None if test[attemptNum]['currentPerservativeTo'] is not None: test[attemptNum]['reasoning'] +=", "##################################### # Set all the rest, up to the next set change, to", "< len(test): if test[y]['set'] != test[attemptNum]['set']: return False # Check to see if", "out if this is not the first set if test[attemptNum]['set'] != 1: return", "attemptNum): test[attemptNum]['correct'] = True else: test[attemptNum]['correct'] = False def isCorrect(test, a): # Determine", "= 0 totalTrials = 0 for a in t: if a['correct']: totalCorrect +=1", "attempt = line.split() test.append({ 'file' : os.path.basename(fullpath), 'attemptNum' : lineCount, 'subject' : int(attempt[SUBJECT]),", ": splitStim(attempt[RESPONSE]), 'testNum' : testNum, '2c' : '', 'classNum' : classNum, 'currentPerservativeTo' :", "# If so, set the Principle whichever principle the client matched if (test[attemptNum]['correct']", "): test[attemptNum]['firstSandwich'] = True test[attemptNum]['perservative'] = True test[attemptNum]['reasoning'] += ' - Attempt is", "the bread if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] ==", "matches the principle (' + pers + ')' return True else: return False", "and adjust the principle accordingly checkNewSet(test, attempt['attemptNum']) # 3. Check if the attempt", "matching the current principle and nothing else.' test[attemptNum]['perservative'] = True return True else:", "was changed.' return True def checkAnswer(test, attemptNum): # Determine how ambiguous the answer", "' + str(y)) # print (test[x]) # print (test[attemptNum]) # print (test[y]) #", "to the new, not currently # perserverative principle if len(tempMatches) != 1: continue", "Get the filename for each file # Get the test number and class", "totalNonPerserverative +=1 if (not a['perservative'] and not a['correct']): totalNonPerserverativeErrors +=1 totalTrials+=1 with open('SUMMARY_'", "and containsPrincipleMatch(test, attemptNum) ): test[attemptNum]['reasoning'] += ' - Attempt is unambiguously perservative due", "checkAnswer(test, attemptNum): # Determine how ambiguous the answer is matchQuotient = 0 #", "== test[attemptNum]['currentPerservativeTo'] ): test[attemptNum]['firstSandwich'] = True test[attemptNum]['perservative'] = True test[attemptNum]['reasoning'] += ' -", "prevPrin = prin else: prin = '' if a['correct']: corr = '+ '", "Make sure it's an error if test[x]['currentPerservativeTo'] in tempMatches: continue # Not currently", "#prin, '+' if a['perservative'] else '', '+' if a['ambiguous'] else '', sw, chain,", "' + str(y) test[attemptNum]['sandwiched'] = True # print (str(attemptNum) + ' Sandwiched Before", "in test[a]['reasoning'] ): test[a]['reasoning'] += ' - Sandwiched attempt is NOT perservative per", "in t: if a['correct']: totalCorrect +=1 if not a['correct']: totalError +=1 totalSetsAttempted =", "== True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If any of the", "v: matches.append(k) return matches def checkUnambiguousPerserveration(test, attemptNum): # Check if the attempt had", "(last set match clause) because set was changed.' return True def checkAnswer(test, attemptNum):", "True test[unambiguousMatches[1]]['reasoning'] += ' - Rule 3: Second unambiguous self-perserveration after attempt '", "'+' else: chain = '' cw.writerow([a['attemptNum'], a['match'], #n, response, '+' if a['correct'] else", "+ ' Sandwiched After by attempt ' + str(y)) # print (test[x]) #", "responses from the first untill the second response (not # including the second", "'3.3'] prevMatch = '' prevPrin = '' for a in test: response =", "test[attemptNum]['set']: break if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] ==", "Principle was established as ' + k + ' from first unambiguous error.'", "t[0]['classNum'] + '.csv', 'a', newline='') as csvfile: cw = csv.writer(csvfile) if os.stat('SUMMARY_' +", "if test[x]['set'] != test[attemptNum]['set']: break if (test[x]['ambiguous'] == False and test[x]['perservative'] == True", "return False # Make sure it's an error match = matches[0] # If", "test[attemptNum]['currentPerservativeTo'] = k test[attemptNum]['set1PrincipleEstablished'] = True test[attemptNum]['reasoning'] += ' - Principle was established", "'X' if a['rule_3_2'] else '', 'X' if a['rule_3_3'] else '', ]) prevMatch =", "# Return the fully populated and analyzed test object # printTest(test) saveResults(test) return", "'\\n', unambiguousMatches, '\\n') test[unambiguousMatches[0]]['rule_3_1'] = True test[unambiguousMatches[0]]['reasoning'] += ' - Rule 3: First", "if '.py' in filename: continue # Skip any python files if 'ANALYSIS' in", "totalPerserverative = 0 totalTrials = 0 for a in t: if a['correct']: totalCorrect", "answer for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: matchQuotient += 1", "' ' if a['firstSandwich']: sw= '+' else: sw = '' if a['2c']: chain", "+ str(lineCount) + ' in file: \\n' + fullpath) lineCount += 1 #", "prin = a['currentPerservativeTo'] prevPrin = prin else: prin = '' if a['correct']: corr", "testNum, '2c' : '', 'classNum' : classNum, 'currentPerservativeTo' : None, # Stores the", "# Iterate through the test and format it for analysis. Skip the headers.", "not 'Attempt is not sandwiched' in test[attemptNum]['reasoning']: test[attemptNum]['reasoning'] += ' - Attempt is", "'U-Pers' else: pers = '' if a['match'] != prevMatch: n = a['match'] else:", "Iterate through each file in each folder in the PATH variable allTests =", "1: return None # Break out if this was not an incorrect answer", "set.' return None def containsPrincipleMatch(test, attemptNum): # Helper function which satisfies Heaton rule", "attempts before the \"bread\" aren't also # sandwiches, then 2c doesn't apply if", "a['response']['color']: response += 'C* ' else: response += 'C ' if a['stimulus']['form'] ==", "sandwich perseveration if not test[attemptNum]['ambiguous']: return False # First we look backwards to", "# print (test[x]) x+=1 ################################# # Principle is not set for future attempts.", "# Determine if a response matches the stimulus on the match criteria match", "os.stat('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv').st_size == 0: cw.writerow(['Class', 'Subject',", "f.readlines() # Iterate through the test and format it for analysis. Skip the", "a): # Determine if a response matches the stimulus on the match criteria", "test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichAfter = True # print", "#n, response, '+' if a['correct'] else '', a['currentPerservativeTo'], #prin, '+' if a['perservative'] else", "else.' test[attemptNum]['perservative'] = True return True else: return False def isSandwiched(test, attemptNum): #", "k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: test[attemptNum]['currentPerservativeTo'] = k test[attemptNum]['set1PrincipleEstablished'] =", "then 2c doesn't apply if not isSandwiched(test, x): return False x -= 1", "ones isFirstSandwich(test, attempt['attemptNum']) for attempt in test: # 9. Check rule 2c for", "must # match this sorting principle. # # 3. The new principle becomes", "answer is matchQuotient = 0 # This is the number of ways the", "1 while x > 0: if test[x]['set'] != test[attemptNum]['set']: return False if isSandwiched(test,", "perservative per 2c' return False def checkSelfPerserveration(test, a): # 1. The client must", "isSandwiched(test, attempt['attemptNum']) for attempt in test: # 8. Check if the sandwiched ambiguous", "= '' if a['correct']: corr = '+ ' else: corr = ' '", "an error checkAnswer(test, attempt['attemptNum']) # 4. If Principle has not been determined (first", "v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: matchQuotient += 1 # Mark whether", "aren't also # sandwiches, then 2c doesn't apply if not isSandwiched(test, y): return", "never have a Principle if attemptNum == 0: return None if test[attemptNum]['set'] !=", "second response (not # including the second response) as unscorable x = unambiguousMatches[0]", ": lineCount, 'subject' : int(attempt[SUBJECT]), 'set' : int(attempt[SET]), 'match' : attempt[MATCH], 'stimulus' :", "principle the same as last attempt.The current # principle will be the same", "'a', newline='') as csvfile: cw = csv.writer(csvfile) if os.stat('SUMMARY_' + t[0]['testNum'] + '_'", "client matched if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False): for k, v", "response (not # including the second response) as unscorable x = unambiguousMatches[0] while", "first set). # We have to know this for every rule before we", "response += 'N* ' else: response += 'N ' if a['perservative'] and a['ambiguous']:", "]) prevMatch = a['match'] print(x.get_string(title= str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ', '", "' + str(test[unambiguousMatches[0]]['attemptNum']) test[unambiguousMatches[2]]['rule_3_3'] = True test[unambiguousMatches[2]]['reasoning'] += ' - Rule 3: Final", "second responses' # print (test[x]) x+=1 ################################# # Principle is not set for", "return False def isFirstSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return False x =", "from the directory names p = path.split('\\\\') classNum = p[len(p)-1] testNum = p[len(p)-2]", "in the first set. if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False and", "if not isSandwiched(test, x): return False x -= 1 # Next we check", "match for an unambiguous result if test[a]['currentPerservativeTo'] in matches: return False if isCorrect(test,", "every rule before we can go on to the more complicated # tests,", "not principle has been set yet. if test[attemptNum]['currentPerservativeTo'] is None: return False pers", "The very first attempt will never have a Principle if attemptNum == 0:", "the # > perseverated-to principle that is currently in # > effect (in", "unambiguous error # to something other than the current principle matches = getMatches(test,", "second response) as unscorable x = unambiguousMatches[0] while x < unambiguousMatches[1]: test[x]['currentPerservativeTo'] =", "test[attemptNum]['ambiguous'] == False): for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: test[attemptNum]['currentPerservativeTo']", "pass: Analyze the data with a set of rules for attempt in test:", "root for filename in files: if '.py' in filename: continue # Skip any", "if an ambiguous, potentially perservative # response was sandwiched by an unambiguous response", "def isSandwiched(test, attemptNum): # It has to have a principle match to be", "the Other category, Principle isn't set. test[attemptNum]['reasoning'] += ' - Client perserverated to", "match! unambiguousMatches.append(test[x]['attemptNum']) if len(unambiguousMatches) == 3: break if len(unambiguousMatches) != 3: return False", "} def continuePreviousPresTo(test, attemptNum): if attemptNum > 0: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['currentPerservativeTo'] test[attemptNum]['reasoning'] +=", "#Mark the sandwich if it hasn't already been done if not test[attemptNum]['sandwiched']: test[attemptNum]['reasoning']", "True test[attemptNum]['reasoning'] += ' - Principle was established as ' + k +", "= attemptNum - 1 sandwichBefore = False while x > 0: if test[x]['set']", "'Pres-To', 'Pers', \"2b\", '2c', '3.1', '3.2', '3.3'] prevMatch = '' prevPrin = ''", "True else: test[attemptNum]['correct'] = False def isCorrect(test, a): # Determine if a response", "+ str(x)) # print (str(attemptNum) + ' Sandwiched After by attempt ' +", "attempt is a candidate for the first indicator. # Let's look ahead for", "test[a]['stimulus'][match] == test[a]['response'][match]: return True else: return False def checkFirstSetPers(test, attemptNum): # Break", "the test number and class number from the directory names p = path.split('\\\\')", "and third unambiguous response must # match this sorting principle. # # 3.", "x > 0: if test[x]['set'] != test[attemptNum]['set']: return False # Check to see", "ways the response matches the answer for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k]", "if not test[attemptNum]['sandwiched']: test[attemptNum]['reasoning'] += ' - Attempt ' + str(attemptNum) + '", "in lines: # Split the test report into an array of Dicts #", "This covers the intermediate results tempMatches = getMatches(test, x) if not match in", "unambiguous self-perserveration' test[unambiguousMatches[1]]['rule_3_2'] = True test[unambiguousMatches[1]]['reasoning'] += ' - Rule 3: Second unambiguous", "chain sandwich perservative per 2c' test[a]['perservative'] = True return True else: test[a]['2c'] =", "set 'rule_3_1' : False, # These are to show matches for Heaton's rule", "# print('Holy shit, we found one on attempt ', attemptNum) # print (test[attemptNum])", "the new, not currently # perserverative principle if len(tempMatches) != 1: continue #", "folder in the PATH variable allTests = [] for path, dirs, files in", "The ambiguous response must match the # > perseverated-to principle that is currently", "'', 'X' if a['rule_3_2'] else '', 'X' if a['rule_3_3'] else '', a['reasoning'] ])", "and format it for analysis. Skip the headers. lines.pop(0) lineCount = 0 for", "not a['perservative']: totalNonPerserverative +=1 if (not a['perservative'] and not a['correct']): totalNonPerserverativeErrors +=1 totalTrials+=1", "first sandwich, matching 2a and 2b. Marking perservative.' return True x-=1 def isChainedSandwich(test,", "allTests.append(analyzeTest(fullpath, testNum, classNum)) for t in allTests: totalCorrect = 0 totalError = 0", "'.csv').st_size == 0: cw.writerow(['Class', 'Subject', 'Sets Attempted', 'Correct', 'Errors', 'Non-Perserverative', 'Non-Perserverative Errors', 'Perserverative',", "if (test[y]['ambiguous'] == False and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ):", "perservative.' return True x-=1 def isChainedSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return False", "= None test[x]['reasoning'] += ' - Rule 3: Set to unscorable for first", "found one on attempt ', attemptNum) # print (test[attemptNum]) return True def checkChainedSandwich(test,", "' + str(test[0]['subject']), '\\n', unambiguousMatches, '\\n') test[unambiguousMatches[0]]['rule_3_1'] = True test[unambiguousMatches[0]]['reasoning'] += ' -", "pers # It's a match! unambiguousMatches.append(test[x]['attemptNum']) if len(unambiguousMatches) == 3: break if len(unambiguousMatches)", "False def isSandwiched(test, attemptNum): # It has to have a principle match to", "Check if the attempt had an unambiguous incorrect answer. Skip the answer #", "answer. # If so, set the Principle whichever principle the client matched if", "# Check to see if we found the bread if (test[x]['ambiguous'] == False", "suggest that this response is perserverating if test[attemptNum]['stimulus'][pers] == test[attemptNum]['response'][pers]: # test[attemptNum]['reasoning'] +=", "x.add_row([a['attemptNum'], a['match'], #n, corr + response, a['currentPerservativeTo'], #prin, pers, sw, chain, 'X' if", "been determined (first set) then the first unambiguous # incorrect answer determines the", "are to show matches for Heaton's rule 3 'rule_3_2' : False, # for", "'', 'X' if a['rule_3_3'] else '', a['reasoning'] ]) prevMatch = a['match'] def printTest(test):", "if not isSandwiched(test, attemptNum): return False x = attemptNum - 1 while x", "unambiguous error.' return True # If the client perserverated to the Other category,", "+ str(test[0]['testNum'])+ ', ' + str(test[0]['subject']) + ', ' + test[0]['file'])) def splitStim(stim):", "test[attemptNum]['response'][pers] + ') which matches the principle (' + pers + ')' return", "False and test[attemptNum]['ambiguous'] == False): for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] ==", "== False and containsPrincipleMatch(test, attemptNum) ): test[attemptNum]['reasoning'] += ' - Attempt is unambiguously", "has to have a principle match to be considered perservative at all if", "error match = matches[0] # If we get here, then we know the", "= '' if a['match'] != prevMatch: n = a['match'] else: n = ''", "for attempt in test: # 7. Now we start looking for ambiguous perserverations.", "new principle x = unambiguousMatches[1] while (x < len(test) and test[x]['set'] == test[unambiguousMatches[1]]['set']):", "sandwichAfter = True # print (str(attemptNum) + ' Sandwiched After by attempt '", "unambiguousMatches[1]: test[x]['currentPerservativeTo'] = None test[x]['reasoning'] += ' - Rule 3: Set to unscorable", "- Rule 3: Set to unscorable for first to second responses' # print", "\"sandwiched\" between ' + str(x) + ' and ' + str(y) test[attemptNum]['sandwiched'] =", "attempt['attemptNum']) # 3. Check if the attempt was an error checkAnswer(test, attempt['attemptNum']) #", "unambiguous incorrect answer. # If so, set the Principle whichever principle the client", "= '' if a['2c']: chain = '+' else: chain = '' cw.writerow([a['attemptNum'], a['match'],", "'2c', '3.1', '3.2', '3.3'] prevMatch = '' prevPrin = '' for a in", "if sandwichBefore == False: return False # Next we check forwards. y =", "# 1. Set the principle the same as last attempt.The current # principle", "the first set if test[attemptNum]['set'] != 1: return None # Break out if", "if (not a['perservative'] and not a['correct']): totalNonPerserverativeErrors +=1 totalTrials+=1 with open('SUMMARY_' + t[0]['testNum']", "+= 1 # First pass: Analyze the data with a set of rules", "response is perserverating if test[attemptNum]['stimulus'][pers] == test[attemptNum]['response'][pers]: # test[attemptNum]['reasoning'] += ' - Attempt", "sandwiched by an unambiguous response for the same principle x = attemptNum -", "first attempt will never have a Principle if attemptNum == 0: return None", "into an array of Dicts # Added some error handling because the text", "str(test[0]['subject']), '\\n', unambiguousMatches, '\\n') test[unambiguousMatches[0]]['rule_3_1'] = True test[unambiguousMatches[0]]['reasoning'] += ' - Rule 3:", ": False, 'set1PrincipleEstablished' : False, # Will change to true if the principle", "os from prettytable import PrettyTable # The top level folder which contains the", "a['currentPerservativeTo'] != prevPrin: prin = a['currentPerservativeTo'] prevPrin = prin else: prin = ''", "perserverating if test[attemptNum]['stimulus'][pers] == test[attemptNum]['response'][pers]: # test[attemptNum]['reasoning'] += ' - Attempt has a", "' - Principle already set. No change for unambiguous error.' return None #", "Attempt is chain sandwich perservative per 2c' test[a]['perservative'] = True return True else:", "(Chained Sandwich)', '3.1 (Self-Perserveration)', '3.2', '3.3', 'Reasoning']) prevMatch = '' prevPrin = ''", "at all if not containsPrincipleMatch(test, attemptNum): return False # It has to be", "in a subsequent rule. continuePreviousPresTo(test, attempt['attemptNum']) # 2. Check if we just moved", "unambiguous error matching the perservative-to rule, AND # the rule was not established", "first-set's Principle checkFirstSetPers(test, attempt['attemptNum']) for attempt in test: # 5. Heaton's rule 3:", "due to start of test.' return None def checkNewSet(test, attemptNum): # The very", "in each folder in the PATH variable allTests = [] for path, dirs,", "+ t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv', 'a', newline='') as csvfile: cw", "# which is neither correct nor currently perserverative. # # 2. All responses", "(' + pers + ')' return True else: return False def getMatches(test, a):", "Variables which contain the column numbers, used for readability SUBJECT = 3 MATCH", "Heaton's rule 3 'rule_3_2' : False, # for self perserverations 'rule_3_3' : False,", "file # Get the test number and class number from the directory names", "= True # print (str(attemptNum) + ' Sandwiched Before by attempt ' +", "+ k + ' from first unambiguous error.' return True # If the", "+ ') which matches the principle (' + pers + ')' return True", "pers, sw, chain, 'X' if a['rule_3_1'] else '', 'X' if a['rule_3_2'] else '',", "first unambiguous # incorrect answer determines the first-set's Principle checkFirstSetPers(test, attempt['attemptNum']) for attempt", "is an unambiguous result if isCorrect(test, x): continue # Make sure it's an", "while y < len(test): if test[y]['set'] != test[attemptNum]['set']: return False # Check to", "' + k + ' from first unambiguous error.' return True # If", "hasn't already been done if not test[attemptNum]['sandwiched']: test[attemptNum]['reasoning'] += ' - Attempt '", "if test[x]['sandwiched']: return False if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and", "' + str(x)) break x -= 1 if sandwichBefore == False: return False", "tests PATH = os.getcwd() # r\"C:\\Users\\wyko.terhaar\\Downloads\\Map voor Wyko\\raw\" # Variables which contain the", "to something other than the current principle matches = getMatches(test, a) if len(matches)", "= '+' else: chain = '' cw.writerow([a['attemptNum'], a['match'], #n, response, '+' if a['correct']", "False # print(str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']), '\\n',", "the answer for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: matchQuotient +=", "return False # Now we look for the last two unambiguous errors to", "and test[attemptNum]['ambiguous'] == False): for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v:", "ambiguous answers are the first ones isFirstSandwich(test, attempt['attemptNum']) for attempt in test: #", "# wait = input('') return True else: if not 'Attempt is not sandwiched'", "file: \\n' + fullpath) lineCount += 1 # First pass: Analyze the data", "test[attemptNum]['response'][pers]: # test[attemptNum]['reasoning'] += ' - Attempt has a response (' + test[attemptNum]['response'][pers]", "all the rest, up to the next set change, to the new principle", "if attemptNum == 0: return None if test[attemptNum]['set'] != test[attemptNum-1]['set']: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['match']", "# > perseverated-to principle that is currently in # > effect (in our", "int(attempt[SUBJECT]), 'set' : int(attempt[SET]), 'match' : attempt[MATCH], 'stimulus' : splitStim(attempt[STIMULUS]), 'response' : splitStim(attempt[RESPONSE]),", "+ '_' + t[0]['classNum'] + '.csv').st_size == 0: cw.writerow(['Class', 'Subject', 'Sets Attempted', 'Correct',", "to \", match) x+=1 def analyzeTest(fullpath, testNum, classNum): test = [] # Open", "9 RESPONSE = 10 def saveResults(test): with open('ANALYSIS_' + test[0]['file'] + '.csv', 'w',", "if isCorrect(test, x): continue # Make sure it's an error if test[x]['currentPerservativeTo'] in", "which satisfies Heaton rule 2a: # > The ambiguous response must match the", "+= ' - Rule 3: Principle set to ' + match + '", "# \"sandwich rule.\" isSandwiched(test, attempt['attemptNum']) for attempt in test: # 8. Check if", "attempt['attemptNum']) for attempt in test: # 5. Heaton's rule 3: Find self-made perserverations", "filename) # Get the filename for each file # Get the test number", "filename: continue # Skip any python files if 'ANALYSIS' in filename: continue #", "and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichBefore = True # print (str(attemptNum) + '", "filename in files: if '.py' in filename: continue # Skip any python files", "while x > 0: if test[x]['set'] != test[attemptNum]['set']: return False if isSandwiched(test, x):", "2c' not in test[a]['reasoning'] ): test[a]['reasoning'] += ' - Sandwiched attempt is NOT", "Rule 3: Final unambiguous self-perserveration' # Set all responses from the first untill", "return False if isCorrect(test, a): return False # Make sure it's an error", "more indicators! x = a unambiguousMatches = [x,] # We need 3 to", "unambiguous error. # First, we check to see if this is an unambiguous", "in all subsequent attempts # This covers the intermediate results tempMatches = getMatches(test,", "+ ' is \"sandwiched\" between ' + str(x) + ' and ' +", "and read it into memory with open (fullpath) as f: lines = f.readlines()", "sandwichAfter = False while y < len(test): if test[y]['set'] != test[attemptNum]['set']: break if", "match the # > perseverated-to principle that is currently in # > effect", "'', sw, chain, 'X' if a['rule_3_1'] else '', 'X' if a['rule_3_2'] else '',", "checkSelfPerserveration(test, a): # 1. The client must make 3 unambiguous errors to a", "Determine if a response matches the stimulus on the match criteria match =", "' else: corr = ' ' if a['firstSandwich']: sw= '+' else: sw =", "if a response matches the stimulus on the match criteria match = test[a]['match']", "def printTest(test): x = PrettyTable() # x.padding_width = 10 x.left_padding_width = 1 x.right_padding_width", "the principle accordingly checkNewSet(test, attempt['attemptNum']) # 3. Check if the attempt was an", "find if an ambiguous, potentially perservative # response was sandwiched by an unambiguous", "# We need 3 to confirm self-perserveration # print{'Added first', x) while x", "isSandwiched(test, attemptNum): return False if isFirstSandwich(test, attemptNum): return False x = attemptNum -", "category. No Principle set.' return None def containsPrincipleMatch(test, attemptNum): # Helper function which", "# print (test[x]) # print (test[attemptNum]) # print (test[y]) # wait = input('')", "' (last set match clause) because set was changed.' return True def checkAnswer(test,", "else: test[attemptNum]['reasoning'] += 'Principle is none due to start of test.' return None", "test[attemptNum]['reasoning'] += ' - Principle was set to ' + str(test[attemptNum]['currentPerservativeTo']) + '", "+= ' - Client perserverated to Other category. No Principle set.' return None", "Here we check the # \"sandwich rule.\" isSandwiched(test, attempt['attemptNum']) for attempt in test:", "'rule_3_3' : False, }) except: print ('There was an error reading line '", "prevPrin = '' for a in test: response = '' if a['stimulus']['color'] ==", "'number' : x.group(3) } def continuePreviousPresTo(test, attemptNum): if attemptNum > 0: test[attemptNum]['currentPerservativeTo'] =", "False and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If", "and 2b. Marking perservative.' return True x-=1 def isChainedSandwich(test, attemptNum): if not isSandwiched(test,", "len(matches) != 1: return False # One match for an unambiguous result if", "+ str(test[unambiguousMatches[0]]['attemptNum']) test[unambiguousMatches[2]]['rule_3_3'] = True test[unambiguousMatches[2]]['reasoning'] += ' - Rule 3: Final unambiguous", "True else: test[attemptNum]['ambiguous'] = False # Determine if the answer is correct if", "that this response is perserverating if test[attemptNum]['stimulus'][pers] == test[attemptNum]['response'][pers]: # test[attemptNum]['reasoning'] += '", "1 # Next we check forwards. y = attemptNum + 1 while y", "2a: # > The ambiguous response must match the # > perseverated-to principle", "the second unambiguous error. # First, we check to see if this is", "> The ambiguous response must match the # > perseverated-to principle that is", "same principle x = attemptNum - 1 sandwichBefore = False while x >", "return False def checkFirstSetPers(test, attemptNum): # Break out if this is not the", "contain the column numbers, used for readability SUBJECT = 3 MATCH = 5", "shit, we found one on attempt ', attemptNum) # print (test[attemptNum]) return True", "to a sorting principle # which is neither correct nor currently perserverative. #", "# Now we look for the last two unambiguous errors to the new,", "headers. lines.pop(0) lineCount = 0 for line in lines: # Split the test", "to be ambiguous to be considered for sandwich perseveration if not test[attemptNum]['ambiguous']: return", "this way and then loop again checkUnambiguousPerserveration(test, attempt['attemptNum']) for attempt in test: #", "(not a['perservative'] and not a['correct']): totalNonPerserverativeErrors +=1 totalTrials+=1 with open('SUMMARY_' + t[0]['testNum'] +", "# 7. Now we start looking for ambiguous perserverations. Here we check the", "the principle changed this attempt in the first set 'rule_3_1' : False, #", "Principle is not set for future attempts. Maybe we also need to have", "- Rule 3: Second unambiguous self-perserveration after attempt ' + str(test[unambiguousMatches[0]]['attemptNum']) test[unambiguousMatches[2]]['rule_3_3'] =", "False # Check to see if we found the bread if (test[y]['ambiguous'] ==", "was not established this attempt (on the first set). # We have to", "' + str(y)) break y += 1 if sandwichAfter and sandwichBefore: #Mark the", "which contain the column numbers, used for readability SUBJECT = 3 MATCH =", "is not the first set if test[attemptNum]['set'] != 1: return None # Break", "for line in lines: # Split the test report into an array of", "False # Now we look for the last two unambiguous errors to the", "match criteria match = test[a]['match'] if test[a]['stimulus'][match] == test[a]['response'][match]: return True else: return", "(test[y]['ambiguous'] == False and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break", "a new set, and adjust the principle accordingly checkNewSet(test, attempt['attemptNum']) # 3. Check", "= test[attemptNum-1]['match'] test[attemptNum]['reasoning'] += ' - Principle was set to ' + str(test[attemptNum]['currentPerservativeTo'])", "Skip the root for filename in files: if '.py' in filename: continue #", "while x > 0: if test[x]['set'] != test[attemptNum]['set']: break if (test[x]['ambiguous'] == False", "test[a]['perservative'] = True return True else: test[a]['2c'] = False if ( test[a]['sandwiched'] and", "will be the same as the last attempt, unless # it changes in", "open('ANALYSIS_' + test[0]['file'] + '.csv', 'w', newline='') as csvfile: cw = csv.writer(csvfile) cw.writerow(['#',", "continue # Ensure it is an unambiguous result if isCorrect(test, x): continue #", "forwards. y = attemptNum + 1 sandwichAfter = False while y < len(test):", "response for the same principle x = attemptNum - 1 sandwichBefore = False", "the new principle x = unambiguousMatches[1] while (x < len(test) and test[x]['set'] ==", "the root for filename in files: if '.py' in filename: continue # Skip", "format it for analysis. Skip the headers. lines.pop(0) lineCount = 0 for line", "will never have a Principle if attemptNum == 0: return None if test[attemptNum]['set']", "perservative # response was sandwiched by an unambiguous response for the same principle", "# principle will be the same as the last attempt, unless # it", "if test[attemptNum]['currentPerservativeTo'] is not None: test[attemptNum]['reasoning'] += ' - Principle already set. No", "the attempt had an unambiguous incorrect answer. Skip the answer # in which", "a match! unambiguousMatches.append(test[x]['attemptNum']) if len(unambiguousMatches) == 3: break if len(unambiguousMatches) != 3: return", "True test[unambiguousMatches[0]]['reasoning'] += ' - Rule 3: First unambiguous self-perserveration' test[unambiguousMatches[1]]['rule_3_2'] = True", "also # sandwiches, then 2c doesn't apply if not isSandwiched(test, x): return False", "1 # print('Holy shit, we found one on attempt ', attemptNum) # print", "\"sandwich rule.\" isSandwiched(test, attempt['attemptNum']) for attempt in test: # 8. Check if the", "a['currentPerservativeTo'], #prin, pers, sw, chain, 'X' if a['rule_3_1'] else '', 'X' if a['rule_3_2']", "currently perserverative. # # 2. All responses between the first and third unambiguous", "an unambiguous response for the same principle x = attemptNum - 1 sandwichBefore", "unambiguous errors to the new, not currently # perserverative principle if len(tempMatches) !=", "'N* ' else: response += 'N ' if a['perservative'] and a['ambiguous']: pers =", "+ ' (last set match clause) because set was changed.' return True def", "(on the first set). # We have to know this for every rule", "perseverated-to principle that is currently in # > effect (in our example, Color", "and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If any of the preceeding attempts", "< len(test) and test[x]['set'] == test[unambiguousMatches[1]]['set']): test[x]['currentPerservativeTo'] = match test[x]['reasoning'] += ' -", "test[attemptNum]['response'][k] == v: matchQuotient += 1 # Mark whether the attempt is ambiguous", "continue # Skip any generated analysis files # if not 'iqdat' in filename:", "an error match = matches[0] # If we get here, then we know", "other than the current principle matches = getMatches(test, a) if len(matches) != 1:", "unambiguousMatches[1] while (x < len(test) and test[x]['set'] == test[unambiguousMatches[1]]['set']): test[x]['currentPerservativeTo'] = match test[x]['reasoning']", "an error reading line ' + str(lineCount) + ' in file: \\n' +", "Check to see if we found the bread if (test[y]['ambiguous'] == False and", "x.left_padding_width = 1 x.right_padding_width = 1 x.field_names = ['#', \"Match\", \"Matched\", 'Pres-To', 'Pers',", "+= 'N* ' else: response += 'N ' if a['perservative'] and a['ambiguous']: pers", "a Principle if attemptNum == 0: return None if test[attemptNum]['set'] != test[attemptNum-1]['set']: test[attemptNum]['currentPerservativeTo']", "sandwiched.' return False def isFirstSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return False x", "test[attemptNum]['currentPerservativeTo'] ): break # If any of the preceeding attempts before the \"bread\"", "== v: matches.append(k) return matches def checkUnambiguousPerserveration(test, attemptNum): # Check if the attempt", "attemptNum): # It has to have a principle match to be considered perservative", "True return True else: return False def isSandwiched(test, attemptNum): # It has to", "to have the category changer run after this? ##################################### # Set all the", "moved into a new set, and adjust the principle accordingly checkNewSet(test, attempt['attemptNum']) #", "if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False and test[attemptNum]['currentPerservativeTo'] is not None", ": None, # Stores the currently active Pres-To Principle 'reasoning' : '', #", "last attempt, unless # it changes in a subsequent rule. continuePreviousPresTo(test, attempt['attemptNum']) #", "response += 'N ' if a['perservative'] and a['ambiguous']: pers = 'A-Pers' elif a['perservative']:", "> 0: if test[x]['set'] != test[attemptNum]['set']: return False # Check to see if", "if a['ambiguous'] else '', sw, chain, 'X' if a['rule_3_1'] else '', 'X' if", "True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If any of the preceeding", "t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv').st_size == 0: cw.writerow(['Class', 'Subject', 'Sets Attempted',", "is an unambiguous error # to something other than the current principle matches", "test[attemptNum]['set'] != test[attemptNum-1]['set']: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['match'] test[attemptNum]['reasoning'] += ' - Principle was set", "whichever principle the client matched if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False):", "ahead for more indicators! x = a unambiguousMatches = [x,] # We need", "csv, os from prettytable import PrettyTable # The top level folder which contains", "return True else: return False def getMatches(test, a): matches = [] for k,", "see if this is an unambiguous error # to something other than the", "'Correct', 'Errors', 'Non-Perserverative', 'Non-Perserverative Errors', 'Perserverative', 'Trials', '% Perserverative']) cw.writerow([ t[0]['classNum'], t[0]['subject'], totalSetsAttempted,", "attempt['attemptNum']) for attempt in test: # 8. Check if the sandwiched ambiguous answers", "v: test[attemptNum]['currentPerservativeTo'] = k test[attemptNum]['set1PrincipleEstablished'] = True test[attemptNum]['reasoning'] += ' - Principle was", "was not an incorrect answer if test[attemptNum]['correct'] == True: return None if test[attemptNum]['currentPerservativeTo']", "test[attemptNum]['set1PrincipleEstablished'] == False and containsPrincipleMatch(test, attemptNum) ): test[attemptNum]['reasoning'] += ' - Attempt is", "if isChainedSandwich(test, a): test[a]['2c'] = True test[a]['reasoning'] += ' - Attempt is chain", "else: return False def checkFirstSetPers(test, attemptNum): # Break out if this is not", "by # > the previous sorting category) # False if not principle has", "v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: test[attemptNum]['currentPerservativeTo'] = k test[attemptNum]['set1PrincipleEstablished'] = True", "is matched in all subsequent attempts # This covers the intermediate results tempMatches", "test[attemptNum]['response'][k] == v: test[attemptNum]['currentPerservativeTo'] = k test[attemptNum]['set1PrincipleEstablished'] = True test[attemptNum]['reasoning'] += ' -", "has to be ambiguous to be considered for sandwich perseveration if not test[attemptNum]['ambiguous']:", "which contains the tests PATH = os.getcwd() # r\"C:\\Users\\wyko.terhaar\\Downloads\\Map voor Wyko\\raw\" # Variables", "'', 'classNum' : classNum, 'currentPerservativeTo' : None, # Stores the currently active Pres-To", "to continue previous pattern.' return True else: test[attemptNum]['reasoning'] += 'Principle is none due", "matches the stimulus on the current Perserveration principle. # This would suggest that", "perservative-to rule, AND # the rule was not established this attempt (on the", "attemptNum > 0: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['currentPerservativeTo'] test[attemptNum]['reasoning'] += 'Principle was set to '", "bread if (test[y]['ambiguous'] == False and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo']", "+ str(y) test[attemptNum]['sandwiched'] = True # print (str(attemptNum) + ' Sandwiched Before by", "line in lines: # Split the test report into an array of Dicts", "first indicator. # Let's look ahead for more indicators! x = a unambiguousMatches", "checkUnambiguousPerserveration(test, attempt['attemptNum']) for attempt in test: # 7. Now we start looking for", "0 totalNonPerserverativeErrors = 0 totalPerserverative = 0 totalTrials = 0 for a in", "' - Rule 3: Principle set to ' + match + ' due", "subsequent rule. continuePreviousPresTo(test, attempt['attemptNum']) # 2. Check if we just moved into a", "be ambiguous to be considered for sandwich perseveration if not test[attemptNum]['ambiguous']: return False", "'\\n') test[unambiguousMatches[0]]['rule_3_1'] = True test[unambiguousMatches[0]]['reasoning'] += ' - Rule 3: First unambiguous self-perserveration'", "the attempt had an unambiguous incorrect answer. # If so, set the Principle", "in tempMatches: return False # Now we look for the last two unambiguous", "Heaton rule 2a: # > The ambiguous response must match the # >", "and test[attemptNum]['currentPerservativeTo'] is not None and test[attemptNum]['set1PrincipleEstablished'] == False and containsPrincipleMatch(test, attemptNum) ):", "test[attemptNum]['currentPerservativeTo'] ): test[attemptNum]['firstSandwich'] = True test[attemptNum]['perservative'] = True test[attemptNum]['reasoning'] += ' - Attempt", "= 10 x.left_padding_width = 1 x.right_padding_width = 1 x.field_names = ['#', \"Match\", \"Matched\",", "the loop this way and then loop again checkUnambiguousPerserveration(test, attempt['attemptNum']) for attempt in", "an unambiguous error matching the perservative-to rule, AND # the rule was not", "unambiguous result if test[a]['currentPerservativeTo'] in matches: return False if isCorrect(test, a): return False", "class number from the directory names p = path.split('\\\\') classNum = p[len(p)-1] testNum", "def checkChainedSandwich(test, a): if isChainedSandwich(test, a): test[a]['2c'] = True test[a]['reasoning'] += ' -", "result if test[a]['currentPerservativeTo'] in matches: return False if isCorrect(test, a): return False #", "containsPrincipleMatch(test, attemptNum): # Helper function which satisfies Heaton rule 2a: # > The", "directory names p = path.split('\\\\') classNum = p[len(p)-1] testNum = p[len(p)-2] allTests.append(analyzeTest(fullpath, testNum,", "match in tempMatches: return False # Now we look for the last two", "elif a['perservative']: pers = 'U-Pers' else: pers = '' if a['match'] != prevMatch:", "' + str(test[attemptNum]['currentPerservativeTo']) + ' to continue previous pattern.' return True else: test[attemptNum]['reasoning']", "continuePreviousPresTo(test, attemptNum): if attemptNum > 0: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['currentPerservativeTo'] test[attemptNum]['reasoning'] += 'Principle was", "Iterate through the test and format it for analysis. Skip the headers. lines.pop(0)", "+ str(test[0]['testNum'])+ ', ' + str(test[0]['subject']), '\\n', unambiguousMatches, '\\n') test[unambiguousMatches[0]]['rule_3_1'] = True test[unambiguousMatches[0]]['reasoning']", "if path == PATH: continue # Skip the root for filename in files:", "this response is perserverating if test[attemptNum]['stimulus'][pers] == test[attemptNum]['response'][pers]: # test[attemptNum]['reasoning'] += ' -", "if not 'Attempt is not sandwiched' in test[attemptNum]['reasoning']: test[attemptNum]['reasoning'] += ' - Attempt", "test[attemptNum]['set1PrincipleEstablished'] = True test[attemptNum]['reasoning'] += ' - Principle was established as ' +", "is correct if isCorrect(test, attemptNum): test[attemptNum]['correct'] = True else: test[attemptNum]['correct'] = False def", "unambiguous result if isCorrect(test, x): continue # Make sure it's an error if", "first and third unambiguous response must # match this sorting principle. # #", "if a['rule_3_3'] else '', ]) prevMatch = a['match'] print(x.get_string(title= str(test[0]['classNum']) + ', '", "Make sure the potential principle is matched in all subsequent attempts # This", "else: corr = ' ' if a['firstSandwich']: sw= '+' else: sw = ''", "set to ' + match + ' due to self-perserveration' # print(\"Test \",", "unless # it changes in a subsequent rule. continuePreviousPresTo(test, attempt['attemptNum']) # 2. Check", "all subsequent attempts # This covers the intermediate results tempMatches = getMatches(test, x)", "3: Principle set to ' + match + ' due to self-perserveration' #", "csv.writer(csvfile) if os.stat('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv').st_size == 0:", "set to \", match) x+=1 def analyzeTest(fullpath, testNum, classNum): test = [] #", "= a['set'] # Will end up being the final set if a['perservative']: totalPerserverative", "= csv.writer(csvfile) if os.stat('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv').st_size ==", "reasoning to help verify results # The following are all boolean 'correct' :", "print (str(attemptNum) + ' Sandwiched Before by attempt ' + str(x)) # print", "if a['rule_3_3'] else '', a['reasoning'] ]) prevMatch = a['match'] def printTest(test): x =", "0 totalPerserverative = 0 totalTrials = 0 for a in t: if a['correct']:", "def checkFirstSetPers(test, attemptNum): # Break out if this is not the first set", "', ' + test[0]['file'])) def splitStim(stim): x = re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)', stim) return { 'color'", "Now we look for the last two unambiguous errors to the new, not", "test[attemptNum]['reasoning'] += 'Principle was set to ' + str(test[attemptNum]['currentPerservativeTo']) + ' to continue", "# if not 'iqdat' in filename: continue fullpath = os.path.join(path, filename) # Get", "+= ' - Rule 3: First unambiguous self-perserveration' test[unambiguousMatches[1]]['rule_3_2'] = True test[unambiguousMatches[1]]['reasoning'] +=", "new, not currently # perserverative principle if len(tempMatches) != 1: continue # Ensure", "break if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo']", "test[unambiguousMatches[1]]['reasoning'] += ' - Rule 3: Second unambiguous self-perserveration after attempt ' +", "x = unambiguousMatches[0] while x < unambiguousMatches[1]: test[x]['currentPerservativeTo'] = None test[x]['reasoning'] += '", "the first set). # We have to know this for every rule before", "analyzeTest(fullpath, testNum, classNum): test = [] # Open the file and read it", "if the sandwiched ambiguous answers are the first ones isFirstSandwich(test, attempt['attemptNum']) for attempt", "test[a]['currentPerservativeTo'] in matches: return False if isCorrect(test, a): return False # Make sure", "# response was sandwiched by an unambiguous response for the same principle x", "', attemptNum) # print (test[attemptNum]) return True def checkChainedSandwich(test, a): if isChainedSandwich(test, a):", "= a['currentPerservativeTo'] prevPrin = prin else: prin = '' if a['correct']: corr =", "if we found the bread if (test[x]['ambiguous'] == False and test[x]['perservative'] == True", "# Get the test number and class number from the directory names p", "'currentPerservativeTo' : None, # Stores the currently active Pres-To Principle 'reasoning' : '',", "' + str(attemptNum) + ' is \"sandwiched\" between ' + str(x) + '", "'+ ' else: corr = ' ' if a['firstSandwich']: sw= '+' else: sw", "None: return False pers = test[attemptNum]['currentPerservativeTo'] # Check to see if the response", "return False def isSandwiched(test, attemptNum): # It has to have a principle match", "False, 'firstSandwich' : False, 'set1PrincipleEstablished' : False, # Will change to true if", "= attemptNum + 1 sandwichAfter = False while y < len(test): if test[y]['set']", "set to ' + str(test[attemptNum]['currentPerservativeTo']) + ' (last set match clause) because set", "Skip the answer # in which the Principle principle was established in the", "= a unambiguousMatches = [x,] # We need 3 to confirm self-perserveration #", "'stimulus' : splitStim(attempt[STIMULUS]), 'response' : splitStim(attempt[RESPONSE]), 'testNum' : testNum, '2c' : '', 'classNum'", "perserverated to Other category. No Principle set.' return None def containsPrincipleMatch(test, attemptNum): #", "isSandwiched(test, x): return False x -= 1 # Next we check forwards. y", "test[attemptNum]['currentPerservativeTo'] # Check to see if the response matches the stimulus on the", "the preceeding attempts before the \"bread\" aren't also # sandwiches, then 2c doesn't", "== 0: return None if test[attemptNum]['set'] != test[attemptNum-1]['set']: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['match'] test[attemptNum]['reasoning'] +=", "return True else: test[attemptNum]['reasoning'] += 'Principle is none due to start of test.'", "True: return None if test[attemptNum]['currentPerservativeTo'] is not None: test[attemptNum]['reasoning'] += ' - Principle", "The client must make 3 unambiguous errors to a sorting principle # which", "test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If any of", "totalSetsAttempted = a['set'] # Will end up being the final set if a['perservative']:", "newline='') as csvfile: cw = csv.writer(csvfile) cw.writerow(['#', 'Match', \"Response\", 'Correct', 'Pres-To', 'Perserverative', 'Ambiguous',", "perseveration if not test[attemptNum]['ambiguous']: return False # First we look backwards to find", "doesn't apply if not isSandwiched(test, x): return False x -= 1 # Next", "and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If any", "are all boolean 'correct' : False, 'perservative' : False, 'ambiguous' : False, 'sandwiched'", "print (str(attemptNum) + ' Sandwiched After by attempt ' + str(y)) break y", "( test[a]['sandwiched'] and 'NOT perservative per 2c' not in test[a]['reasoning'] ): test[a]['reasoning'] +=", "attemptNum): return False if isFirstSandwich(test, attemptNum): return False x = attemptNum - 1", "1 if sandwichBefore == False: return False # Next we check forwards. y", "Break out if this is not the first set if test[attemptNum]['set'] != 1:", "a['currentPerservativeTo'], #prin, '+' if a['perservative'] else '', '+' if a['ambiguous'] else '', sw,", "False): for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: test[attemptNum]['currentPerservativeTo'] = k", "results tempMatches = getMatches(test, x) if not match in tempMatches: return False #", "test[attemptNum]['reasoning'] += ' - Client perserverated to Other category. No Principle set.' return", "== True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If any of the", "== PATH: continue # Skip the root for filename in files: if '.py'", "rule.\" isSandwiched(test, attempt['attemptNum']) for attempt in test: # 8. Check if the sandwiched", "False: return False # Next we check forwards. y = attemptNum + 1", "Skip the headers. lines.pop(0) lineCount = 0 for line in lines: # Split", "as csvfile: cw = csv.writer(csvfile) cw.writerow(['#', 'Match', \"Response\", 'Correct', 'Pres-To', 'Perserverative', 'Ambiguous', \"2b", "defined by # > the previous sorting category) # False if not principle", "have to know this for every rule before we can go on to", "totalError +=1 totalSetsAttempted = a['set'] # Will end up being the final set", "sandwichBefore = True # print (str(attemptNum) + ' Sandwiched Before by attempt '", "criteria match = test[a]['match'] if test[a]['stimulus'][match] == test[a]['response'][match]: return True else: return False", "After by attempt ' + str(y)) # print (test[x]) # print (test[attemptNum]) #", "rule 3: Find self-made perserverations checkSelfPerserveration(test, attempt['attemptNum']) for attempt in test: # 6.", "attempt in test: # 6. If this was an unambiguous error matching the", "first ones isFirstSandwich(test, attempt['attemptNum']) for attempt in test: # 9. Check rule 2c", "with open('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv', 'a', newline='') as", "and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichAfter = True #", "attempt ' + str(x)) # print (str(attemptNum) + ' Sandwiched After by attempt", "in os.walk(PATH): if path == PATH: continue # Skip the root for filename", "be considered perservative at all if not containsPrincipleMatch(test, attemptNum): return False # It", "x = unambiguousMatches[1] while (x < len(test) and test[x]['set'] == test[unambiguousMatches[1]]['set']): test[x]['currentPerservativeTo'] =", "totalNonPerserverativeErrors = 0 totalPerserverative = 0 totalTrials = 0 for a in t:", "Dicts # Added some error handling because the text files aren't always clean.", "!= prevMatch: n = a['match'] else: n = '' if a['currentPerservativeTo'] != prevPrin:", "already been done if not test[attemptNum]['sandwiched']: test[attemptNum]['reasoning'] += ' - Attempt ' +", "# Make sure it's an error if test[x]['currentPerservativeTo'] in tempMatches: continue # Not", "Return the fully populated and analyzed test object # printTest(test) saveResults(test) return test", "and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichAfter = True # print (str(attemptNum) + '", "is currently in # > effect (in our example, Color as defined by", "# Determine how ambiguous the answer is matchQuotient = 0 # This is", "test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['match'] test[attemptNum]['reasoning'] += ' - Principle was set to ' +", "break y += 1 if sandwichAfter and sandwichBefore: #Mark the sandwich if it", "filename: continue fullpath = os.path.join(path, filename) # Get the filename for each file", "totalTrials = 0 for a in t: if a['correct']: totalCorrect +=1 if not", "False if not principle has been set yet. if test[attemptNum]['currentPerservativeTo'] is None: return", "True test[attemptNum]['perservative'] = True test[attemptNum]['reasoning'] += ' - Attempt is a first sandwich,", "principle. # # 3. The new principle becomes active to register perserverations only", "rule. continuePreviousPresTo(test, attempt['attemptNum']) # 2. Check if we just moved into a new", "\"2b (1st Sandwich)\", '2c (Chained Sandwich)', '3.1 (Self-Perserveration)', '3.2', '3.3', 'Reasoning']) prevMatch =", "PrettyTable() # x.padding_width = 10 x.left_padding_width = 1 x.right_padding_width = 1 x.field_names =", "if this is an unambiguous error # to something other than the current", "' Sandwiched Before by attempt ' + str(x)) # print (str(attemptNum) + '", "== False and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichAfter =", "established this attempt (on the first set). # We have to know this", "change, to the new principle x = unambiguousMatches[1] while (x < len(test) and", "3. The new principle becomes active to register perserverations only # after the", "'attemptNum' : lineCount, 'subject' : int(attempt[SUBJECT]), 'set' : int(attempt[SET]), 'match' : attempt[MATCH], 'stimulus'", "+ test[attemptNum]['response'][pers] + ') which matches the principle (' + pers + ')'", "set to ' + str(test[attemptNum]['currentPerservativeTo']) + ' to continue previous pattern.' return True", "+ str(x) + ' and ' + str(y) test[attemptNum]['sandwiched'] = True # print", "perserverations 'rule_3_3' : False, }) except: print ('There was an error reading line", "complicated # tests, so we finish the loop this way and then loop", "the answer is correct if isCorrect(test, attemptNum): test[attemptNum]['correct'] = True else: test[attemptNum]['correct'] =", "testNum = p[len(p)-2] allTests.append(analyzeTest(fullpath, testNum, classNum)) for t in allTests: totalCorrect = 0", "Perserverative']) cw.writerow([ t[0]['classNum'], t[0]['subject'], totalSetsAttempted, totalCorrect, totalError, totalNonPerserverative, totalNonPerserverativeErrors, totalPerserverative, totalTrials, str(round((totalPerserverative /", "# If the client perserverated to the Other category, Principle isn't set. test[attemptNum]['reasoning']", "principle accordingly checkNewSet(test, attempt['attemptNum']) # 3. Check if the attempt was an error", "if this was not an incorrect answer if test[attemptNum]['correct'] == True: return None", "test[a]['2c'] = False if ( test[a]['sandwiched'] and 'NOT perservative per 2c' not in", "test[attemptNum]['reasoning']: test[attemptNum]['reasoning'] += ' - Attempt is not sandwiched.' return False def isFirstSandwich(test,", "if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ):", "'color' : x.group(1), 'form' : x.group(2), 'number' : x.group(3) } def continuePreviousPresTo(test, attemptNum):", "# Let's look ahead for more indicators! x = a unambiguousMatches = [x,]", "unambiguous self-perserveration after attempt ' + str(test[unambiguousMatches[0]]['attemptNum']) test[unambiguousMatches[2]]['rule_3_3'] = True test[unambiguousMatches[2]]['reasoning'] += '", "stim) return { 'color' : x.group(1), 'form' : x.group(2), 'number' : x.group(3) }", "first', x) while x < len(test)-1: x+=1 # Make sure the potential principle", "each folder in the PATH variable allTests = [] for path, dirs, files", "not set for future attempts. Maybe we also need to have the category", "True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): test[attemptNum]['firstSandwich'] = True test[attemptNum]['perservative'] = True test[attemptNum]['reasoning']", "up to the next set change, to the new principle x = unambiguousMatches[1]", "plaintext reasoning to help verify results # The following are all boolean 'correct'", "not the first set if test[attemptNum]['set'] != 1: return None # Break out", "test[attemptNum]['currentPerservativeTo'] is not None: test[attemptNum]['reasoning'] += ' - Principle already set. No change", "None # Break out if this was not an incorrect answer if test[attemptNum]['correct']", "in the first set 'rule_3_1' : False, # These are to show matches", "' Sandwiched After by attempt ' + str(y)) break y += 1 if", "'form' : x.group(2), 'number' : x.group(3) } def continuePreviousPresTo(test, attemptNum): if attemptNum >", "the Principle principle was established in the first set. if (test[attemptNum]['correct'] == False", "in matches: return False if isCorrect(test, a): return False # Make sure it's", "Rule 3: Principle set to ' + match + ' due to self-perserveration'", "printTest(test) saveResults(test) return test # Iterate through each file in each folder in", "# > The ambiguous response must match the # > perseverated-to principle that", "== False and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break #", "totalCorrect, totalError, totalNonPerserverative, totalNonPerserverativeErrors, totalPerserverative, totalTrials, str(round((totalPerserverative / totalTrials)*100, 2)) + '%', ])", "to help verify results # The following are all boolean 'correct' : False,", "= a['match'] else: n = '' if a['currentPerservativeTo'] != prevPrin: prin = a['currentPerservativeTo']", "= False def isCorrect(test, a): # Determine if a response matches the stimulus", "# It has to have a principle match to be considered perservative at", "t[0]['subject'], totalSetsAttempted, totalCorrect, totalError, totalNonPerserverative, totalNonPerserverativeErrors, totalPerserverative, totalTrials, str(round((totalPerserverative / totalTrials)*100, 2)) +", "False, 'perservative' : False, 'ambiguous' : False, 'sandwiched' : False, 'firstSandwich' : False,", "a['stimulus']['number'] == a['response']['number']: response += 'N* ' else: response += 'N ' if", "'', # Contains plaintext reasoning to help verify results # The following are", "between ' + str(x) + ' and ' + str(y) test[attemptNum]['sandwiched'] = True", "a): return False # Make sure it's an error match = matches[0] #", "Set all responses from the first untill the second response (not # including", "response += 'C ' if a['stimulus']['form'] == a['response']['form']: response += 'F* ' else:", "to see if we found the bread if (test[y]['ambiguous'] == False and test[y]['perservative']", "is chain sandwich perservative per 2c' test[a]['perservative'] = True return True else: test[a]['2c']", "the previous sorting category) # False if not principle has been set yet.", "has a response (' + test[attemptNum]['response'][pers] + ') which matches the principle ('", "+= ' - Principle already set. No change for unambiguous error.' return None", "sandwiches, then 2c doesn't apply if not isSandwiched(test, y): return False y +=", "'+' if a['correct'] else '', a['currentPerservativeTo'], #prin, '+' if a['perservative'] else '', '+'", "containsPrincipleMatch(test, attemptNum): return False # It has to be ambiguous to be considered", "== False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): test[attemptNum]['firstSandwich'] =", "'w', newline='') as csvfile: cw = csv.writer(csvfile) cw.writerow(['#', 'Match', \"Response\", 'Correct', 'Pres-To', 'Perserverative',", "in test[attemptNum]['reasoning']: test[attemptNum]['reasoning'] += ' - Attempt is not sandwiched.' return False def", "need to have the category changer run after this? ##################################### # Set all", "the text files aren't always clean. try: attempt = line.split() test.append({ 'file' :", "a['perservative']: totalPerserverative +=1 if not a['perservative']: totalNonPerserverative +=1 if (not a['perservative'] and not", "[] # Open the file and read it into memory with open (fullpath)", "t[0]['classNum'] + '.csv').st_size == 0: cw.writerow(['Class', 'Subject', 'Sets Attempted', 'Correct', 'Errors', 'Non-Perserverative', 'Non-Perserverative", "a['reasoning'] ]) prevMatch = a['match'] def printTest(test): x = PrettyTable() # x.padding_width =", "sw = '' if a['2c']: chain = '+' else: chain = '' cw.writerow([a['attemptNum'],", "allTests = [] for path, dirs, files in os.walk(PATH): if path == PATH:", "The top level folder which contains the tests PATH = os.getcwd() # r\"C:\\Users\\wyko.terhaar\\Downloads\\Map", "0 # This is the number of ways the response matches the answer", "in the PATH variable allTests = [] for path, dirs, files in os.walk(PATH):", "test[x]['currentPerservativeTo'] in tempMatches: continue # Not currently pers # It's a match! unambiguousMatches.append(test[x]['attemptNum'])", "# First we look backwards to find if an ambiguous, potentially perservative #", "Ensure it is an unambiguous result if isCorrect(test, x): continue # Make sure", "the directory names p = path.split('\\\\') classNum = p[len(p)-1] testNum = p[len(p)-2] allTests.append(analyzeTest(fullpath,", "' else: response += 'F ' if a['stimulus']['number'] == a['response']['number']: response += 'N*", "0: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['currentPerservativeTo'] test[attemptNum]['reasoning'] += 'Principle was set to ' + str(test[attemptNum]['currentPerservativeTo'])", "'Perserverative', 'Trials', '% Perserverative']) cw.writerow([ t[0]['classNum'], t[0]['subject'], totalSetsAttempted, totalCorrect, totalError, totalNonPerserverative, totalNonPerserverativeErrors, totalPerserverative,", "# print{'Added first', x) while x < len(test)-1: x+=1 # Make sure the", "(test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False): for k, v in test[attemptNum]['stimulus'].items(): if", "y = attemptNum + 1 sandwichAfter = False while y < len(test): if", "response) as unscorable x = unambiguousMatches[0] while x < unambiguousMatches[1]: test[x]['currentPerservativeTo'] = None", "if test[attemptNum]['response'][k] == v: matchQuotient += 1 # Mark whether the attempt is", "data with a set of rules for attempt in test: # 1. Set", "'' if a['correct']: corr = '+ ' else: corr = ' ' if", "variable allTests = [] for path, dirs, files in os.walk(PATH): if path ==", "with open('ANALYSIS_' + test[0]['file'] + '.csv', 'w', newline='') as csvfile: cw = csv.writer(csvfile)", "unambiguous # incorrect answer determines the first-set's Principle checkFirstSetPers(test, attempt['attemptNum']) for attempt in", "(fullpath) as f: lines = f.readlines() # Iterate through the test and format", "False, # These are to show matches for Heaton's rule 3 'rule_3_2' :", "attempt in test: # 1. Set the principle the same as last attempt.The", "test[unambiguousMatches[1]]['set']): test[x]['currentPerservativeTo'] = match test[x]['reasoning'] += ' - Rule 3: Principle set to", "Sandwich)', '3.1 (Self-Perserveration)', '3.2', '3.3', 'Reasoning']) prevMatch = '' prevPrin = '' for", "chained perserverations checkChainedSandwich(test, attempt['attemptNum']) # Return the fully populated and analyzed test object", "+=1 if not a['correct']: totalError +=1 totalSetsAttempted = a['set'] # Will end up", "1 while x > 0: if test[x]['set'] != test[attemptNum]['set']: return False # Check", "'firstSandwich' : False, 'set1PrincipleEstablished' : False, # Will change to true if the", "response matches the stimulus on the match criteria match = test[a]['match'] if test[a]['stimulus'][match]", "help verify results # The following are all boolean 'correct' : False, 'perservative'", "'rule_3_1' : False, # These are to show matches for Heaton's rule 3", "path.split('\\\\') classNum = p[len(p)-1] testNum = p[len(p)-2] allTests.append(analyzeTest(fullpath, testNum, classNum)) for t in", "unscorable x = unambiguousMatches[0] while x < unambiguousMatches[1]: test[x]['currentPerservativeTo'] = None test[x]['reasoning'] +=", "p = path.split('\\\\') classNum = p[len(p)-1] testNum = p[len(p)-2] allTests.append(analyzeTest(fullpath, testNum, classNum)) for", "Stores the currently active Pres-To Principle 'reasoning' : '', # Contains plaintext reasoning", "+ response, a['currentPerservativeTo'], #prin, pers, sw, chain, 'X' if a['rule_3_1'] else '', 'X'", "filename for each file # Get the test number and class number from", "found the bread if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo']", "into a new set, and adjust the principle accordingly checkNewSet(test, attempt['attemptNum']) # 3.", "If Principle has not been determined (first set) then the first unambiguous #", "not 'iqdat' in filename: continue fullpath = os.path.join(path, filename) # Get the filename", "break # If any of the preceeding attempts before the \"bread\" aren't also", "error. # First, we check to see if this is an unambiguous error", "import PrettyTable # The top level folder which contains the tests PATH =", "the test and format it for analysis. Skip the headers. lines.pop(0) lineCount =", "files aren't always clean. try: attempt = line.split() test.append({ 'file' : os.path.basename(fullpath), 'attemptNum'", "else: sw = '' if a['2c']: chain = '+' else: chain = ''", "result if isCorrect(test, x): continue # Make sure it's an error if test[x]['currentPerservativeTo']", "in test: # 8. Check if the sandwiched ambiguous answers are the first", "Break out if this was not an incorrect answer if test[attemptNum]['correct'] == True:", "return None # Check if the attempt had an unambiguous incorrect answer. #", "for more indicators! x = a unambiguousMatches = [x,] # We need 3", "SET = 6 STIMULUS = 9 RESPONSE = 10 def saveResults(test): with open('ANALYSIS_'", "principle. # This would suggest that this response is perserverating if test[attemptNum]['stimulus'][pers] ==", "= csv.writer(csvfile) cw.writerow(['#', 'Match', \"Response\", 'Correct', 'Pres-To', 'Perserverative', 'Ambiguous', \"2b (1st Sandwich)\", '2c", "the current Perserveration principle. # This would suggest that this response is perserverating", "If any of the preceeding attempts before the \"bread\" aren't also # sandwiches,", "+ str(y)) # print (test[x]) # print (test[attemptNum]) # print (test[y]) # wait", "if not a['perservative']: totalNonPerserverative +=1 if (not a['perservative'] and not a['correct']): totalNonPerserverativeErrors +=1", "'correct' : False, 'perservative' : False, 'ambiguous' : False, 'sandwiched' : False, 'firstSandwich'", "+ 1 while y < len(test): if test[y]['set'] != test[attemptNum]['set']: return False #", ": '', # Contains plaintext reasoning to help verify results # The following", "attempt is ambiguous if matchQuotient > 1: test[attemptNum]['ambiguous'] = True else: test[attemptNum]['ambiguous'] =", "then the first unambiguous # incorrect answer determines the first-set's Principle checkFirstSetPers(test, attempt['attemptNum'])", "Find self-made perserverations checkSelfPerserveration(test, attempt['attemptNum']) for attempt in test: # 6. If this", "for unambiguous error.' return None # Check if the attempt had an unambiguous", "== test[attemptNum]['currentPerservativeTo'] ): sandwichBefore = True # print (str(attemptNum) + ' Sandwiched Before", "principle matches = getMatches(test, a) if len(matches) != 1: return False # One", "str(y)) # print (test[x]) # print (test[attemptNum]) # print (test[y]) # wait =", "+ str(x)) break x -= 1 if sandwichBefore == False: return False #", "): sandwichBefore = True # print (str(attemptNum) + ' Sandwiched Before by attempt", "if len(unambiguousMatches) != 3: return False # print(str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+", "attempt is NOT perservative per 2c' return False def checkSelfPerserveration(test, a): # 1.", "a first sandwich, matching 2a and 2b. Marking perservative.' return True x-=1 def", "Set the principle the same as last attempt.The current # principle will be", "= True test[attemptNum]['reasoning'] += ' - Attempt is a first sandwich, matching 2a", "'.csv', 'a', newline='') as csvfile: cw = csv.writer(csvfile) if os.stat('SUMMARY_' + t[0]['testNum'] +", "# Will change to true if the principle changed this attempt in the", "match clause) because set was changed.' return True def checkAnswer(test, attemptNum): # Determine", "False if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo']", "rules for attempt in test: # 1. Set the principle the same as", "in # > effect (in our example, Color as defined by # >", "object # printTest(test) saveResults(test) return test # Iterate through each file in each", "'_' + t[0]['classNum'] + '.csv', 'a', newline='') as csvfile: cw = csv.writer(csvfile) if", "y += 1 if sandwichAfter and sandwichBefore: #Mark the sandwich if it hasn't", "test[a]['match'] if test[a]['stimulus'][match] == test[a]['response'][match]: return True else: return False def checkFirstSetPers(test, attemptNum):", "if test[a]['currentPerservativeTo'] in matches: return False if isCorrect(test, a): return False # Make", "False and test[attemptNum]['ambiguous'] == False and test[attemptNum]['currentPerservativeTo'] is not None and test[attemptNum]['set1PrincipleEstablished'] ==", "== a['response']['number']: response += 'N* ' else: response += 'N ' if a['perservative']", "to Other category. No Principle set.' return None def containsPrincipleMatch(test, attemptNum): # Helper", "re, csv, os from prettytable import PrettyTable # The top level folder which", "a['ambiguous']: pers = 'A-Pers' elif a['perservative']: pers = 'U-Pers' else: pers = ''", "return False if isSandwiched(test, x): return False # if test[x]['sandwiched']: return False if", "also # sandwiches, then 2c doesn't apply if not isSandwiched(test, y): return False", "check the # \"sandwich rule.\" isSandwiched(test, attempt['attemptNum']) for attempt in test: # 8.", "the Principle whichever principle the client matched if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous']", "the answer is matchQuotient = 0 # This is the number of ways", "test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: test[attemptNum]['currentPerservativeTo'] = k test[attemptNum]['set1PrincipleEstablished'] = True test[attemptNum]['reasoning'] +=", "test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['currentPerservativeTo'] test[attemptNum]['reasoning'] += 'Principle was set to ' + str(test[attemptNum]['currentPerservativeTo']) +", "for future attempts. Maybe we also need to have the category changer run", "!= 1: return None # Break out if this was not an incorrect", "False and test[attemptNum]['currentPerservativeTo'] is not None and test[attemptNum]['set1PrincipleEstablished'] == False and containsPrincipleMatch(test, attemptNum)", "matches: return False if isCorrect(test, a): return False # Make sure it's an", "(str(attemptNum) + ' Sandwiched Before by attempt ' + str(x)) # print (str(attemptNum)", "in test: # 6. If this was an unambiguous error matching the perservative-to", "check forwards. y = attemptNum + 1 while y < len(test): if test[y]['set']", "+ ', ' + test[0]['file'])) def splitStim(stim): x = re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)', stim) return {", "It has to be ambiguous to be considered for sandwich perseveration if not", "os.path.join(path, filename) # Get the filename for each file # Get the test", "def saveResults(test): with open('ANALYSIS_' + test[0]['file'] + '.csv', 'w', newline='') as csvfile: cw", "sandwichAfter and sandwichBefore: #Mark the sandwich if it hasn't already been done if", "x+=1 ################################# # Principle is not set for future attempts. Maybe we also", ": int(attempt[SUBJECT]), 'set' : int(attempt[SET]), 'match' : attempt[MATCH], 'stimulus' : splitStim(attempt[STIMULUS]), 'response' :", "One match for an unambiguous result if test[a]['currentPerservativeTo'] in matches: return False if", "for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: matchQuotient += 1 #", "0: if test[x]['set'] != test[attemptNum]['set']: break if (test[x]['ambiguous'] == False and test[x]['perservative'] ==", "'Pers', \"2b\", '2c', '3.1', '3.2', '3.3'] prevMatch = '' prevPrin = '' for", "end up being the final set if a['perservative']: totalPerserverative +=1 if not a['perservative']:", "# 4. If Principle has not been determined (first set) then the first", "top level folder which contains the tests PATH = os.getcwd() # r\"C:\\Users\\wyko.terhaar\\Downloads\\Map voor", "= test[attemptNum]['currentPerservativeTo'] # Check to see if the response matches the stimulus on", "first to second responses' # print (test[x]) x+=1 ################################# # Principle is not", "def checkSelfPerserveration(test, a): # 1. The client must make 3 unambiguous errors to", "if the attempt had an unambiguous incorrect answer. # If so, set the", "+= 'N ' if a['perservative'] and a['ambiguous']: pers = 'A-Pers' elif a['perservative']: pers", "False x = attemptNum - 1 while x > 0: if test[x]['set'] !=", "if isCorrect(test, a): return False # Make sure it's an error match =", "out if this was not an incorrect answer if test[attemptNum]['correct'] == True: return", "Principle isn't set. test[attemptNum]['reasoning'] += ' - Client perserverated to Other category. No", "adjust the principle accordingly checkNewSet(test, attempt['attemptNum']) # 3. Check if the attempt was", "pers = 'U-Pers' else: pers = '' if a['match'] != prevMatch: n =", "perserverations checkSelfPerserveration(test, attempt['attemptNum']) for attempt in test: # 6. If this was an", "+= 1 if sandwichAfter and sandwichBefore: #Mark the sandwich if it hasn't already", "# # 3. The new principle becomes active to register perserverations only #", "ambiguous perserverations. Here we check the # \"sandwich rule.\" isSandwiched(test, attempt['attemptNum']) for attempt", "Determine how ambiguous the answer is matchQuotient = 0 # This is the", "+ ' in file: \\n' + fullpath) lineCount += 1 # First pass:", "response must match the # > perseverated-to principle that is currently in #", "test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): test[attemptNum]['firstSandwich'] = True test[attemptNum]['perservative'] =", "################################# # Principle is not set for future attempts. Maybe we also need", "}) except: print ('There was an error reading line ' + str(lineCount) +", "for attempt in test: # 9. Check rule 2c for chained perserverations checkChainedSandwich(test,", "# it changes in a subsequent rule. continuePreviousPresTo(test, attempt['attemptNum']) # 2. Check if", "of rules for attempt in test: # 1. Set the principle the same", "a['rule_3_3'] else '', a['reasoning'] ]) prevMatch = a['match'] def printTest(test): x = PrettyTable()", "set match clause) because set was changed.' return True def checkAnswer(test, attemptNum): #", "attempt['attemptNum']) for attempt in test: # 7. Now we start looking for ambiguous", "print('Holy shit, we found one on attempt ', attemptNum) # print (test[attemptNum]) return", "else: test[attemptNum]['correct'] = False def isCorrect(test, a): # Determine if a response matches", "error reading line ' + str(lineCount) + ' in file: \\n' + fullpath)", "principle x = attemptNum - 1 sandwichBefore = False while x > 0:", "files: if '.py' in filename: continue # Skip any python files if 'ANALYSIS'", "currently in # > effect (in our example, Color as defined by #", "len(test) and test[x]['set'] == test[unambiguousMatches[1]]['set']): test[x]['currentPerservativeTo'] = match test[x]['reasoning'] += ' - Rule", "'Perserverative', 'Ambiguous', \"2b (1st Sandwich)\", '2c (Chained Sandwich)', '3.1 (Self-Perserveration)', '3.2', '3.3', 'Reasoning'])", "# One match for an unambiguous result if test[a]['currentPerservativeTo'] in matches: return False", "First unambiguous self-perserveration' test[unambiguousMatches[1]]['rule_3_2'] = True test[unambiguousMatches[1]]['reasoning'] += ' - Rule 3: Second", "client must make 3 unambiguous errors to a sorting principle # which is", "Split the test report into an array of Dicts # Added some error", "attempt['attemptNum']) for attempt in test: # 9. Check rule 2c for chained perserverations", "to the new principle x = unambiguousMatches[1] while (x < len(test) and test[x]['set']", "way and then loop again checkUnambiguousPerserveration(test, attempt['attemptNum']) for attempt in test: # 7.", "the first-set's Principle checkFirstSetPers(test, attempt['attemptNum']) for attempt in test: # 5. Heaton's rule", "not in test[a]['reasoning'] ): test[a]['reasoning'] += ' - Sandwiched attempt is NOT perservative", "= test[a]['match'] if test[a]['stimulus'][match] == test[a]['response'][match]: return True else: return False def checkFirstSetPers(test,", "# match this sorting principle. # # 3. The new principle becomes active", "and sandwichBefore: #Mark the sandwich if it hasn't already been done if not", "response, '+' if a['correct'] else '', a['currentPerservativeTo'], #prin, '+' if a['perservative'] else '',", "PATH = os.getcwd() # r\"C:\\Users\\wyko.terhaar\\Downloads\\Map voor Wyko\\raw\" # Variables which contain the column", "if the answer is correct if isCorrect(test, attemptNum): test[attemptNum]['correct'] = True else: test[attemptNum]['correct']", "!= test[attemptNum]['set']: break if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo']", "Sandwich)\", '2c (Chained Sandwich)', '3.1 (Self-Perserveration)', '3.2', '3.3', 'Reasoning']) prevMatch = '' prevPrin", "'C* ' else: response += 'C ' if a['stimulus']['form'] == a['response']['form']: response +=", "return True # If the client perserverated to the Other category, Principle isn't", "names p = path.split('\\\\') classNum = p[len(p)-1] testNum = p[len(p)-2] allTests.append(analyzeTest(fullpath, testNum, classNum))", "print ('There was an error reading line ' + str(lineCount) + ' in", "the intermediate results tempMatches = getMatches(test, x) if not match in tempMatches: return", "attempt['attemptNum']) # Return the fully populated and analyzed test object # printTest(test) saveResults(test)", "test[attemptNum]['reasoning'] += ' - Principle already set. No change for unambiguous error.' return", "Set to unscorable for first to second responses' # print (test[x]) x+=1 #################################", "csvfile: cw = csv.writer(csvfile) if os.stat('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum'] +", "testNum, classNum): test = [] # Open the file and read it into", "a) if len(matches) != 1: return False # One match for an unambiguous", "1: return False # One match for an unambiguous result if test[a]['currentPerservativeTo'] in", "6 STIMULUS = 9 RESPONSE = 10 def saveResults(test): with open('ANALYSIS_' + test[0]['file']", "Rule 3: First unambiguous self-perserveration' test[unambiguousMatches[1]]['rule_3_2'] = True test[unambiguousMatches[1]]['reasoning'] += ' - Rule", ": False, 'perservative' : False, 'ambiguous' : False, 'sandwiched' : False, 'firstSandwich' :", "' else: response += 'C ' if a['stimulus']['form'] == a['response']['form']: response += 'F*", "'Attempt is not sandwiched' in test[attemptNum]['reasoning']: test[attemptNum]['reasoning'] += ' - Attempt is not", "if test[y]['set'] != test[attemptNum]['set']: break if (test[y]['ambiguous'] == False and test[y]['perservative'] == True", "'+' else: chain = '' x.add_row([a['attemptNum'], a['match'], #n, corr + response, a['currentPerservativeTo'], #prin,", "is matchQuotient = 0 # This is the number of ways the response", "whether the attempt is ambiguous if matchQuotient > 1: test[attemptNum]['ambiguous'] = True else:", "'', 'X' if a['rule_3_2'] else '', 'X' if a['rule_3_3'] else '', ]) prevMatch", "'C ' if a['stimulus']['form'] == a['response']['form']: response += 'F* ' else: response +=", "# False if not principle has been set yet. if test[attemptNum]['currentPerservativeTo'] is None:", "all responses from the first untill the second response (not # including the", "nor currently perserverative. # # 2. All responses between the first and third", "NOT perservative per 2c' return False def checkSelfPerserveration(test, a): # 1. The client", "active Pres-To Principle 'reasoning' : '', # Contains plaintext reasoning to help verify", "+ fullpath) lineCount += 1 # First pass: Analyze the data with a", "t: if a['correct']: totalCorrect +=1 if not a['correct']: totalError +=1 totalSetsAttempted = a['set']", "a principle match to be considered perservative at all if not containsPrincipleMatch(test, attemptNum):", "x) while x < len(test)-1: x+=1 # Make sure the potential principle is", "= False # Determine if the answer is correct if isCorrect(test, attemptNum): test[attemptNum]['correct']", "# Mark whether the attempt is ambiguous if matchQuotient > 1: test[attemptNum]['ambiguous'] =", "def containsPrincipleMatch(test, attemptNum): # Helper function which satisfies Heaton rule 2a: # >", "unambiguous self-perserveration' # Set all responses from the first untill the second response", "unambiguous response for the same principle x = attemptNum - 1 sandwichBefore =", "# Stores the currently active Pres-To Principle 'reasoning' : '', # Contains plaintext", "the same principle x = attemptNum - 1 sandwichBefore = False while x", "for first to second responses' # print (test[x]) x+=1 ################################# # Principle is", "covers the intermediate results tempMatches = getMatches(test, x) if not match in tempMatches:", "isChainedSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return False if isFirstSandwich(test, attemptNum): return False", "= ['#', \"Match\", \"Matched\", 'Pres-To', 'Pers', \"2b\", '2c', '3.1', '3.2', '3.3'] prevMatch =", "'F* ' else: response += 'F ' if a['stimulus']['number'] == a['response']['number']: response +=", "two unambiguous errors to the new, not currently # perserverative principle if len(tempMatches)", "which the Principle principle was established in the first set. if (test[attemptNum]['correct'] ==", "tempMatches: continue # Not currently pers # It's a match! unambiguousMatches.append(test[x]['attemptNum']) if len(unambiguousMatches)", "import re, csv, os from prettytable import PrettyTable # The top level folder", "= unambiguousMatches[0] while x < unambiguousMatches[1]: test[x]['currentPerservativeTo'] = None test[x]['reasoning'] += ' -", "python files if 'ANALYSIS' in filename: continue # Skip any generated analysis files", "import with_statement import re, csv, os from prettytable import PrettyTable # The top", "# sandwiches, then 2c doesn't apply if not isSandwiched(test, x): return False x", "test[a]['sandwiched'] and 'NOT perservative per 2c' not in test[a]['reasoning'] ): test[a]['reasoning'] += '", "match + ' due to self-perserveration' # print(\"Test \", x, \" principle set", "test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): test[attemptNum]['firstSandwich'] = True test[attemptNum]['perservative'] = True test[attemptNum]['reasoning'] += '", "> perseverated-to principle that is currently in # > effect (in our example,", "start looking for ambiguous perserverations. Here we check the # \"sandwich rule.\" isSandwiched(test,", "[] for path, dirs, files in os.walk(PATH): if path == PATH: continue #", "perserverations only # after the second unambiguous error. # First, we check to", "while x < len(test)-1: x+=1 # Make sure the potential principle is matched", "', ' + str(test[0]['subject']) + ', ' + test[0]['file'])) def splitStim(stim): x =", "the headers. lines.pop(0) lineCount = 0 for line in lines: # Split the", "test[attemptNum-1]['currentPerservativeTo'] test[attemptNum]['reasoning'] += 'Principle was set to ' + str(test[attemptNum]['currentPerservativeTo']) + ' to", "\"bread\" aren't also # sandwiches, then 2c doesn't apply if not isSandwiched(test, x):", "here, then we know the attempt is a candidate for the first indicator.", "any of the preceeding attempts before the \"bread\" aren't also # sandwiches, then", "0: if test[x]['set'] != test[attemptNum]['set']: return False if isSandwiched(test, x): return False #", "again checkUnambiguousPerserveration(test, attempt['attemptNum']) for attempt in test: # 7. Now we start looking", "wait = input('') return True else: if not 'Attempt is not sandwiched' in", "in test: # 5. Heaton's rule 3: Find self-made perserverations checkSelfPerserveration(test, attempt['attemptNum']) for", "# Variables which contain the column numbers, used for readability SUBJECT = 3", "a['rule_3_3'] else '', ]) prevMatch = a['match'] print(x.get_string(title= str(test[0]['classNum']) + ', ' +", "unambiguousMatches, '\\n') test[unambiguousMatches[0]]['rule_3_1'] = True test[unambiguousMatches[0]]['reasoning'] += ' - Rule 3: First unambiguous", "# Check to see if we found the bread if (test[y]['ambiguous'] == False", "MATCH = 5 SET = 6 STIMULUS = 9 RESPONSE = 10 def", "prin = '' if a['correct']: corr = '+ ' else: corr = '", "'+' if a['ambiguous'] else '', sw, chain, 'X' if a['rule_3_1'] else '', 'X'", "1. The client must make 3 unambiguous errors to a sorting principle #", "re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)', stim) return { 'color' : x.group(1), 'form' : x.group(2), 'number' : x.group(3)", "+ str(test[0]['subject']), '\\n', unambiguousMatches, '\\n') test[unambiguousMatches[0]]['rule_3_1'] = True test[unambiguousMatches[0]]['reasoning'] += ' - Rule", "False y += 1 # print('Holy shit, we found one on attempt ',", "(x < len(test) and test[x]['set'] == test[unambiguousMatches[1]]['set']): test[x]['currentPerservativeTo'] = match test[x]['reasoning'] += '", "is None: return False pers = test[attemptNum]['currentPerservativeTo'] # Check to see if the", "same as the last attempt, unless # it changes in a subsequent rule.", "None def checkNewSet(test, attemptNum): # The very first attempt will never have a", "start of test.' return None def checkNewSet(test, attemptNum): # The very first attempt", "< unambiguousMatches[1]: test[x]['currentPerservativeTo'] = None test[x]['reasoning'] += ' - Rule 3: Set to", "attemptNum): if attemptNum > 0: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['currentPerservativeTo'] test[attemptNum]['reasoning'] += 'Principle was set", "test object # printTest(test) saveResults(test) return test # Iterate through each file in", "isChainedSandwich(test, a): test[a]['2c'] = True test[a]['reasoning'] += ' - Attempt is chain sandwich", "test.' return None def checkNewSet(test, attemptNum): # The very first attempt will never", "of Dicts # Added some error handling because the text files aren't always", "sure the potential principle is matched in all subsequent attempts # This covers", "run after this? ##################################### # Set all the rest, up to the next", "It's a match! unambiguousMatches.append(test[x]['attemptNum']) if len(unambiguousMatches) == 3: break if len(unambiguousMatches) != 3:", "allTests: totalCorrect = 0 totalError = 0 totalSetsAttempted = 0 totalNonPerserverative = 0", "return True else: test[a]['2c'] = False if ( test[a]['sandwiched'] and 'NOT perservative per", "if a['rule_3_2'] else '', 'X' if a['rule_3_3'] else '', ]) prevMatch = a['match']", "if test[y]['set'] != test[attemptNum]['set']: return False # Check to see if we found", "(not # including the second response) as unscorable x = unambiguousMatches[0] while x", "a['correct'] else '', a['currentPerservativeTo'], #prin, '+' if a['perservative'] else '', '+' if a['ambiguous']", "this attempt (on the first set). # We have to know this for", "to the Other category, Principle isn't set. test[attemptNum]['reasoning'] += ' - Client perserverated", "unambiguous error.' return None # Check if the attempt had an unambiguous incorrect", "+= ' - Rule 3: Set to unscorable for first to second responses'", "'F ' if a['stimulus']['number'] == a['response']['number']: response += 'N* ' else: response +=", "and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If any", "0 totalTrials = 0 for a in t: if a['correct']: totalCorrect +=1 if", "' - Attempt ' + str(attemptNum) + ' is \"sandwiched\" between ' +", "!= 1: return False # One match for an unambiguous result if test[a]['currentPerservativeTo']", "if a['2c']: chain = '+' else: chain = '' cw.writerow([a['attemptNum'], a['match'], #n, response,", "# Break out if this is not the first set if test[attemptNum]['set'] !=", "# # 2. All responses between the first and third unambiguous response must", "+= ' - Attempt has a response (' + test[attemptNum]['response'][pers] + ') which", "changer run after this? ##################################### # Set all the rest, up to the", "test[attemptNum]['reasoning'] += 'Principle is none due to start of test.' return None def", "'Principle is none due to start of test.' return None def checkNewSet(test, attemptNum):", "'' cw.writerow([a['attemptNum'], a['match'], #n, response, '+' if a['correct'] else '', a['currentPerservativeTo'], #prin, '+'", "a['rule_3_2'] else '', 'X' if a['rule_3_3'] else '', ]) prevMatch = a['match'] print(x.get_string(title=", "we check forwards. y = attemptNum + 1 while y < len(test): if", "a): if isChainedSandwich(test, a): test[a]['2c'] = True test[a]['reasoning'] += ' - Attempt is", "including the second response) as unscorable x = unambiguousMatches[0] while x < unambiguousMatches[1]:", "chain, 'X' if a['rule_3_1'] else '', 'X' if a['rule_3_2'] else '', 'X' if", "if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False): for k, v in test[attemptNum]['stimulus'].items():", "test[a]['reasoning'] += ' - Attempt is chain sandwich perservative per 2c' test[a]['perservative'] =", "= 0 for a in t: if a['correct']: totalCorrect +=1 if not a['correct']:", "# This would suggest that this response is perserverating if test[attemptNum]['stimulus'][pers] == test[attemptNum]['response'][pers]:", "Will change to true if the principle changed this attempt in the first", "sw, chain, 'X' if a['rule_3_1'] else '', 'X' if a['rule_3_2'] else '', 'X'", "'3.2', '3.3'] prevMatch = '' prevPrin = '' for a in test: response", "False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichBefore = True", "test[a]['stimulus'].items(): if test[a]['response'][k] == v: matches.append(k) return matches def checkUnambiguousPerserveration(test, attemptNum): # Check", "ambiguous to be considered for sandwich perseveration if not test[attemptNum]['ambiguous']: return False #", "t[0]['classNum'], t[0]['subject'], totalSetsAttempted, totalCorrect, totalError, totalNonPerserverative, totalNonPerserverativeErrors, totalPerserverative, totalTrials, str(round((totalPerserverative / totalTrials)*100, 2))", "after this? ##################################### # Set all the rest, up to the next set", "an incorrect answer if test[attemptNum]['correct'] == True: return None if test[attemptNum]['currentPerservativeTo'] is not", "by attempt ' + str(y)) # print (test[x]) # print (test[attemptNum]) # print", "' - Principle was set to ' + str(test[attemptNum]['currentPerservativeTo']) + ' (last set", "+= 1 # Mark whether the attempt is ambiguous if matchQuotient > 1:", "neither correct nor currently perserverative. # # 2. All responses between the first", "len(test): if test[y]['set'] != test[attemptNum]['set']: break if (test[y]['ambiguous'] == False and test[y]['perservative'] ==", "for ambiguous perserverations. Here we check the # \"sandwich rule.\" isSandwiched(test, attempt['attemptNum']) for", "False # First we look backwards to find if an ambiguous, potentially perservative", "splitStim(attempt[RESPONSE]), 'testNum' : testNum, '2c' : '', 'classNum' : classNum, 'currentPerservativeTo' : None,", "# test[attemptNum]['reasoning'] += ' - Attempt has a response (' + test[attemptNum]['response'][pers] +", "else: return False def getMatches(test, a): matches = [] for k, v in", "as ' + k + ' from first unambiguous error.' return True #", "response was sandwiched by an unambiguous response for the same principle x =", "apply if not isSandwiched(test, x): return False x -= 1 # Next we", "# Check if the attempt had an unambiguous incorrect answer. Skip the answer", "'' if a['match'] != prevMatch: n = a['match'] else: n = '' if", "check forwards. y = attemptNum + 1 sandwichAfter = False while y <", "If we get here, then we know the attempt is a candidate for", "'NOT perservative per 2c' not in test[a]['reasoning'] ): test[a]['reasoning'] += ' - Sandwiched", "prevMatch = a['match'] def printTest(test): x = PrettyTable() # x.padding_width = 10 x.left_padding_width", "for sandwich perseveration if not test[attemptNum]['ambiguous']: return False # First we look backwards", "an error if test[x]['currentPerservativeTo'] in tempMatches: continue # Not currently pers # It's", "pattern.' return True else: test[attemptNum]['reasoning'] += 'Principle is none due to start of", "== False and test[attemptNum]['ambiguous'] == False and test[attemptNum]['currentPerservativeTo'] is not None and test[attemptNum]['set1PrincipleEstablished']", "the current principle and nothing else.' test[attemptNum]['perservative'] = True return True else: return", "Principle set to ' + match + ' due to self-perserveration' # print(\"Test", "attemptNum): # Determine how ambiguous the answer is matchQuotient = 0 # This", "matched if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] == False): for k, v in", "> 0: if test[x]['set'] != test[attemptNum]['set']: return False if isSandwiched(test, x): return False", "a unambiguousMatches = [x,] # We need 3 to confirm self-perserveration # print{'Added", "to confirm self-perserveration # print{'Added first', x) while x < len(test)-1: x+=1 #", "for path, dirs, files in os.walk(PATH): if path == PATH: continue # Skip", "= '' if a['stimulus']['color'] == a['response']['color']: response += 'C* ' else: response +=", "== test[attemptNum]['currentPerservativeTo'] ): break # If any of the preceeding attempts before the", "lines: # Split the test report into an array of Dicts # Added", "'set' : int(attempt[SET]), 'match' : attempt[MATCH], 'stimulus' : splitStim(attempt[STIMULUS]), 'response' : splitStim(attempt[RESPONSE]), 'testNum'", "in test: # 9. Check rule 2c for chained perserverations checkChainedSandwich(test, attempt['attemptNum']) #", "== v: matchQuotient += 1 # Mark whether the attempt is ambiguous if", "1 x.right_padding_width = 1 x.field_names = ['#', \"Match\", \"Matched\", 'Pres-To', 'Pers', \"2b\", '2c',", "Attempt is not sandwiched.' return False def isFirstSandwich(test, attemptNum): if not isSandwiched(test, attemptNum):", "active to register perserverations only # after the second unambiguous error. # First,", "- Rule 3: First unambiguous self-perserveration' test[unambiguousMatches[1]]['rule_3_2'] = True test[unambiguousMatches[1]]['reasoning'] += ' -", ": attempt[MATCH], 'stimulus' : splitStim(attempt[STIMULUS]), 'response' : splitStim(attempt[RESPONSE]), 'testNum' : testNum, '2c' :", "matches = getMatches(test, a) if len(matches) != 1: return False # One match", "= matches[0] # If we get here, then we know the attempt is", "str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']) + ', '", "' - Attempt has a response (' + test[attemptNum]['response'][pers] + ') which matches", "principle if len(tempMatches) != 1: continue # Ensure it is an unambiguous result", "matches[0] # If we get here, then we know the attempt is a", "was established in the first set. if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous'] ==", "if not isSandwiched(test, y): return False y += 1 # print('Holy shit, we", "which matches the principle (' + pers + ')' return True else: return", "= 9 RESPONSE = 10 def saveResults(test): with open('ANALYSIS_' + test[0]['file'] + '.csv',", "text files aren't always clean. try: attempt = line.split() test.append({ 'file' : os.path.basename(fullpath),", "attempts # This covers the intermediate results tempMatches = getMatches(test, x) if not", "After by attempt ' + str(y)) break y += 1 if sandwichAfter and", "changed this attempt in the first set 'rule_3_1' : False, # These are", "looking for ambiguous perserverations. Here we check the # \"sandwich rule.\" isSandwiched(test, attempt['attemptNum'])", "else '', a['currentPerservativeTo'], #prin, '+' if a['perservative'] else '', '+' if a['ambiguous'] else", "+ '_' + t[0]['classNum'] + '.csv', 'a', newline='') as csvfile: cw = csv.writer(csvfile)", "if a['firstSandwich']: sw= '+' else: sw = '' if a['2c']: chain = '+'", "# These are to show matches for Heaton's rule 3 'rule_3_2' : False,", "is not None and test[attemptNum]['set1PrincipleEstablished'] == False and containsPrincipleMatch(test, attemptNum) ): test[attemptNum]['reasoning'] +=", "# Contains plaintext reasoning to help verify results # The following are all", "def getMatches(test, a): matches = [] for k, v in test[a]['stimulus'].items(): if test[a]['response'][k]", "the more complicated # tests, so we finish the loop this way and", "= a['match'] print(x.get_string(title= str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject'])", "a): # 1. The client must make 3 unambiguous errors to a sorting", "test[attemptNum]['ambiguous'] = True else: test[attemptNum]['ambiguous'] = False # Determine if the answer is", "return True def checkAnswer(test, attemptNum): # Determine how ambiguous the answer is matchQuotient", "= [] for path, dirs, files in os.walk(PATH): if path == PATH: continue", "# x.padding_width = 10 x.left_padding_width = 1 x.right_padding_width = 1 x.field_names = ['#',", "sorting category) # False if not principle has been set yet. if test[attemptNum]['currentPerservativeTo']", "analysis files # if not 'iqdat' in filename: continue fullpath = os.path.join(path, filename)", "classNum = p[len(p)-1] testNum = p[len(p)-2] allTests.append(analyzeTest(fullpath, testNum, classNum)) for t in allTests:", "attempt['attemptNum']) # 2. Check if we just moved into a new set, and", "# print(str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']), '\\n', unambiguousMatches,", "responses' # print (test[x]) x+=1 ################################# # Principle is not set for future", "answer is correct if isCorrect(test, attemptNum): test[attemptNum]['correct'] = True else: test[attemptNum]['correct'] = False", "ambiguous if matchQuotient > 1: test[attemptNum]['ambiguous'] = True else: test[attemptNum]['ambiguous'] = False #", "int(attempt[SET]), 'match' : attempt[MATCH], 'stimulus' : splitStim(attempt[STIMULUS]), 'response' : splitStim(attempt[RESPONSE]), 'testNum' : testNum,", "return False # Check to see if we found the bread if (test[y]['ambiguous']", "attempt will never have a Principle if attemptNum == 0: return None if", "False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): test[attemptNum]['firstSandwich'] = True", "Maybe we also need to have the category changer run after this? #####################################", "test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichBefore = True # print", "if isFirstSandwich(test, attemptNum): return False x = attemptNum - 1 while x >", "aren't always clean. try: attempt = line.split() test.append({ 'file' : os.path.basename(fullpath), 'attemptNum' :", "cw = csv.writer(csvfile) if os.stat('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv').st_size", "for analysis. Skip the headers. lines.pop(0) lineCount = 0 for line in lines:", "x): continue # Make sure it's an error if test[x]['currentPerservativeTo'] in tempMatches: continue", "readability SUBJECT = 3 MATCH = 5 SET = 6 STIMULUS = 9", "test[attemptNum]['currentPerservativeTo'] ): sandwichBefore = True # print (str(attemptNum) + ' Sandwiched Before by", "test.append({ 'file' : os.path.basename(fullpath), 'attemptNum' : lineCount, 'subject' : int(attempt[SUBJECT]), 'set' : int(attempt[SET]),", "for the first indicator. # Let's look ahead for more indicators! x =", "]) prevMatch = a['match'] def printTest(test): x = PrettyTable() # x.padding_width = 10", "attemptNum): # Check if the attempt had an unambiguous incorrect answer. Skip the", "rule 2c for chained perserverations checkChainedSandwich(test, attempt['attemptNum']) # Return the fully populated and", "'' if a['2c']: chain = '+' else: chain = '' x.add_row([a['attemptNum'], a['match'], #n,", "+ '.csv', 'a', newline='') as csvfile: cw = csv.writer(csvfile) if os.stat('SUMMARY_' + t[0]['testNum']", "principle set to \", match) x+=1 def analyzeTest(fullpath, testNum, classNum): test = []", "3: Second unambiguous self-perserveration after attempt ' + str(test[unambiguousMatches[0]]['attemptNum']) test[unambiguousMatches[2]]['rule_3_3'] = True test[unambiguousMatches[2]]['reasoning']", "in tempMatches: continue # Not currently pers # It's a match! unambiguousMatches.append(test[x]['attemptNum']) if", "'reasoning' : '', # Contains plaintext reasoning to help verify results # The", "totalCorrect +=1 if not a['correct']: totalError +=1 totalSetsAttempted = a['set'] # Will end", "# First pass: Analyze the data with a set of rules for attempt", "PATH: continue # Skip the root for filename in files: if '.py' in", "cw.writerow([ t[0]['classNum'], t[0]['subject'], totalSetsAttempted, totalCorrect, totalError, totalNonPerserverative, totalNonPerserverativeErrors, totalPerserverative, totalTrials, str(round((totalPerserverative / totalTrials)*100,", "only # after the second unambiguous error. # First, we check to see", "'Trials', '% Perserverative']) cw.writerow([ t[0]['classNum'], t[0]['subject'], totalSetsAttempted, totalCorrect, totalError, totalNonPerserverative, totalNonPerserverativeErrors, totalPerserverative, totalTrials,", "return True else: return False def isSandwiched(test, attemptNum): # It has to have", "nothing else.' test[attemptNum]['perservative'] = True return True else: return False def isSandwiched(test, attemptNum):", "with open (fullpath) as f: lines = f.readlines() # Iterate through the test", "attemptNum) ): test[attemptNum]['reasoning'] += ' - Attempt is unambiguously perservative due to matching", "' in file: \\n' + fullpath) lineCount += 1 # First pass: Analyze", "line.split() test.append({ 'file' : os.path.basename(fullpath), 'attemptNum' : lineCount, 'subject' : int(attempt[SUBJECT]), 'set' :", "y = attemptNum + 1 while y < len(test): if test[y]['set'] != test[attemptNum]['set']:", "was set to ' + str(test[attemptNum]['currentPerservativeTo']) + ' (last set match clause) because", "we get here, then we know the attempt is a candidate for the", "can go on to the more complicated # tests, so we finish the", "had an unambiguous incorrect answer. Skip the answer # in which the Principle", "> 0: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['currentPerservativeTo'] test[attemptNum]['reasoning'] += 'Principle was set to ' +", "must match the # > perseverated-to principle that is currently in # >", "False # It has to be ambiguous to be considered for sandwich perseveration", "test[y]['set'] != test[attemptNum]['set']: return False # Check to see if we found the", "to second responses' # print (test[x]) x+=1 ################################# # Principle is not set", "6. If this was an unambiguous error matching the perservative-to rule, AND #", "in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: matchQuotient += 1 # Mark whether the", "correct if isCorrect(test, attemptNum): test[attemptNum]['correct'] = True else: test[attemptNum]['correct'] = False def isCorrect(test,", "response += 'C* ' else: response += 'C ' if a['stimulus']['form'] == a['response']['form']:", "self-perserveration after attempt ' + str(test[unambiguousMatches[0]]['attemptNum']) test[unambiguousMatches[2]]['rule_3_3'] = True test[unambiguousMatches[2]]['reasoning'] += ' -", "if isCorrect(test, attemptNum): test[attemptNum]['correct'] = True else: test[attemptNum]['correct'] = False def isCorrect(test, a):", "the fully populated and analyzed test object # printTest(test) saveResults(test) return test #", "# print (str(attemptNum) + ' Sandwiched Before by attempt ' + str(x)) #", "if not containsPrincipleMatch(test, attemptNum): return False # It has to be ambiguous to", "intermediate results tempMatches = getMatches(test, x) if not match in tempMatches: return False", "matches the answer for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: matchQuotient", "prevPrin: prin = a['currentPerservativeTo'] prevPrin = prin else: prin = '' if a['correct']:", "If so, set the Principle whichever principle the client matched if (test[attemptNum]['correct'] ==", "self-perserveration' # Set all responses from the first untill the second response (not", "> the previous sorting category) # False if not principle has been set", "'ANALYSIS' in filename: continue # Skip any generated analysis files # if not", ": False, 'firstSandwich' : False, 'set1PrincipleEstablished' : False, # Will change to true", "Attempted', 'Correct', 'Errors', 'Non-Perserverative', 'Non-Perserverative Errors', 'Perserverative', 'Trials', '% Perserverative']) cw.writerow([ t[0]['classNum'], t[0]['subject'],", "We have to know this for every rule before we can go on", "+ str(test[attemptNum]['currentPerservativeTo']) + ' to continue previous pattern.' return True else: test[attemptNum]['reasoning'] +=", "False # Make sure it's an error match = matches[0] # If we", "x = re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)', stim) return { 'color' : x.group(1), 'form' : x.group(2), 'number'", "test[x]['set'] != test[attemptNum]['set']: break if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and", "for attempt in test: # 6. If this was an unambiguous error matching", "= True test[unambiguousMatches[0]]['reasoning'] += ' - Rule 3: First unambiguous self-perserveration' test[unambiguousMatches[1]]['rule_3_2'] =", "== a['response']['color']: response += 'C* ' else: response += 'C ' if a['stimulus']['form']", "and not a['correct']): totalNonPerserverativeErrors +=1 totalTrials+=1 with open('SUMMARY_' + t[0]['testNum'] + '_' +", "' is \"sandwiched\" between ' + str(x) + ' and ' + str(y)", "match this sorting principle. # # 3. The new principle becomes active to", "= [] # Open the file and read it into memory with open", ": os.path.basename(fullpath), 'attemptNum' : lineCount, 'subject' : int(attempt[SUBJECT]), 'set' : int(attempt[SET]), 'match' :", "def checkUnambiguousPerserveration(test, attemptNum): # Check if the attempt had an unambiguous incorrect answer.", "# Make sure the potential principle is matched in all subsequent attempts #", "and test[x]['set'] == test[unambiguousMatches[1]]['set']): test[x]['currentPerservativeTo'] = match test[x]['reasoning'] += ' - Rule 3:", "+=1 totalSetsAttempted = a['set'] # Will end up being the final set if", "attempt had an unambiguous incorrect answer. Skip the answer # in which the", "None: test[attemptNum]['reasoning'] += ' - Principle already set. No change for unambiguous error.'", "return False # print(str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']),", "set yet. if test[attemptNum]['currentPerservativeTo'] is None: return False pers = test[attemptNum]['currentPerservativeTo'] # Check", "'' x.add_row([a['attemptNum'], a['match'], #n, corr + response, a['currentPerservativeTo'], #prin, pers, sw, chain, 'X'", "str(x)) # print (str(attemptNum) + ' Sandwiched After by attempt ' + str(y))", "= 1 x.right_padding_width = 1 x.field_names = ['#', \"Match\", \"Matched\", 'Pres-To', 'Pers', \"2b\",", "'file' : os.path.basename(fullpath), 'attemptNum' : lineCount, 'subject' : int(attempt[SUBJECT]), 'set' : int(attempt[SET]), 'match'", "5 SET = 6 STIMULUS = 9 RESPONSE = 10 def saveResults(test): with", "from __future__ import with_statement import re, csv, os from prettytable import PrettyTable #", "principle # which is neither correct nor currently perserverative. # # 2. All", "due to matching the current principle and nothing else.' test[attemptNum]['perservative'] = True return", "attempt['attemptNum']) # 4. If Principle has not been determined (first set) then the", "' - Rule 3: Final unambiguous self-perserveration' # Set all responses from the", "the stimulus on the match criteria match = test[a]['match'] if test[a]['stimulus'][match] == test[a]['response'][match]:", "return None # Break out if this was not an incorrect answer if", "10 def saveResults(test): with open('ANALYSIS_' + test[0]['file'] + '.csv', 'w', newline='') as csvfile:", "of ways the response matches the answer for k, v in test[attemptNum]['stimulus'].items(): if", "It has to have a principle match to be considered perservative at all", "(test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break", "else '', 'X' if a['rule_3_2'] else '', 'X' if a['rule_3_3'] else '', a['reasoning']", "x.field_names = ['#', \"Match\", \"Matched\", 'Pres-To', 'Pers', \"2b\", '2c', '3.1', '3.2', '3.3'] prevMatch", "checkSelfPerserveration(test, attempt['attemptNum']) for attempt in test: # 6. If this was an unambiguous", ": False, }) except: print ('There was an error reading line ' +", "test and format it for analysis. Skip the headers. lines.pop(0) lineCount = 0", "None # Check if the attempt had an unambiguous incorrect answer. # If", "False, 'set1PrincipleEstablished' : False, # Will change to true if the principle changed", "x): return False # if test[x]['sandwiched']: return False if (test[x]['ambiguous'] == False and", "rule before we can go on to the more complicated # tests, so", "principle will be the same as the last attempt, unless # it changes", "in filename: continue # Skip any python files if 'ANALYSIS' in filename: continue", "3: Set to unscorable for first to second responses' # print (test[x]) x+=1", "'X' if a['rule_3_2'] else '', 'X' if a['rule_3_3'] else '', a['reasoning'] ]) prevMatch", "== 3: break if len(unambiguousMatches) != 3: return False # print(str(test[0]['classNum']) + ',", "for an unambiguous result if test[a]['currentPerservativeTo'] in matches: return False if isCorrect(test, a):", "test = [] # Open the file and read it into memory with", "Next we check forwards. y = attemptNum + 1 while y < len(test):", "is unambiguously perservative due to matching the current principle and nothing else.' test[attemptNum]['perservative']", "test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: matchQuotient += 1 # Mark whether the attempt", "-= 1 # Next we check forwards. y = attemptNum + 1 while", "# 9. Check rule 2c for chained perserverations checkChainedSandwich(test, attempt['attemptNum']) # Return the", "3 'rule_3_2' : False, # for self perserverations 'rule_3_3' : False, }) except:", "containsPrincipleMatch(test, attemptNum) ): test[attemptNum]['reasoning'] += ' - Attempt is unambiguously perservative due to", "Skip any generated analysis files # if not 'iqdat' in filename: continue fullpath", "attempt in the first set 'rule_3_1' : False, # These are to show", "'.csv', 'w', newline='') as csvfile: cw = csv.writer(csvfile) cw.writerow(['#', 'Match', \"Response\", 'Correct', 'Pres-To',", "match to be considered perservative at all if not containsPrincipleMatch(test, attemptNum): return False", "set) then the first unambiguous # incorrect answer determines the first-set's Principle checkFirstSetPers(test,", "' Sandwiched After by attempt ' + str(y)) # print (test[x]) # print", "a['ambiguous'] else '', sw, chain, 'X' if a['rule_3_1'] else '', 'X' if a['rule_3_2']", "if test[attemptNum]['stimulus'][pers] == test[attemptNum]['response'][pers]: # test[attemptNum]['reasoning'] += ' - Attempt has a response", "+ ')' return True else: return False def getMatches(test, a): matches = []", "-= 1 if sandwichBefore == False: return False # Next we check forwards.", "also need to have the category changer run after this? ##################################### # Set", "'3.3', 'Reasoning']) prevMatch = '' prevPrin = '' for a in test: response", "response += 'F* ' else: response += 'F ' if a['stimulus']['number'] == a['response']['number']:", "# printTest(test) saveResults(test) return test # Iterate through each file in each folder", "test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichAfter = True # print (str(attemptNum) + ' Sandwiched", "attempt in test: # 7. Now we start looking for ambiguous perserverations. Here", "print (str(attemptNum) + ' Sandwiched After by attempt ' + str(y)) # print", "see if the response matches the stimulus on the current Perserveration principle. #", "): test[attemptNum]['reasoning'] += ' - Attempt is unambiguously perservative due to matching the", "SUBJECT = 3 MATCH = 5 SET = 6 STIMULUS = 9 RESPONSE", "False # Determine if the answer is correct if isCorrect(test, attemptNum): test[attemptNum]['correct'] =", "# 5. Heaton's rule 3: Find self-made perserverations checkSelfPerserveration(test, attempt['attemptNum']) for attempt in", "1 sandwichAfter = False while y < len(test): if test[y]['set'] != test[attemptNum]['set']: break", ": x.group(3) } def continuePreviousPresTo(test, attemptNum): if attemptNum > 0: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['currentPerservativeTo']", "= p[len(p)-1] testNum = p[len(p)-2] allTests.append(analyzeTest(fullpath, testNum, classNum)) for t in allTests: totalCorrect", "not a['correct']): totalNonPerserverativeErrors +=1 totalTrials+=1 with open('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum']", "# Open the file and read it into memory with open (fullpath) as", "\"Match\", \"Matched\", 'Pres-To', 'Pers', \"2b\", '2c', '3.1', '3.2', '3.3'] prevMatch = '' prevPrin", "change for unambiguous error.' return None # Check if the attempt had an", "'N ' if a['perservative'] and a['ambiguous']: pers = 'A-Pers' elif a['perservative']: pers =", "sw = '' if a['2c']: chain = '+' else: chain = '' x.add_row([a['attemptNum'],", "== True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichAfter = True # print (str(attemptNum)", "the column numbers, used for readability SUBJECT = 3 MATCH = 5 SET", "a['perservative']: pers = 'U-Pers' else: pers = '' if a['match'] != prevMatch: n", "cw.writerow(['#', 'Match', \"Response\", 'Correct', 'Pres-To', 'Perserverative', 'Ambiguous', \"2b (1st Sandwich)\", '2c (Chained Sandwich)',", "unambiguously perservative due to matching the current principle and nothing else.' test[attemptNum]['perservative'] =", "else '', 'X' if a['rule_3_3'] else '', a['reasoning'] ]) prevMatch = a['match'] def", "to unscorable for first to second responses' # print (test[x]) x+=1 ################################# #", "__future__ import with_statement import re, csv, os from prettytable import PrettyTable # The", "Principle was set to ' + str(test[attemptNum]['currentPerservativeTo']) + ' (last set match clause)", "r\"C:\\Users\\wyko.terhaar\\Downloads\\Map voor Wyko\\raw\" # Variables which contain the column numbers, used for readability", "a candidate for the first indicator. # Let's look ahead for more indicators!", "in files: if '.py' in filename: continue # Skip any python files if", "ambiguous the answer is matchQuotient = 0 # This is the number of", "matches the stimulus on the match criteria match = test[a]['match'] if test[a]['stimulus'][match] ==", "): break # If any of the preceeding attempts before the \"bread\" aren't", "attempt in test: # 9. Check rule 2c for chained perserverations checkChainedSandwich(test, attempt['attemptNum'])", "due to self-perserveration' # print(\"Test \", x, \" principle set to \", match)", "test[a]['2c'] = True test[a]['reasoning'] += ' - Attempt is chain sandwich perservative per", "in test: response = '' if a['stimulus']['color'] == a['response']['color']: response += 'C* '", "else: pers = '' if a['match'] != prevMatch: n = a['match'] else: n", "we know the attempt is a candidate for the first indicator. # Let's", "pers = 'A-Pers' elif a['perservative']: pers = 'U-Pers' else: pers = '' if", "else: return False def isSandwiched(test, attemptNum): # It has to have a principle", ": False, 'sandwiched' : False, 'firstSandwich' : False, 'set1PrincipleEstablished' : False, # Will", "y < len(test): if test[y]['set'] != test[attemptNum]['set']: return False # Check to see", "matchQuotient > 1: test[attemptNum]['ambiguous'] = True else: test[attemptNum]['ambiguous'] = False # Determine if", "str(attemptNum) + ' is \"sandwiched\" between ' + str(x) + ' and '", "x -= 1 if sandwichBefore == False: return False # Next we check", "+=1 totalTrials+=1 with open('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv', 'a',", "!= test[attemptNum-1]['set']: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['match'] test[attemptNum]['reasoning'] += ' - Principle was set to", "future attempts. Maybe we also need to have the category changer run after", "x = attemptNum - 1 while x > 0: if test[x]['set'] != test[attemptNum]['set']:", "if attemptNum > 0: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['currentPerservativeTo'] test[attemptNum]['reasoning'] += 'Principle was set to", "checkChainedSandwich(test, a): if isChainedSandwich(test, a): test[a]['2c'] = True test[a]['reasoning'] += ' - Attempt", "the first ones isFirstSandwich(test, attempt['attemptNum']) for attempt in test: # 9. Check rule", "(first set) then the first unambiguous # incorrect answer determines the first-set's Principle", "\\n' + fullpath) lineCount += 1 # First pass: Analyze the data with", "of the preceeding attempts before the \"bread\" aren't also # sandwiches, then 2c", "# This is the number of ways the response matches the answer for", "isFirstSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return False x = attemptNum - 1", "n = '' if a['currentPerservativeTo'] != prevPrin: prin = a['currentPerservativeTo'] prevPrin = prin", "# 2. All responses between the first and third unambiguous response must #", "final set if a['perservative']: totalPerserverative +=1 if not a['perservative']: totalNonPerserverative +=1 if (not", "!= test[attemptNum]['set']: return False if isSandwiched(test, x): return False # if test[x]['sandwiched']: return", "into memory with open (fullpath) as f: lines = f.readlines() # Iterate through", "', ' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']) + ', ' + test[0]['file']))", "= False while y < len(test): if test[y]['set'] != test[attemptNum]['set']: break if (test[y]['ambiguous']", "# r\"C:\\Users\\wyko.terhaar\\Downloads\\Map voor Wyko\\raw\" # Variables which contain the column numbers, used for", "bread if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo']", "'2c' : '', 'classNum' : classNum, 'currentPerservativeTo' : None, # Stores the currently", "else '', 'X' if a['rule_3_2'] else '', 'X' if a['rule_3_3'] else '', ])", "matching 2a and 2b. Marking perservative.' return True x-=1 def isChainedSandwich(test, attemptNum): if", "to see if we found the bread if (test[x]['ambiguous'] == False and test[x]['perservative']", "+= 'C* ' else: response += 'C ' if a['stimulus']['form'] == a['response']['form']: response", "= ' ' if a['firstSandwich']: sw= '+' else: sw = '' if a['2c']:", "self-perserveration' test[unambiguousMatches[1]]['rule_3_2'] = True test[unambiguousMatches[1]]['reasoning'] += ' - Rule 3: Second unambiguous self-perserveration", "+ ' Sandwiched Before by attempt ' + str(x)) # print (str(attemptNum) +", "+= ' - Rule 3: Final unambiguous self-perserveration' # Set all responses from", "= [x,] # We need 3 to confirm self-perserveration # print{'Added first', x)", "# tests, so we finish the loop this way and then loop again", "a['correct']: corr = '+ ' else: corr = ' ' if a['firstSandwich']: sw=", "attemptNum + 1 while y < len(test): if test[y]['set'] != test[attemptNum]['set']: return False", "False # Check to see if we found the bread if (test[x]['ambiguous'] ==", "totalNonPerserverativeErrors +=1 totalTrials+=1 with open('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv',", "need 3 to confirm self-perserveration # print{'Added first', x) while x < len(test)-1:", "rest, up to the next set change, to the new principle x =", "the same as the last attempt, unless # it changes in a subsequent", "return None if test[attemptNum]['currentPerservativeTo'] is not None: test[attemptNum]['reasoning'] += ' - Principle already", "= True else: test[attemptNum]['ambiguous'] = False # Determine if the answer is correct", "and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichBefore = True #", "' + str(lineCount) + ' in file: \\n' + fullpath) lineCount += 1", "open (fullpath) as f: lines = f.readlines() # Iterate through the test and", ": x.group(2), 'number' : x.group(3) } def continuePreviousPresTo(test, attemptNum): if attemptNum > 0:", "'2c (Chained Sandwich)', '3.1 (Self-Perserveration)', '3.2', '3.3', 'Reasoning']) prevMatch = '' prevPrin =", "'3.1 (Self-Perserveration)', '3.2', '3.3', 'Reasoning']) prevMatch = '' prevPrin = '' for a", ": testNum, '2c' : '', 'classNum' : classNum, 'currentPerservativeTo' : None, # Stores", "None if test[attemptNum]['currentPerservativeTo'] is not None: test[attemptNum]['reasoning'] += ' - Principle already set.", "we finish the loop this way and then loop again checkUnambiguousPerserveration(test, attempt['attemptNum']) for", "isFirstSandwich(test, attempt['attemptNum']) for attempt in test: # 9. Check rule 2c for chained", "is none due to start of test.' return None def checkNewSet(test, attemptNum): #", "each file in each folder in the PATH variable allTests = [] for", "read it into memory with open (fullpath) as f: lines = f.readlines() #", "> 1: test[attemptNum]['ambiguous'] = True else: test[attemptNum]['ambiguous'] = False # Determine if the", "if test[attemptNum]['set'] != 1: return None # Break out if this was not", "Sandwiched After by attempt ' + str(y)) # print (test[x]) # print (test[attemptNum])", "backwards to find if an ambiguous, potentially perservative # response was sandwiched by", "# Not currently pers # It's a match! unambiguousMatches.append(test[x]['attemptNum']) if len(unambiguousMatches) == 3:", "1 sandwichBefore = False while x > 0: if test[x]['set'] != test[attemptNum]['set']: break", "(1st Sandwich)\", '2c (Chained Sandwich)', '3.1 (Self-Perserveration)', '3.2', '3.3', 'Reasoning']) prevMatch = ''", "Principle already set. No change for unambiguous error.' return None # Check if", "incorrect answer if test[attemptNum]['correct'] == True: return None if test[attemptNum]['currentPerservativeTo'] is not None:", "match) x+=1 def analyzeTest(fullpath, testNum, classNum): test = [] # Open the file", "0 totalError = 0 totalSetsAttempted = 0 totalNonPerserverative = 0 totalNonPerserverativeErrors = 0", "= 0 totalPerserverative = 0 totalTrials = 0 for a in t: if", "not isSandwiched(test, x): return False x -= 1 # Next we check forwards.", "These are to show matches for Heaton's rule 3 'rule_3_2' : False, #", "test: # 9. Check rule 2c for chained perserverations checkChainedSandwich(test, attempt['attemptNum']) # Return", "stimulus on the current Perserveration principle. # This would suggest that this response", "any python files if 'ANALYSIS' in filename: continue # Skip any generated analysis", "the number of ways the response matches the answer for k, v in", "Mark whether the attempt is ambiguous if matchQuotient > 1: test[attemptNum]['ambiguous'] = True", "error # to something other than the current principle matches = getMatches(test, a)", "True else: if not 'Attempt is not sandwiched' in test[attemptNum]['reasoning']: test[attemptNum]['reasoning'] += '", "rule 2a: # > The ambiguous response must match the # > perseverated-to", "= line.split() test.append({ 'file' : os.path.basename(fullpath), 'attemptNum' : lineCount, 'subject' : int(attempt[SUBJECT]), 'set'", "= True test[attemptNum]['perservative'] = True test[attemptNum]['reasoning'] += ' - Attempt is a first", "attempt.The current # principle will be the same as the last attempt, unless", "+ match + ' due to self-perserveration' # print(\"Test \", x, \" principle", "on the match criteria match = test[a]['match'] if test[a]['stimulus'][match] == test[a]['response'][match]: return True", "attempt in test: # 5. Heaton's rule 3: Find self-made perserverations checkSelfPerserveration(test, attempt['attemptNum'])", "clean. try: attempt = line.split() test.append({ 'file' : os.path.basename(fullpath), 'attemptNum' : lineCount, 'subject'", "== True: return None if test[attemptNum]['currentPerservativeTo'] is not None: test[attemptNum]['reasoning'] += ' -", "'', a['reasoning'] ]) prevMatch = a['match'] def printTest(test): x = PrettyTable() # x.padding_width", "untill the second response (not # including the second response) as unscorable x", "# Set all the rest, up to the next set change, to the", "while (x < len(test) and test[x]['set'] == test[unambiguousMatches[1]]['set']): test[x]['currentPerservativeTo'] = match test[x]['reasoning'] +=", "are the first ones isFirstSandwich(test, attempt['attemptNum']) for attempt in test: # 9. Check", "# Skip the root for filename in files: if '.py' in filename: continue", "and test[attemptNum]['ambiguous'] == False and test[attemptNum]['currentPerservativeTo'] is not None and test[attemptNum]['set1PrincipleEstablished'] == False", "show matches for Heaton's rule 3 'rule_3_2' : False, # for self perserverations", "subsequent attempts # This covers the intermediate results tempMatches = getMatches(test, x) if", "!= 3: return False # print(str(test[0]['classNum']) + ', ' + str(test[0]['testNum'])+ ', '", "to register perserverations only # after the second unambiguous error. # First, we", "break if (test[y]['ambiguous'] == False and test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo']", "# 6. If this was an unambiguous error matching the perservative-to rule, AND", "go on to the more complicated # tests, so we finish the loop", "') which matches the principle (' + pers + ')' return True else:", "make 3 unambiguous errors to a sorting principle # which is neither correct", "+= ' - Attempt is not sandwiched.' return False def isFirstSandwich(test, attemptNum): if", "= 0 totalNonPerserverative = 0 totalNonPerserverativeErrors = 0 totalPerserverative = 0 totalTrials =", "# 2. Check if we just moved into a new set, and adjust", "else: test[attemptNum]['ambiguous'] = False # Determine if the answer is correct if isCorrect(test,", "check to see if this is an unambiguous error # to something other", "Check to see if we found the bread if (test[x]['ambiguous'] == False and", "x.group(3) } def continuePreviousPresTo(test, attemptNum): if attemptNum > 0: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['currentPerservativeTo'] test[attemptNum]['reasoning']", "look backwards to find if an ambiguous, potentially perservative # response was sandwiched", "# Skip any python files if 'ANALYSIS' in filename: continue # Skip any", "not isSandwiched(test, attemptNum): return False x = attemptNum - 1 while x >", "we just moved into a new set, and adjust the principle accordingly checkNewSet(test,", "+ str(y)) break y += 1 if sandwichAfter and sandwichBefore: #Mark the sandwich", "= attemptNum - 1 while x > 0: if test[x]['set'] != test[attemptNum]['set']: return", "= True test[a]['reasoning'] += ' - Attempt is chain sandwich perservative per 2c'", "# if test[x]['sandwiched']: return False if (test[x]['ambiguous'] == False and test[x]['perservative'] == True", "test[attemptNum]['currentPerservativeTo'] ): sandwichAfter = True # print (str(attemptNum) + ' Sandwiched After by", "# The very first attempt will never have a Principle if attemptNum ==", "sorting principle # which is neither correct nor currently perserverative. # # 2.", "the current principle matches = getMatches(test, a) if len(matches) != 1: return False", "if not 'iqdat' in filename: continue fullpath = os.path.join(path, filename) # Get the", "principle changed this attempt in the first set 'rule_3_1' : False, # These", "'classNum' : classNum, 'currentPerservativeTo' : None, # Stores the currently active Pres-To Principle", "Get the test number and class number from the directory names p =", "forwards. y = attemptNum + 1 while y < len(test): if test[y]['set'] !=", "a['perservative'] and not a['correct']): totalNonPerserverativeErrors +=1 totalTrials+=1 with open('SUMMARY_' + t[0]['testNum'] + '_'", "if ( test[a]['sandwiched'] and 'NOT perservative per 2c' not in test[a]['reasoning'] ): test[a]['reasoning']", "test[attemptNum]['correct'] == True: return None if test[attemptNum]['currentPerservativeTo'] is not None: test[attemptNum]['reasoning'] += '", "because the text files aren't always clean. try: attempt = line.split() test.append({ 'file'", "through each file in each folder in the PATH variable allTests = []", "- 1 sandwichBefore = False while x > 0: if test[x]['set'] != test[attemptNum]['set']:", "<filename>WCST_Scoring.py from __future__ import with_statement import re, csv, os from prettytable import PrettyTable", "it hasn't already been done if not test[attemptNum]['sandwiched']: test[attemptNum]['reasoning'] += ' - Attempt", "a in t: if a['correct']: totalCorrect +=1 if not a['correct']: totalError +=1 totalSetsAttempted", "found the bread if (test[y]['ambiguous'] == False and test[y]['perservative'] == True and test[y]['currentPerservativeTo']", "test[x]['set'] != test[attemptNum]['set']: return False if isSandwiched(test, x): return False # if test[x]['sandwiched']:", "it's an error if test[x]['currentPerservativeTo'] in tempMatches: continue # Not currently pers #", "set for future attempts. Maybe we also need to have the category changer", "Attempt ' + str(attemptNum) + ' is \"sandwiched\" between ' + str(x) +", "# print (test[attemptNum]) # print (test[y]) # wait = input('') return True else:", "prevMatch: n = a['match'] else: n = '' if a['currentPerservativeTo'] != prevPrin: prin", "- Attempt is unambiguously perservative due to matching the current principle and nothing", "classNum, 'currentPerservativeTo' : None, # Stores the currently active Pres-To Principle 'reasoning' :", "Before by attempt ' + str(x)) break x -= 1 if sandwichBefore ==", "'Pres-To', 'Perserverative', 'Ambiguous', \"2b (1st Sandwich)\", '2c (Chained Sandwich)', '3.1 (Self-Perserveration)', '3.2', '3.3',", "with a set of rules for attempt in test: # 1. Set the", "to the next set change, to the new principle x = unambiguousMatches[1] while", ": x.group(1), 'form' : x.group(2), 'number' : x.group(3) } def continuePreviousPresTo(test, attemptNum): if", "error.' return True # If the client perserverated to the Other category, Principle", "str(test[attemptNum]['currentPerservativeTo']) + ' to continue previous pattern.' return True else: test[attemptNum]['reasoning'] += 'Principle", "# Determine if the answer is correct if isCorrect(test, attemptNum): test[attemptNum]['correct'] = True", "test[x]['reasoning'] += ' - Rule 3: Set to unscorable for first to second", "have the category changer run after this? ##################################### # Set all the rest,", "column numbers, used for readability SUBJECT = 3 MATCH = 5 SET =", "we found the bread if (test[y]['ambiguous'] == False and test[y]['perservative'] == True and", "' + match + ' due to self-perserveration' # print(\"Test \", x, \"", "continuePreviousPresTo(test, attempt['attemptNum']) # 2. Check if we just moved into a new set,", "for k, v in test[a]['stimulus'].items(): if test[a]['response'][k] == v: matches.append(k) return matches def", "the match criteria match = test[a]['match'] if test[a]['stimulus'][match] == test[a]['response'][match]: return True else:", "cw = csv.writer(csvfile) cw.writerow(['#', 'Match', \"Response\", 'Correct', 'Pres-To', 'Perserverative', 'Ambiguous', \"2b (1st Sandwich)\",", "str(y) test[attemptNum]['sandwiched'] = True # print (str(attemptNum) + ' Sandwiched Before by attempt", ": '', 'classNum' : classNum, 'currentPerservativeTo' : None, # Stores the currently active", "test[attemptNum]['reasoning'] += ' - Attempt has a response (' + test[attemptNum]['response'][pers] + ')", "third unambiguous response must # match this sorting principle. # # 3. The", "a['correct']): totalNonPerserverativeErrors +=1 totalTrials+=1 with open('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum'] +", "changes in a subsequent rule. continuePreviousPresTo(test, attempt['attemptNum']) # 2. Check if we just", "was established as ' + k + ' from first unambiguous error.' return", "None def containsPrincipleMatch(test, attemptNum): # Helper function which satisfies Heaton rule 2a: #", "something other than the current principle matches = getMatches(test, a) if len(matches) !=", "= '+' else: chain = '' x.add_row([a['attemptNum'], a['match'], #n, corr + response, a['currentPerservativeTo'],", "= 6 STIMULUS = 9 RESPONSE = 10 def saveResults(test): with open('ANALYSIS_' +", "== v: test[attemptNum]['currentPerservativeTo'] = k test[attemptNum]['set1PrincipleEstablished'] = True test[attemptNum]['reasoning'] += ' - Principle", "not None and test[attemptNum]['set1PrincipleEstablished'] == False and containsPrincipleMatch(test, attemptNum) ): test[attemptNum]['reasoning'] += '", "#n, corr + response, a['currentPerservativeTo'], #prin, pers, sw, chain, 'X' if a['rule_3_1'] else", "lines.pop(0) lineCount = 0 for line in lines: # Split the test report", "' - Client perserverated to Other category. No Principle set.' return None def", "'', a['currentPerservativeTo'], #prin, '+' if a['perservative'] else '', '+' if a['ambiguous'] else '',", "print{'Added first', x) while x < len(test)-1: x+=1 # Make sure the potential", "('There was an error reading line ' + str(lineCount) + ' in file:", "Other category. No Principle set.' return None def containsPrincipleMatch(test, attemptNum): # Helper function", "\"Matched\", 'Pres-To', 'Pers', \"2b\", '2c', '3.1', '3.2', '3.3'] prevMatch = '' prevPrin =", "considered perservative at all if not containsPrincipleMatch(test, attemptNum): return False # It has", "an unambiguous incorrect answer. # If so, set the Principle whichever principle the", "set. No change for unambiguous error.' return None # Check if the attempt", "Sandwiched Before by attempt ' + str(x)) # print (str(attemptNum) + ' Sandwiched", "None if test[attemptNum]['set'] != test[attemptNum-1]['set']: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['match'] test[attemptNum]['reasoning'] += ' - Principle", "'' for a in test: response = '' if a['stimulus']['color'] == a['response']['color']: response", "(test[x]) x+=1 ################################# # Principle is not set for future attempts. Maybe we", "is not set for future attempts. Maybe we also need to have the", "clause) because set was changed.' return True def checkAnswer(test, attemptNum): # Determine how", "< len(test)-1: x+=1 # Make sure the potential principle is matched in all", "answer # in which the Principle principle was established in the first set.", "an unambiguous incorrect answer. Skip the answer # in which the Principle principle", "boolean 'correct' : False, 'perservative' : False, 'ambiguous' : False, 'sandwiched' : False,", "False if isSandwiched(test, x): return False # if test[x]['sandwiched']: return False if (test[x]['ambiguous']", "changed.' return True def checkAnswer(test, attemptNum): # Determine how ambiguous the answer is", "k + ' from first unambiguous error.' return True # If the client", "perservative at all if not containsPrincipleMatch(test, attemptNum): return False # It has to", "if os.stat('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv').st_size == 0: cw.writerow(['Class',", "is ambiguous if matchQuotient > 1: test[attemptNum]['ambiguous'] = True else: test[attemptNum]['ambiguous'] = False", "'3.1', '3.2', '3.3'] prevMatch = '' prevPrin = '' for a in test:", "indicators! x = a unambiguousMatches = [x,] # We need 3 to confirm", "len(tempMatches) != 1: continue # Ensure it is an unambiguous result if isCorrect(test,", "# after the second unambiguous error. # First, we check to see if", "' if a['stimulus']['number'] == a['response']['number']: response += 'N* ' else: response += 'N", "the first and third unambiguous response must # match this sorting principle. #", "an ambiguous, potentially perservative # response was sandwiched by an unambiguous response for", "from the first untill the second response (not # including the second response)", "already set. No change for unambiguous error.' return None # Check if the", "a['match'], #n, corr + response, a['currentPerservativeTo'], #prin, pers, sw, chain, 'X' if a['rule_3_1']", "4. If Principle has not been determined (first set) then the first unambiguous", "\" principle set to \", match) x+=1 def analyzeTest(fullpath, testNum, classNum): test =", "# The top level folder which contains the tests PATH = os.getcwd() #", "error.' return None # Check if the attempt had an unambiguous incorrect answer.", "not sandwiched.' return False def isFirstSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return False", "x) if not match in tempMatches: return False # Now we look for", "= 0 totalError = 0 totalSetsAttempted = 0 totalNonPerserverative = 0 totalNonPerserverativeErrors =", "0 totalSetsAttempted = 0 totalNonPerserverative = 0 totalNonPerserverativeErrors = 0 totalPerserverative = 0", "and analyzed test object # printTest(test) saveResults(test) return test # Iterate through each", "= k test[attemptNum]['set1PrincipleEstablished'] = True test[attemptNum]['reasoning'] += ' - Principle was established as", "+ ', ' + str(test[0]['testNum'])+ ', ' + str(test[0]['subject']) + ', ' +", "# print (str(attemptNum) + ' Sandwiched After by attempt ' + str(y)) #", "' - Attempt is not sandwiched.' return False def isFirstSandwich(test, attemptNum): if not", "test[0]['file'] + '.csv', 'w', newline='') as csvfile: cw = csv.writer(csvfile) cw.writerow(['#', 'Match', \"Response\",", "than the current principle matches = getMatches(test, a) if len(matches) != 1: return", "each file # Get the test number and class number from the directory", "' else: response += 'N ' if a['perservative'] and a['ambiguous']: pers = 'A-Pers'", "splitStim(attempt[STIMULUS]), 'response' : splitStim(attempt[RESPONSE]), 'testNum' : testNum, '2c' : '', 'classNum' : classNum,", "if matchQuotient > 1: test[attemptNum]['ambiguous'] = True else: test[attemptNum]['ambiguous'] = False # Determine", "sandwichBefore = False while x > 0: if test[x]['set'] != test[attemptNum]['set']: break if", "getMatches(test, x) if not match in tempMatches: return False # Now we look", "to show matches for Heaton's rule 3 'rule_3_2' : False, # for self", "is not sandwiched' in test[attemptNum]['reasoning']: test[attemptNum]['reasoning'] += ' - Attempt is not sandwiched.'", "attemptNum): if not isSandwiched(test, attemptNum): return False x = attemptNum - 1 while", "This would suggest that this response is perserverating if test[attemptNum]['stimulus'][pers] == test[attemptNum]['response'][pers]: #", "print (str(attemptNum) + ' Sandwiched Before by attempt ' + str(x)) break x", "- Attempt is chain sandwich perservative per 2c' test[a]['perservative'] = True return True", "in which the Principle principle was established in the first set. if (test[attemptNum]['correct']", "Open the file and read it into memory with open (fullpath) as f:", "if test[x]['set'] != test[attemptNum]['set']: return False # Check to see if we found", "' + str(test[0]['subject']) + ', ' + test[0]['file'])) def splitStim(stim): x = re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)',", "1 while y < len(test): if test[y]['set'] != test[attemptNum]['set']: return False # Check", "unambiguous response must # match this sorting principle. # # 3. The new", "# 1. The client must make 3 unambiguous errors to a sorting principle", "an unambiguous result if test[a]['currentPerservativeTo'] in matches: return False if isCorrect(test, a): return", "return False if isFirstSandwich(test, attemptNum): return False x = attemptNum - 1 while", "error checkAnswer(test, attempt['attemptNum']) # 4. If Principle has not been determined (first set)", "# If we get here, then we know the attempt is a candidate", "0: cw.writerow(['Class', 'Subject', 'Sets Attempted', 'Correct', 'Errors', 'Non-Perserverative', 'Non-Perserverative Errors', 'Perserverative', 'Trials', '%", "becomes active to register perserverations only # after the second unambiguous error. #", "principle was established in the first set. if (test[attemptNum]['correct'] == False and test[attemptNum]['ambiguous']", "set change, to the new principle x = unambiguousMatches[1] while (x < len(test)", "False pers = test[attemptNum]['currentPerservativeTo'] # Check to see if the response matches the", "loop again checkUnambiguousPerserveration(test, attempt['attemptNum']) for attempt in test: # 7. Now we start", "True else: test[attemptNum]['reasoning'] += 'Principle is none due to start of test.' return", "for t in allTests: totalCorrect = 0 totalError = 0 totalSetsAttempted = 0", "last two unambiguous errors to the new, not currently # perserverative principle if", "if a['perservative'] and a['ambiguous']: pers = 'A-Pers' elif a['perservative']: pers = 'U-Pers' else:", "break x -= 1 if sandwichBefore == False: return False # Next we", "matchQuotient = 0 # This is the number of ways the response matches", "'Principle was set to ' + str(test[attemptNum]['currentPerservativeTo']) + ' to continue previous pattern.'", "the stimulus on the current Perserveration principle. # This would suggest that this", "return False if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] ==", "0: if test[x]['set'] != test[attemptNum]['set']: return False # Check to see if we", "in allTests: totalCorrect = 0 totalError = 0 totalSetsAttempted = 0 totalNonPerserverative =", "' Sandwiched Before by attempt ' + str(x)) break x -= 1 if", "used for readability SUBJECT = 3 MATCH = 5 SET = 6 STIMULUS", "before the \"bread\" aren't also # sandwiches, then 2c doesn't apply if not", "response must # match this sorting principle. # # 3. The new principle", "if len(unambiguousMatches) == 3: break if len(unambiguousMatches) != 3: return False # print(str(test[0]['classNum'])", "None test[x]['reasoning'] += ' - Rule 3: Set to unscorable for first to", "test[y]['perservative'] == True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If any of", "Helper function which satisfies Heaton rule 2a: # > The ambiguous response must", ": False, # These are to show matches for Heaton's rule 3 'rule_3_2'", "True and test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichAfter = True # print (str(attemptNum) +", "is a candidate for the first indicator. # Let's look ahead for more", "if we found the bread if (test[y]['ambiguous'] == False and test[y]['perservative'] == True", "sandwich, matching 2a and 2b. Marking perservative.' return True x-=1 def isChainedSandwich(test, attemptNum):", "any generated analysis files # if not 'iqdat' in filename: continue fullpath =", "test[attemptNum]['perservative'] = True test[attemptNum]['reasoning'] += ' - Attempt is a first sandwich, matching", "attempt, unless # it changes in a subsequent rule. continuePreviousPresTo(test, attempt['attemptNum']) # 2.", "(str(attemptNum) + ' Sandwiched After by attempt ' + str(y)) break y +=", "= test[attemptNum-1]['currentPerservativeTo'] test[attemptNum]['reasoning'] += 'Principle was set to ' + str(test[attemptNum]['currentPerservativeTo']) + '", "return True else: return False def checkFirstSetPers(test, attemptNum): # Break out if this", "look for the last two unambiguous errors to the new, not currently #", "attempt ' + str(x)) break x -= 1 if sandwichBefore == False: return", "a response (' + test[attemptNum]['response'][pers] + ') which matches the principle (' +", "test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If any of the preceeding attempts before", "unscorable for first to second responses' # print (test[x]) x+=1 ################################# # Principle", "attemptNum - 1 while x > 0: if test[x]['set'] != test[attemptNum]['set']: return False", "the response matches the stimulus on the current Perserveration principle. # This would", "effect (in our example, Color as defined by # > the previous sorting", "match test[x]['reasoning'] += ' - Rule 3: Principle set to ' + match", "attemptNum): if not isSandwiched(test, attemptNum): return False if isFirstSandwich(test, attemptNum): return False x", "1 if sandwichAfter and sandwichBefore: #Mark the sandwich if it hasn't already been", "unambiguous errors to a sorting principle # which is neither correct nor currently", "os.walk(PATH): if path == PATH: continue # Skip the root for filename in", "errors to a sorting principle # which is neither correct nor currently perserverative.", "True x-=1 def isChainedSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return False if isFirstSandwich(test,", "we check to see if this is an unambiguous error # to something", "== False and test[attemptNum]['currentPerservativeTo'] is not None and test[attemptNum]['set1PrincipleEstablished'] == False and containsPrincipleMatch(test,", "1: continue # Ensure it is an unambiguous result if isCorrect(test, x): continue", "test # Iterate through each file in each folder in the PATH variable", "attemptNum - 1 sandwichBefore = False while x > 0: if test[x]['set'] !=", "while x > 0: if test[x]['set'] != test[attemptNum]['set']: return False # Check to", "- Principle was established as ' + k + ' from first unambiguous", "def isFirstSandwich(test, attemptNum): if not isSandwiched(test, attemptNum): return False x = attemptNum -", "+= ' - Rule 3: Second unambiguous self-perserveration after attempt ' + str(test[unambiguousMatches[0]]['attemptNum'])", "done if not test[attemptNum]['sandwiched']: test[attemptNum]['reasoning'] += ' - Attempt ' + str(attemptNum) +", "'X' if a['rule_3_3'] else '', a['reasoning'] ]) prevMatch = a['match'] def printTest(test): x", "while y < len(test): if test[y]['set'] != test[attemptNum]['set']: break if (test[y]['ambiguous'] == False", "No change for unambiguous error.' return None # Check if the attempt had", "True return True else: test[a]['2c'] = False if ( test[a]['sandwiched'] and 'NOT perservative", "a['2c']: chain = '+' else: chain = '' cw.writerow([a['attemptNum'], a['match'], #n, response, '+'", "'testNum' : testNum, '2c' : '', 'classNum' : classNum, 'currentPerservativeTo' : None, #", "' - Sandwiched attempt is NOT perservative per 2c' return False def checkSelfPerserveration(test,", "analysis. Skip the headers. lines.pop(0) lineCount = 0 for line in lines: #", "a['match'] != prevMatch: n = a['match'] else: n = '' if a['currentPerservativeTo'] !=", "pers = '' if a['match'] != prevMatch: n = a['match'] else: n =", "to start of test.' return None def checkNewSet(test, attemptNum): # The very first", "answers are the first ones isFirstSandwich(test, attempt['attemptNum']) for attempt in test: # 9.", "in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k] == v: test[attemptNum]['currentPerservativeTo'] = k test[attemptNum]['set1PrincipleEstablished'] = True test[attemptNum]['reasoning']", "we also need to have the category changer run after this? ##################################### #", "return False def getMatches(test, a): matches = [] for k, v in test[a]['stimulus'].items():", "report into an array of Dicts # Added some error handling because the", "confirm self-perserveration # print{'Added first', x) while x < len(test)-1: x+=1 # Make", "we check forwards. y = attemptNum + 1 sandwichAfter = False while y", "'.py' in filename: continue # Skip any python files if 'ANALYSIS' in filename:", "' if a['firstSandwich']: sw= '+' else: sw = '' if a['2c']: chain =", "to know this for every rule before we can go on to the", "memory with open (fullpath) as f: lines = f.readlines() # Iterate through the", "- Attempt is a first sandwich, matching 2a and 2b. Marking perservative.' return", "determined (first set) then the first unambiguous # incorrect answer determines the first-set's", "we found the bread if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and", "if len(tempMatches) != 1: continue # Ensure it is an unambiguous result if", "'' if a['2c']: chain = '+' else: chain = '' cw.writerow([a['attemptNum'], a['match'], #n,", "'', 'X' if a['rule_3_3'] else '', ]) prevMatch = a['match'] print(x.get_string(title= str(test[0]['classNum']) +", "after the second unambiguous error. # First, we check to see if this", "a['perservative'] else '', '+' if a['ambiguous'] else '', sw, chain, 'X' if a['rule_3_1']", "t in allTests: totalCorrect = 0 totalError = 0 totalSetsAttempted = 0 totalNonPerserverative", "function which satisfies Heaton rule 2a: # > The ambiguous response must match", "if not match in tempMatches: return False # Now we look for the", "newline='') as csvfile: cw = csv.writer(csvfile) if os.stat('SUMMARY_' + t[0]['testNum'] + '_' +", "isCorrect(test, a): # Determine if a response matches the stimulus on the match", "k, v in test[a]['stimulus'].items(): if test[a]['response'][k] == v: matches.append(k) return matches def checkUnambiguousPerserveration(test,", "isSandwiched(test, x): return False # if test[x]['sandwiched']: return False if (test[x]['ambiguous'] == False", "return False # Next we check forwards. y = attemptNum + 1 sandwichAfter", "perservative due to matching the current principle and nothing else.' test[attemptNum]['perservative'] = True", "str(lineCount) + ' in file: \\n' + fullpath) lineCount += 1 # First", "if not a['correct']: totalError +=1 totalSetsAttempted = a['set'] # Will end up being", "for readability SUBJECT = 3 MATCH = 5 SET = 6 STIMULUS =", "== False: return False # Next we check forwards. y = attemptNum +", "verify results # The following are all boolean 'correct' : False, 'perservative' :", "to self-perserveration' # print(\"Test \", x, \" principle set to \", match) x+=1", "we found one on attempt ', attemptNum) # print (test[attemptNum]) return True def", "Perserveration principle. # This would suggest that this response is perserverating if test[attemptNum]['stimulus'][pers]", "str(test[0]['subject']) + ', ' + test[0]['file'])) def splitStim(stim): x = re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)', stim) return", "False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If", "False, }) except: print ('There was an error reading line ' + str(lineCount)", "x.group(1), 'form' : x.group(2), 'number' : x.group(3) } def continuePreviousPresTo(test, attemptNum): if attemptNum", "'sandwiched' : False, 'firstSandwich' : False, 'set1PrincipleEstablished' : False, # Will change to", "'response' : splitStim(attempt[RESPONSE]), 'testNum' : testNum, '2c' : '', 'classNum' : classNum, 'currentPerservativeTo'", "an unambiguous result if isCorrect(test, x): continue # Make sure it's an error", "the attempt is ambiguous if matchQuotient > 1: test[attemptNum]['ambiguous'] = True else: test[attemptNum]['ambiguous']", "then 2c doesn't apply if not isSandwiched(test, y): return False y += 1", "perserverated to the Other category, Principle isn't set. test[attemptNum]['reasoning'] += ' - Client", "the \"bread\" aren't also # sandwiches, then 2c doesn't apply if not isSandwiched(test,", "\"2b\", '2c', '3.1', '3.2', '3.3'] prevMatch = '' prevPrin = '' for a", "test[x]['currentPerservativeTo'] = match test[x]['reasoning'] += ' - Rule 3: Principle set to '", "perserverations checkChainedSandwich(test, attempt['attemptNum']) # Return the fully populated and analyzed test object #", "principle becomes active to register perserverations only # after the second unambiguous error.", "str(test[0]['testNum'])+ ', ' + str(test[0]['subject']) + ', ' + test[0]['file'])) def splitStim(stim): x", "' - Attempt is unambiguously perservative due to matching the current principle and", "(test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichBefore", "Attempt has a response (' + test[attemptNum]['response'][pers] + ') which matches the principle", "which is neither correct nor currently perserverative. # # 2. All responses between", "we can go on to the more complicated # tests, so we finish", ": int(attempt[SET]), 'match' : attempt[MATCH], 'stimulus' : splitStim(attempt[STIMULUS]), 'response' : splitStim(attempt[RESPONSE]), 'testNum' :", "#prin, pers, sw, chain, 'X' if a['rule_3_1'] else '', 'X' if a['rule_3_2'] else", "a['rule_3_2'] else '', 'X' if a['rule_3_3'] else '', a['reasoning'] ]) prevMatch = a['match']", "sandwich perservative per 2c' test[a]['perservative'] = True return True else: test[a]['2c'] = False", "return None if test[attemptNum]['set'] != test[attemptNum-1]['set']: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['match'] test[attemptNum]['reasoning'] += ' -", "1. Set the principle the same as last attempt.The current # principle will", "ambiguous response must match the # > perseverated-to principle that is currently in", "p[len(p)-1] testNum = p[len(p)-2] allTests.append(analyzeTest(fullpath, testNum, classNum)) for t in allTests: totalCorrect =", "a['match'], #n, response, '+' if a['correct'] else '', a['currentPerservativeTo'], #prin, '+' if a['perservative']", "k test[attemptNum]['set1PrincipleEstablished'] = True test[attemptNum]['reasoning'] += ' - Principle was established as '", "Sandwiched attempt is NOT perservative per 2c' return False def checkSelfPerserveration(test, a): #", "1: test[attemptNum]['ambiguous'] = True else: test[attemptNum]['ambiguous'] = False # Determine if the answer", "!= test[attemptNum]['set']: break if (test[y]['ambiguous'] == False and test[y]['perservative'] == True and test[y]['currentPerservativeTo']", "# Next we check forwards. y = attemptNum + 1 sandwichAfter = False", "perserverative. # # 2. All responses between the first and third unambiguous response", "set. test[attemptNum]['reasoning'] += ' - Client perserverated to Other category. No Principle set.'", "totalNonPerserverative = 0 totalNonPerserverativeErrors = 0 totalPerserverative = 0 totalTrials = 0 for", "if the attempt was an error checkAnswer(test, attempt['attemptNum']) # 4. If Principle has", "The new principle becomes active to register perserverations only # after the second", "finish the loop this way and then loop again checkUnambiguousPerserveration(test, attempt['attemptNum']) for attempt", "and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If any of the preceeding attempts", "very first attempt will never have a Principle if attemptNum == 0: return", "so, set the Principle whichever principle the client matched if (test[attemptNum]['correct'] == False", "True and test[x]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): sandwichBefore = True # print (str(attemptNum) +", "3 MATCH = 5 SET = 6 STIMULUS = 9 RESPONSE = 10", "test[unambiguousMatches[1]]['rule_3_2'] = True test[unambiguousMatches[1]]['reasoning'] += ' - Rule 3: Second unambiguous self-perserveration after", "False, 'ambiguous' : False, 'sandwiched' : False, 'firstSandwich' : False, 'set1PrincipleEstablished' : False,", "sandwiched ambiguous answers are the first ones isFirstSandwich(test, attempt['attemptNum']) for attempt in test:", "len(unambiguousMatches) == 3: break if len(unambiguousMatches) != 3: return False # print(str(test[0]['classNum']) +", "'Ambiguous', \"2b (1st Sandwich)\", '2c (Chained Sandwich)', '3.1 (Self-Perserveration)', '3.2', '3.3', 'Reasoning']) prevMatch", "# This covers the intermediate results tempMatches = getMatches(test, x) if not match", "new principle becomes active to register perserverations only # after the second unambiguous", "# Skip any generated analysis files # if not 'iqdat' in filename: continue", "set if test[attemptNum]['set'] != 1: return None # Break out if this was", "test[attemptNum]['sandwiched']: test[attemptNum]['reasoning'] += ' - Attempt ' + str(attemptNum) + ' is \"sandwiched\"", "if a['stimulus']['number'] == a['response']['number']: response += 'N* ' else: response += 'N '", "test[x]['sandwiched']: return False if (test[x]['ambiguous'] == False and test[x]['perservative'] == True and test[x]['currentPerservativeTo']", "the attempt was an error checkAnswer(test, attempt['attemptNum']) # 4. If Principle has not", "= 1 x.field_names = ['#', \"Match\", \"Matched\", 'Pres-To', 'Pers', \"2b\", '2c', '3.1', '3.2',", "Rule 3: Set to unscorable for first to second responses' # print (test[x])", "this for every rule before we can go on to the more complicated", "same as last attempt.The current # principle will be the same as the", "test[x]['set'] == test[unambiguousMatches[1]]['set']): test[x]['currentPerservativeTo'] = match test[x]['reasoning'] += ' - Rule 3: Principle", "and test[attemptNum]['set1PrincipleEstablished'] == False and containsPrincipleMatch(test, attemptNum) ): test[attemptNum]['reasoning'] += ' - Attempt", "+ test[0]['file'])) def splitStim(stim): x = re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)', stim) return { 'color' : x.group(1),", "= True test[attemptNum]['reasoning'] += ' - Principle was established as ' + k", "this? ##################################### # Set all the rest, up to the next set change,", "[] for k, v in test[a]['stimulus'].items(): if test[a]['response'][k] == v: matches.append(k) return matches", "is neither correct nor currently perserverative. # # 2. All responses between the", "of test.' return None def checkNewSet(test, attemptNum): # The very first attempt will", "we look backwards to find if an ambiguous, potentially perservative # response was", "self-perserveration' # print(\"Test \", x, \" principle set to \", match) x+=1 def", "checkNewSet(test, attempt['attemptNum']) # 3. Check if the attempt was an error checkAnswer(test, attempt['attemptNum'])", "' and ' + str(y) test[attemptNum]['sandwiched'] = True # print (str(attemptNum) + '", "def checkAnswer(test, attemptNum): # Determine how ambiguous the answer is matchQuotient = 0", "return False def checkSelfPerserveration(test, a): # 1. The client must make 3 unambiguous", "isSandwiched(test, y): return False y += 1 # print('Holy shit, we found one", "' to continue previous pattern.' return True else: test[attemptNum]['reasoning'] += 'Principle is none", "was set to ' + str(test[attemptNum]['currentPerservativeTo']) + ' to continue previous pattern.' return", "else '', a['reasoning'] ]) prevMatch = a['match'] def printTest(test): x = PrettyTable() #", "False def isCorrect(test, a): # Determine if a response matches the stimulus on", "on attempt ', attemptNum) # print (test[attemptNum]) return True def checkChainedSandwich(test, a): if", "Client perserverated to Other category. No Principle set.' return None def containsPrincipleMatch(test, attemptNum):", "if a['stimulus']['form'] == a['response']['form']: response += 'F* ' else: response += 'F '", "if test[a]['response'][k] == v: matches.append(k) return matches def checkUnambiguousPerserveration(test, attemptNum): # Check if", "and ' + str(y) test[attemptNum]['sandwiched'] = True # print (str(attemptNum) + ' Sandwiched", "Set all the rest, up to the next set change, to the new", "the filename for each file # Get the test number and class number", "- Rule 3: Final unambiguous self-perserveration' # Set all responses from the first", "principle x = unambiguousMatches[1] while (x < len(test) and test[x]['set'] == test[unambiguousMatches[1]]['set']): test[x]['currentPerservativeTo']", "+= 'C ' if a['stimulus']['form'] == a['response']['form']: response += 'F* ' else: response", "if a['correct'] else '', a['currentPerservativeTo'], #prin, '+' if a['perservative'] else '', '+' if", "+= 'F ' if a['stimulus']['number'] == a['response']['number']: response += 'N* ' else: response", "attemptNum == 0: return None if test[attemptNum]['set'] != test[attemptNum-1]['set']: test[attemptNum]['currentPerservativeTo'] = test[attemptNum-1]['match'] test[attemptNum]['reasoning']", "' - Rule 3: Second unambiguous self-perserveration after attempt ' + str(test[unambiguousMatches[0]]['attemptNum']) test[unambiguousMatches[2]]['rule_3_3']", "we check the # \"sandwich rule.\" isSandwiched(test, attempt['attemptNum']) for attempt in test: #", "# Break out if this was not an incorrect answer if test[attemptNum]['correct'] ==", "print (test[attemptNum]) return True def checkChainedSandwich(test, a): if isChainedSandwich(test, a): test[a]['2c'] = True", "unambiguousMatches = [x,] # We need 3 to confirm self-perserveration # print{'Added first',", "if a['rule_3_1'] else '', 'X' if a['rule_3_2'] else '', 'X' if a['rule_3_3'] else", "(test[x]) # print (test[attemptNum]) # print (test[y]) # wait = input('') return True", "- Principle was set to ' + str(test[attemptNum]['currentPerservativeTo']) + ' (last set match", "'Subject', 'Sets Attempted', 'Correct', 'Errors', 'Non-Perserverative', 'Non-Perserverative Errors', 'Perserverative', 'Trials', '% Perserverative']) cw.writerow([", "a['correct']: totalError +=1 totalSetsAttempted = a['set'] # Will end up being the final", "isSandwiched(test, attemptNum): return False x = attemptNum - 1 while x > 0:", "== False and test[attemptNum]['ambiguous'] == False): for k, v in test[attemptNum]['stimulus'].items(): if test[attemptNum]['response'][k]", "for every rule before we can go on to the more complicated #", "it changes in a subsequent rule. continuePreviousPresTo(test, attempt['attemptNum']) # 2. Check if we", "+=1 if (not a['perservative'] and not a['correct']): totalNonPerserverativeErrors +=1 totalTrials+=1 with open('SUMMARY_' +", "- Principle already set. No change for unambiguous error.' return None # Check", "Not currently pers # It's a match! unambiguousMatches.append(test[x]['attemptNum']) if len(unambiguousMatches) == 3: break", "matches.append(k) return matches def checkUnambiguousPerserveration(test, attemptNum): # Check if the attempt had an", "the sandwich if it hasn't already been done if not test[attemptNum]['sandwiched']: test[attemptNum]['reasoning'] +=", "totalTrials+=1 with open('SUMMARY_' + t[0]['testNum'] + '_' + t[0]['classNum'] + '.csv', 'a', newline='')", "'A-Pers' elif a['perservative']: pers = 'U-Pers' else: pers = '' if a['match'] !=", "matches def checkUnambiguousPerserveration(test, attemptNum): # Check if the attempt had an unambiguous incorrect", "principle (' + pers + ')' return True else: return False def getMatches(test,", "+ t[0]['classNum'] + '.csv', 'a', newline='') as csvfile: cw = csv.writer(csvfile) if os.stat('SUMMARY_'", "the last attempt, unless # it changes in a subsequent rule. continuePreviousPresTo(test, attempt['attemptNum'])", "def splitStim(stim): x = re.match(r'(^[A-Z][a-z]+)([A-Z][a-z]+)(\\d+)', stim) return { 'color' : x.group(1), 'form' :", "not an incorrect answer if test[attemptNum]['correct'] == True: return None if test[attemptNum]['currentPerservativeTo'] is", "test[y]['currentPerservativeTo'] == test[attemptNum]['currentPerservativeTo'] ): break # If any of the preceeding attempts before", "incorrect answer determines the first-set's Principle checkFirstSetPers(test, attempt['attemptNum']) for attempt in test: #" ]
[ "KIND, either express or implied. # See the License for the specific language", "Unless required by applicable law or agreed to in writing, software # distributed", "should limit the number of connections to the number of threads, which is", "self.redis = redis.client.Redis(self.redis_server(), decode_responses=True, socket_connect_timeout=self.CONNECT_TIMEOUT ) # NOTE: Tried to do this with", "2019 by <NAME> # # Licensed under the Apache License, Version 2.0 (the", "is final so it # it doesn't really matter. Worst thing that happens", "limit the number of connections to the number of threads, which is 1.", "return the address of the Redis server.\"\"\" pass def __init__(self, event_loop, ttl_grace): self.redis", "= ttl_grace # NOTE: This could be protected by a lock, but setting", "this file except in compliance with the License. # You may obtain a", "= 5 def redis_server(self): \"\"\"Needs to be subclassed to return the address of", "the Redis server.\"\"\" pass def __init__(self, event_loop, ttl_grace): self.redis = redis.client.Redis(self.redis_server(), decode_responses=True, socket_connect_timeout=self.CONNECT_TIMEOUT", "at subclasses to see how this is used.) self.stop = False return def", "\"\"\"Needs to be subclassed to return the address of the Redis server.\"\"\" pass", "run.\"\"\" if self.stop: self.event_loop.stop() return self.event_loop.run_in_executor(self.executor, func, *args) return def redis_executor(self, func, *args):", "number of connections to the number of threads, which is 1. #connection_pool=redis.connection.BlockingConnectionPool( #max_connections=2,timeout=5)", "using a ThreadPoolExecutor to post to Redis. \"\"\" import traceback import asyncio from", "<NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "ANY KIND, either express or implied. # See the License for the specific", "but setting it True is final so it # it doesn't really matter.", "to run.\"\"\" if self.stop: self.event_loop.stop() return self.event_loop.run_in_executor(self.executor, func, *args) return def redis_executor(self, func,", "redis.client.Redis(self.redis_server(), decode_responses=True, socket_connect_timeout=self.CONNECT_TIMEOUT ) # NOTE: Tried to do this with a BlockingConnectionPool", "# errors get logged. (Look at subclasses to see how this is used.)", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "is an asyncio event sink using a ThreadPoolExecutor to post to Redis. \"\"\"", "it refused to connect # to anything but localhost. I don't think it", "= 'client;{}'.format(client_address) self.redis.incr(k) self.redis.expire(k, self.ttl_grace) return def submit(self, func, *args): \"\"\"Submit a Redis", "\"\"\"Handles calls to Redis so that they can be run in a different", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "The Redis Handler is an asyncio event sink using a ThreadPoolExecutor to post", "client_to_redis(self, client_address): \"\"\"Called internally by the other *_to_redis() methods to update the client.\"\"\"", "update to run.\"\"\" if self.stop: self.event_loop.stop() return self.event_loop.run_in_executor(self.executor, func, *args) return def redis_executor(self,", "OF ANY KIND, either express or implied. # See the License for the", "Redis so that they can be run in a different thread.\"\"\" CONNECT_TIMEOUT =", "return self.event_loop.run_in_executor(self.executor, func, *args) return def redis_executor(self, func, *args): \"\"\"Encapsulate exceptions which might", "*args) return def redis_executor(self, func, *args): \"\"\"Encapsulate exceptions which might occur within redis", "__init__(self, event_loop, ttl_grace): self.redis = redis.client.Redis(self.redis_server(), decode_responses=True, socket_connect_timeout=self.CONNECT_TIMEOUT ) # NOTE: Tried to", "self.event_loop.stop() return self.event_loop.run_in_executor(self.executor, func, *args) return def redis_executor(self, func, *args): \"\"\"Encapsulate exceptions which", "a BlockingConnectionPool but it refused to connect # to anything but localhost. I", "see how this is used.) self.stop = False return def client_to_redis(self, client_address): \"\"\"Called", "\"\"\" try: func(*args) except ConnectionError as e: if not self.stop: logging.error('redis.exceptions.ConnectionError: {}'.format(e)) self.stop", "other *_to_redis() methods to update the client.\"\"\" k = 'client;{}'.format(client_address) self.redis.incr(k) self.redis.expire(k, self.ttl_grace)", "doesn't really matter. Worst thing that happens is that multiple # errors get", "refused to connect # to anything but localhost. I don't think it matters,", "within redis threads. All calling of Redis network functions is done inside of", "def submit(self, func, *args): \"\"\"Submit a Redis update to run.\"\"\" if self.stop: self.event_loop.stop()", "lock, but setting it True is final so it # it doesn't really", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "but localhost. I don't think it matters, the ThreadPoolExecutor # should limit the", "\"\"\"Submit a Redis update to run.\"\"\" if self.stop: self.event_loop.stop() return self.event_loop.run_in_executor(self.executor, func, *args)", "how this is used.) self.stop = False return def client_to_redis(self, client_address): \"\"\"Called internally", "RedisBaseHandler(object): \"\"\"Handles calls to Redis so that they can be run in a", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "True except Exception as e: if not self.stop: traceback.print_exc() self.stop = True return", "traceback import asyncio from concurrent.futures import ThreadPoolExecutor import redis class RedisBaseHandler(object): \"\"\"Handles calls", "k = 'client;{}'.format(client_address) self.redis.incr(k) self.redis.expire(k, self.ttl_grace) return def submit(self, func, *args): \"\"\"Submit a", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "of these blocks. \"\"\" try: func(*args) except ConnectionError as e: if not self.stop:", "of the Redis server.\"\"\" pass def __init__(self, event_loop, ttl_grace): self.redis = redis.client.Redis(self.redis_server(), decode_responses=True,", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "that multiple # errors get logged. (Look at subclasses to see how this", "socket_connect_timeout=self.CONNECT_TIMEOUT ) # NOTE: Tried to do this with a BlockingConnectionPool but it", "ttl_grace # NOTE: This could be protected by a lock, but setting it", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "and # limitations under the License. \"\"\"Redis Handler. The Redis Handler is an", "ttl_grace): self.redis = redis.client.Redis(self.redis_server(), decode_responses=True, socket_connect_timeout=self.CONNECT_TIMEOUT ) # NOTE: Tried to do this", "final so it # it doesn't really matter. Worst thing that happens is", "post to Redis. \"\"\" import traceback import asyncio from concurrent.futures import ThreadPoolExecutor import", "Tried to do this with a BlockingConnectionPool but it refused to connect #", "protected by a lock, but setting it True is final so it #", "connections to the number of threads, which is 1. #connection_pool=redis.connection.BlockingConnectionPool( #max_connections=2,timeout=5) #) self.executor", "required by applicable law or agreed to in writing, software # distributed under", "multiple # errors get logged. (Look at subclasses to see how this is", "done inside of one of these blocks. \"\"\" try: func(*args) except ConnectionError as", "applicable law or agreed to in writing, software # distributed under the License", "import asyncio from concurrent.futures import ThreadPoolExecutor import redis class RedisBaseHandler(object): \"\"\"Handles calls to", "errors get logged. (Look at subclasses to see how this is used.) self.stop", "if self.stop: self.event_loop.stop() return self.event_loop.run_in_executor(self.executor, func, *args) return def redis_executor(self, func, *args): \"\"\"Encapsulate", "redis_executor(self, func, *args): \"\"\"Encapsulate exceptions which might occur within redis threads. All calling", "or agreed to in writing, software # distributed under the License is distributed", "under the License. \"\"\"Redis Handler. The Redis Handler is an asyncio event sink", "a different thread.\"\"\" CONNECT_TIMEOUT = 5 def redis_server(self): \"\"\"Needs to be subclassed to", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "thing that happens is that multiple # errors get logged. (Look at subclasses", "an asyncio event sink using a ThreadPoolExecutor to post to Redis. \"\"\" import", "address of the Redis server.\"\"\" pass def __init__(self, event_loop, ttl_grace): self.redis = redis.client.Redis(self.redis_server(),", "'client;{}'.format(client_address) self.redis.incr(k) self.redis.expire(k, self.ttl_grace) return def submit(self, func, *args): \"\"\"Submit a Redis update", "the number of threads, which is 1. #connection_pool=redis.connection.BlockingConnectionPool( #max_connections=2,timeout=5) #) self.executor = ThreadPoolExecutor(max_workers=1)", "ThreadPoolExecutor(max_workers=1) self.event_loop = event_loop self.ttl_grace = ttl_grace # NOTE: This could be protected", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "writing, software # distributed under the License is distributed on an \"AS IS\"", "be protected by a lock, but setting it True is final so it", "= True except Exception as e: if not self.stop: traceback.print_exc() self.stop = True", "Redis network functions is done inside of one of these blocks. \"\"\" try:", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "License. # You may obtain a copy of the License at # #", "import redis class RedisBaseHandler(object): \"\"\"Handles calls to Redis so that they can be", "*_to_redis() methods to update the client.\"\"\" k = 'client;{}'.format(client_address) self.redis.incr(k) self.redis.expire(k, self.ttl_grace) return", "threads, which is 1. #connection_pool=redis.connection.BlockingConnectionPool( #max_connections=2,timeout=5) #) self.executor = ThreadPoolExecutor(max_workers=1) self.event_loop = event_loop", "compliance with the License. # You may obtain a copy of the License", "func(*args) except ConnectionError as e: if not self.stop: logging.error('redis.exceptions.ConnectionError: {}'.format(e)) self.stop = True", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "connect # to anything but localhost. I don't think it matters, the ThreadPoolExecutor", "could be protected by a lock, but setting it True is final so", "= redis.client.Redis(self.redis_server(), decode_responses=True, socket_connect_timeout=self.CONNECT_TIMEOUT ) # NOTE: Tried to do this with a", "# limitations under the License. \"\"\"Redis Handler. The Redis Handler is an asyncio", "run in a different thread.\"\"\" CONNECT_TIMEOUT = 5 def redis_server(self): \"\"\"Needs to be", "which might occur within redis threads. All calling of Redis network functions is", "not use this file except in compliance with the License. # You may", "exceptions which might occur within redis threads. All calling of Redis network functions", "if not self.stop: logging.error('redis.exceptions.ConnectionError: {}'.format(e)) self.stop = True except Exception as e: if", "License, Version 2.0 (the \"License\"); # you may not use this file except", "functions is done inside of one of these blocks. \"\"\" try: func(*args) except", "e: if not self.stop: logging.error('redis.exceptions.ConnectionError: {}'.format(e)) self.stop = True except Exception as e:", "*args): \"\"\"Submit a Redis update to run.\"\"\" if self.stop: self.event_loop.stop() return self.event_loop.run_in_executor(self.executor, func,", "is done inside of one of these blocks. \"\"\" try: func(*args) except ConnectionError", "get logged. (Look at subclasses to see how this is used.) self.stop =", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "self.stop = True except Exception as e: if not self.stop: traceback.print_exc() self.stop =", "by <NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\");", "def redis_server(self): \"\"\"Needs to be subclassed to return the address of the Redis", "{}'.format(e)) self.stop = True except Exception as e: if not self.stop: traceback.print_exc() self.stop", "*args): \"\"\"Encapsulate exceptions which might occur within redis threads. All calling of Redis", "redis_server(self): \"\"\"Needs to be subclassed to return the address of the Redis server.\"\"\"", "# you may not use this file except in compliance with the License.", "agreed to in writing, software # distributed under the License is distributed on", "calling of Redis network functions is done inside of one of these blocks.", "internally by the other *_to_redis() methods to update the client.\"\"\" k = 'client;{}'.format(client_address)", "localhost. I don't think it matters, the ThreadPoolExecutor # should limit the number", "threads. All calling of Redis network functions is done inside of one of", "(the \"License\"); # you may not use this file except in compliance with", "\"\"\" import traceback import asyncio from concurrent.futures import ThreadPoolExecutor import redis class RedisBaseHandler(object):", "True is final so it # it doesn't really matter. Worst thing that", "#connection_pool=redis.connection.BlockingConnectionPool( #max_connections=2,timeout=5) #) self.executor = ThreadPoolExecutor(max_workers=1) self.event_loop = event_loop self.ttl_grace = ttl_grace #", "the other *_to_redis() methods to update the client.\"\"\" k = 'client;{}'.format(client_address) self.redis.incr(k) self.redis.expire(k,", "# Unless required by applicable law or agreed to in writing, software #", "= event_loop self.ttl_grace = ttl_grace # NOTE: This could be protected by a", "the License. \"\"\"Redis Handler. The Redis Handler is an asyncio event sink using", "by applicable law or agreed to in writing, software # distributed under the", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "it matters, the ThreadPoolExecutor # should limit the number of connections to the", "is that multiple # errors get logged. (Look at subclasses to see how", "asyncio from concurrent.futures import ThreadPoolExecutor import redis class RedisBaseHandler(object): \"\"\"Handles calls to Redis", "Redis server.\"\"\" pass def __init__(self, event_loop, ttl_grace): self.redis = redis.client.Redis(self.redis_server(), decode_responses=True, socket_connect_timeout=self.CONNECT_TIMEOUT )", "a Redis update to run.\"\"\" if self.stop: self.event_loop.stop() return self.event_loop.run_in_executor(self.executor, func, *args) return", "one of these blocks. \"\"\" try: func(*args) except ConnectionError as e: if not", "file except in compliance with the License. # You may obtain a copy", "these blocks. \"\"\" try: func(*args) except ConnectionError as e: if not self.stop: logging.error('redis.exceptions.ConnectionError:", "do this with a BlockingConnectionPool but it refused to connect # to anything", "specific language governing permissions and # limitations under the License. \"\"\"Redis Handler. The", "return def submit(self, func, *args): \"\"\"Submit a Redis update to run.\"\"\" if self.stop:", "is used.) self.stop = False return def client_to_redis(self, client_address): \"\"\"Called internally by the", "(Look at subclasses to see how this is used.) self.stop = False return", "License for the specific language governing permissions and # limitations under the License.", "so it # it doesn't really matter. Worst thing that happens is that", "to return the address of the Redis server.\"\"\" pass def __init__(self, event_loop, ttl_grace):", "that happens is that multiple # errors get logged. (Look at subclasses to", "of one of these blocks. \"\"\" try: func(*args) except ConnectionError as e: if", "def redis_executor(self, func, *args): \"\"\"Encapsulate exceptions which might occur within redis threads. All", "it doesn't really matter. Worst thing that happens is that multiple # errors", "to in writing, software # distributed under the License is distributed on an", "implied. # See the License for the specific language governing permissions and #", "\"License\"); # you may not use this file except in compliance with the", "really matter. Worst thing that happens is that multiple # errors get logged.", "self.executor = ThreadPoolExecutor(max_workers=1) self.event_loop = event_loop self.ttl_grace = ttl_grace # NOTE: This could", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "Redis Handler is an asyncio event sink using a ThreadPoolExecutor to post to", "the number of connections to the number of threads, which is 1. #connection_pool=redis.connection.BlockingConnectionPool(", "redis threads. All calling of Redis network functions is done inside of one", "func, *args): \"\"\"Submit a Redis update to run.\"\"\" if self.stop: self.event_loop.stop() return self.event_loop.run_in_executor(self.executor,", "of threads, which is 1. #connection_pool=redis.connection.BlockingConnectionPool( #max_connections=2,timeout=5) #) self.executor = ThreadPoolExecutor(max_workers=1) self.event_loop =", "concurrent.futures import ThreadPoolExecutor import redis class RedisBaseHandler(object): \"\"\"Handles calls to Redis so that", "or implied. # See the License for the specific language governing permissions and", "be run in a different thread.\"\"\" CONNECT_TIMEOUT = 5 def redis_server(self): \"\"\"Needs to", "in a different thread.\"\"\" CONNECT_TIMEOUT = 5 def redis_server(self): \"\"\"Needs to be subclassed", "to connect # to anything but localhost. I don't think it matters, the", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "calls to Redis so that they can be run in a different thread.\"\"\"", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "ConnectionError as e: if not self.stop: logging.error('redis.exceptions.ConnectionError: {}'.format(e)) self.stop = True except Exception", "try: func(*args) except ConnectionError as e: if not self.stop: logging.error('redis.exceptions.ConnectionError: {}'.format(e)) self.stop =", "the specific language governing permissions and # limitations under the License. \"\"\"Redis Handler.", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "#!/usr/bin/python3 # Copyright (c) 2019 by <NAME> # # Licensed under the Apache", "anything but localhost. I don't think it matters, the ThreadPoolExecutor # should limit", "# should limit the number of connections to the number of threads, which", "happens is that multiple # errors get logged. (Look at subclasses to see", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "client_address): \"\"\"Called internally by the other *_to_redis() methods to update the client.\"\"\" k", "<filename>shodohflo/redis_handler.py<gh_stars>1-10 #!/usr/bin/python3 # Copyright (c) 2019 by <NAME> # # Licensed under the", "decode_responses=True, socket_connect_timeout=self.CONNECT_TIMEOUT ) # NOTE: Tried to do this with a BlockingConnectionPool but", "# to anything but localhost. I don't think it matters, the ThreadPoolExecutor #", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "you may not use this file except in compliance with the License. #", "to be subclassed to return the address of the Redis server.\"\"\" pass def", "# NOTE: This could be protected by a lock, but setting it True", "network functions is done inside of one of these blocks. \"\"\" try: func(*args)", "Handler. The Redis Handler is an asyncio event sink using a ThreadPoolExecutor to", "This could be protected by a lock, but setting it True is final", "= False return def client_to_redis(self, client_address): \"\"\"Called internally by the other *_to_redis() methods", "use this file except in compliance with the License. # You may obtain", "is 1. #connection_pool=redis.connection.BlockingConnectionPool( #max_connections=2,timeout=5) #) self.executor = ThreadPoolExecutor(max_workers=1) self.event_loop = event_loop self.ttl_grace =", "the client.\"\"\" k = 'client;{}'.format(client_address) self.redis.incr(k) self.redis.expire(k, self.ttl_grace) return def submit(self, func, *args):", "All calling of Redis network functions is done inside of one of these", "return def redis_executor(self, func, *args): \"\"\"Encapsulate exceptions which might occur within redis threads.", "inside of one of these blocks. \"\"\" try: func(*args) except ConnectionError as e:", "to Redis so that they can be run in a different thread.\"\"\" CONNECT_TIMEOUT", "thread.\"\"\" CONNECT_TIMEOUT = 5 def redis_server(self): \"\"\"Needs to be subclassed to return the", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "False return def client_to_redis(self, client_address): \"\"\"Called internally by the other *_to_redis() methods to", "event_loop self.ttl_grace = ttl_grace # NOTE: This could be protected by a lock,", "pass def __init__(self, event_loop, ttl_grace): self.redis = redis.client.Redis(self.redis_server(), decode_responses=True, socket_connect_timeout=self.CONNECT_TIMEOUT ) # NOTE:", "2.0 (the \"License\"); # you may not use this file except in compliance", "Worst thing that happens is that multiple # errors get logged. (Look at", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "License. \"\"\"Redis Handler. The Redis Handler is an asyncio event sink using a", "# # Unless required by applicable law or agreed to in writing, software", "express or implied. # See the License for the specific language governing permissions", "import ThreadPoolExecutor import redis class RedisBaseHandler(object): \"\"\"Handles calls to Redis so that they", "limitations under the License. \"\"\"Redis Handler. The Redis Handler is an asyncio event", "to Redis. \"\"\" import traceback import asyncio from concurrent.futures import ThreadPoolExecutor import redis", "logging.error('redis.exceptions.ConnectionError: {}'.format(e)) self.stop = True except Exception as e: if not self.stop: traceback.print_exc()", "either express or implied. # See the License for the specific language governing", "different thread.\"\"\" CONNECT_TIMEOUT = 5 def redis_server(self): \"\"\"Needs to be subclassed to return", "governing permissions and # limitations under the License. \"\"\"Redis Handler. The Redis Handler", "to the number of threads, which is 1. #connection_pool=redis.connection.BlockingConnectionPool( #max_connections=2,timeout=5) #) self.executor =", "ThreadPoolExecutor import redis class RedisBaseHandler(object): \"\"\"Handles calls to Redis so that they can", "(c) 2019 by <NAME> # # Licensed under the Apache License, Version 2.0", "the address of the Redis server.\"\"\" pass def __init__(self, event_loop, ttl_grace): self.redis =", "= ThreadPoolExecutor(max_workers=1) self.event_loop = event_loop self.ttl_grace = ttl_grace # NOTE: This could be", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "def __init__(self, event_loop, ttl_grace): self.redis = redis.client.Redis(self.redis_server(), decode_responses=True, socket_connect_timeout=self.CONNECT_TIMEOUT ) # NOTE: Tried", "update the client.\"\"\" k = 'client;{}'.format(client_address) self.redis.incr(k) self.redis.expire(k, self.ttl_grace) return def submit(self, func,", "# Copyright (c) 2019 by <NAME> # # Licensed under the Apache License,", "CONNECT_TIMEOUT = 5 def redis_server(self): \"\"\"Needs to be subclassed to return the address", "import traceback import asyncio from concurrent.futures import ThreadPoolExecutor import redis class RedisBaseHandler(object): \"\"\"Handles", "ThreadPoolExecutor to post to Redis. \"\"\" import traceback import asyncio from concurrent.futures import", "of Redis network functions is done inside of one of these blocks. \"\"\"", "the License. # You may obtain a copy of the License at #", "#) self.executor = ThreadPoolExecutor(max_workers=1) self.event_loop = event_loop self.ttl_grace = ttl_grace # NOTE: This", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "BlockingConnectionPool but it refused to connect # to anything but localhost. I don't", "func, *args): \"\"\"Encapsulate exceptions which might occur within redis threads. All calling of", "self.ttl_grace) return def submit(self, func, *args): \"\"\"Submit a Redis update to run.\"\"\" if", "return def client_to_redis(self, client_address): \"\"\"Called internally by the other *_to_redis() methods to update", "server.\"\"\" pass def __init__(self, event_loop, ttl_grace): self.redis = redis.client.Redis(self.redis_server(), decode_responses=True, socket_connect_timeout=self.CONNECT_TIMEOUT ) #", "5 def redis_server(self): \"\"\"Needs to be subclassed to return the address of the", "used.) self.stop = False return def client_to_redis(self, client_address): \"\"\"Called internally by the other", "to post to Redis. \"\"\" import traceback import asyncio from concurrent.futures import ThreadPoolExecutor", "redis class RedisBaseHandler(object): \"\"\"Handles calls to Redis so that they can be run", "by the other *_to_redis() methods to update the client.\"\"\" k = 'client;{}'.format(client_address) self.redis.incr(k)", "I don't think it matters, the ThreadPoolExecutor # should limit the number of", "as e: if not self.stop: logging.error('redis.exceptions.ConnectionError: {}'.format(e)) self.stop = True except Exception as", "with the License. # You may obtain a copy of the License at", "a ThreadPoolExecutor to post to Redis. \"\"\" import traceback import asyncio from concurrent.futures", "might occur within redis threads. All calling of Redis network functions is done", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "which is 1. #connection_pool=redis.connection.BlockingConnectionPool( #max_connections=2,timeout=5) #) self.executor = ThreadPoolExecutor(max_workers=1) self.event_loop = event_loop self.ttl_grace", "ThreadPoolExecutor # should limit the number of connections to the number of threads,", "\"\"\"Encapsulate exceptions which might occur within redis threads. All calling of Redis network", "Redis. \"\"\" import traceback import asyncio from concurrent.futures import ThreadPoolExecutor import redis class", "law or agreed to in writing, software # distributed under the License is", "the License for the specific language governing permissions and # limitations under the", "except ConnectionError as e: if not self.stop: logging.error('redis.exceptions.ConnectionError: {}'.format(e)) self.stop = True except", "Handler is an asyncio event sink using a ThreadPoolExecutor to post to Redis.", "\"\"\"Called internally by the other *_to_redis() methods to update the client.\"\"\" k =", "Redis update to run.\"\"\" if self.stop: self.event_loop.stop() return self.event_loop.run_in_executor(self.executor, func, *args) return def", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "self.stop: logging.error('redis.exceptions.ConnectionError: {}'.format(e)) self.stop = True except Exception as e: if not self.stop:", "self.stop = False return def client_to_redis(self, client_address): \"\"\"Called internally by the other *_to_redis()", "for the specific language governing permissions and # limitations under the License. \"\"\"Redis", "event sink using a ThreadPoolExecutor to post to Redis. \"\"\" import traceback import", "methods to update the client.\"\"\" k = 'client;{}'.format(client_address) self.redis.incr(k) self.redis.expire(k, self.ttl_grace) return def", "self.event_loop.run_in_executor(self.executor, func, *args) return def redis_executor(self, func, *args): \"\"\"Encapsulate exceptions which might occur", "in compliance with the License. # You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "to see how this is used.) self.stop = False return def client_to_redis(self, client_address):", "this with a BlockingConnectionPool but it refused to connect # to anything but", "to anything but localhost. I don't think it matters, the ThreadPoolExecutor # should", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "permissions and # limitations under the License. \"\"\"Redis Handler. The Redis Handler is", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "matter. Worst thing that happens is that multiple # errors get logged. (Look", "NOTE: This could be protected by a lock, but setting it True is", "See the License for the specific language governing permissions and # limitations under", "def client_to_redis(self, client_address): \"\"\"Called internally by the other *_to_redis() methods to update the", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "# NOTE: Tried to do this with a BlockingConnectionPool but it refused to", "event_loop, ttl_grace): self.redis = redis.client.Redis(self.redis_server(), decode_responses=True, socket_connect_timeout=self.CONNECT_TIMEOUT ) # NOTE: Tried to do", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "by a lock, but setting it True is final so it # it", "self.redis.incr(k) self.redis.expire(k, self.ttl_grace) return def submit(self, func, *args): \"\"\"Submit a Redis update to", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "NOTE: Tried to do this with a BlockingConnectionPool but it refused to connect", "this is used.) self.stop = False return def client_to_redis(self, client_address): \"\"\"Called internally by", "logged. (Look at subclasses to see how this is used.) self.stop = False", "number of threads, which is 1. #connection_pool=redis.connection.BlockingConnectionPool( #max_connections=2,timeout=5) #) self.executor = ThreadPoolExecutor(max_workers=1) self.event_loop", "it # it doesn't really matter. Worst thing that happens is that multiple", "so that they can be run in a different thread.\"\"\" CONNECT_TIMEOUT = 5", "to update the client.\"\"\" k = 'client;{}'.format(client_address) self.redis.incr(k) self.redis.expire(k, self.ttl_grace) return def submit(self,", "subclasses to see how this is used.) self.stop = False return def client_to_redis(self,", "1. #connection_pool=redis.connection.BlockingConnectionPool( #max_connections=2,timeout=5) #) self.executor = ThreadPoolExecutor(max_workers=1) self.event_loop = event_loop self.ttl_grace = ttl_grace", "think it matters, the ThreadPoolExecutor # should limit the number of connections to", "that they can be run in a different thread.\"\"\" CONNECT_TIMEOUT = 5 def", ") # NOTE: Tried to do this with a BlockingConnectionPool but it refused", "with a BlockingConnectionPool but it refused to connect # to anything but localhost.", "Version 2.0 (the \"License\"); # you may not use this file except in", "# it doesn't really matter. Worst thing that happens is that multiple #", "be subclassed to return the address of the Redis server.\"\"\" pass def __init__(self,", "except in compliance with the License. # You may obtain a copy of", "submit(self, func, *args): \"\"\"Submit a Redis update to run.\"\"\" if self.stop: self.event_loop.stop() return", "don't think it matters, the ThreadPoolExecutor # should limit the number of connections", "language governing permissions and # limitations under the License. \"\"\"Redis Handler. The Redis", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "blocks. \"\"\" try: func(*args) except ConnectionError as e: if not self.stop: logging.error('redis.exceptions.ConnectionError: {}'.format(e))", "client.\"\"\" k = 'client;{}'.format(client_address) self.redis.incr(k) self.redis.expire(k, self.ttl_grace) return def submit(self, func, *args): \"\"\"Submit", "not self.stop: logging.error('redis.exceptions.ConnectionError: {}'.format(e)) self.stop = True except Exception as e: if not", "class RedisBaseHandler(object): \"\"\"Handles calls to Redis so that they can be run in", "can be run in a different thread.\"\"\" CONNECT_TIMEOUT = 5 def redis_server(self): \"\"\"Needs", "occur within redis threads. All calling of Redis network functions is done inside", "from concurrent.futures import ThreadPoolExecutor import redis class RedisBaseHandler(object): \"\"\"Handles calls to Redis so", "to do this with a BlockingConnectionPool but it refused to connect # to", "self.redis.expire(k, self.ttl_grace) return def submit(self, func, *args): \"\"\"Submit a Redis update to run.\"\"\"", "the ThreadPoolExecutor # should limit the number of connections to the number of", "they can be run in a different thread.\"\"\" CONNECT_TIMEOUT = 5 def redis_server(self):", "matters, the ThreadPoolExecutor # should limit the number of connections to the number", "a lock, but setting it True is final so it # it doesn't", "of connections to the number of threads, which is 1. #connection_pool=redis.connection.BlockingConnectionPool( #max_connections=2,timeout=5) #)", "it True is final so it # it doesn't really matter. Worst thing", "subclassed to return the address of the Redis server.\"\"\" pass def __init__(self, event_loop,", "self.event_loop = event_loop self.ttl_grace = ttl_grace # NOTE: This could be protected by", "self.stop: self.event_loop.stop() return self.event_loop.run_in_executor(self.executor, func, *args) return def redis_executor(self, func, *args): \"\"\"Encapsulate exceptions", "but it refused to connect # to anything but localhost. I don't think", "\"\"\"Redis Handler. The Redis Handler is an asyncio event sink using a ThreadPoolExecutor", "#max_connections=2,timeout=5) #) self.executor = ThreadPoolExecutor(max_workers=1) self.event_loop = event_loop self.ttl_grace = ttl_grace # NOTE:", "sink using a ThreadPoolExecutor to post to Redis. \"\"\" import traceback import asyncio", "Copyright (c) 2019 by <NAME> # # Licensed under the Apache License, Version", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "asyncio event sink using a ThreadPoolExecutor to post to Redis. \"\"\" import traceback", "setting it True is final so it # it doesn't really matter. Worst", "func, *args) return def redis_executor(self, func, *args): \"\"\"Encapsulate exceptions which might occur within", "self.ttl_grace = ttl_grace # NOTE: This could be protected by a lock, but" ]
[ "nn def group_norm(out_channels): num_groups = 32 if out_channels % 32 == 0: return", "group_norm(out_channels): num_groups = 32 if out_channels % 32 == 0: return nn.GroupNorm(num_groups, out_channels)", "32 if out_channels % 32 == 0: return nn.GroupNorm(num_groups, out_channels) else: return nn.GroupNorm(num_groups", "if out_channels % 32 == 0: return nn.GroupNorm(num_groups, out_channels) else: return nn.GroupNorm(num_groups //", "torch import nn def group_norm(out_channels): num_groups = 32 if out_channels % 32 ==", "def group_norm(out_channels): num_groups = 32 if out_channels % 32 == 0: return nn.GroupNorm(num_groups,", "from torch import nn def group_norm(out_channels): num_groups = 32 if out_channels % 32", "<gh_stars>10-100 from torch import nn def group_norm(out_channels): num_groups = 32 if out_channels %", "% 32 == 0: return nn.GroupNorm(num_groups, out_channels) else: return nn.GroupNorm(num_groups // 2, out_channels)", "num_groups = 32 if out_channels % 32 == 0: return nn.GroupNorm(num_groups, out_channels) else:", "= 32 if out_channels % 32 == 0: return nn.GroupNorm(num_groups, out_channels) else: return", "out_channels % 32 == 0: return nn.GroupNorm(num_groups, out_channels) else: return nn.GroupNorm(num_groups // 2,", "import nn def group_norm(out_channels): num_groups = 32 if out_channels % 32 == 0:" ]
[ "ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"''\", '\\n\\n') _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ", "ㅄㅎㄴ ㄷㅎㄷ', \"2.5+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄷㅎㄷ', \"4+0i\") _test('(ㄱ ㄱ", "ㄱㅀㄹ', \"'불꽃'\", '불\\n꽃') _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄷㅎㄷ', \"{}\") _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄴ ㄷ ㅅㅈㅎㄷ ㅅㅈㅎㄱ", "ㄴㄱ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") def test_floor_div(self): _test = self._assert_execute _test('ㄱ", "ㅅㅎㄷ) ㄷ ㄱㅎㄷ', \"1.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄱㅎㄷ', \"1+0i\") _test('(ㄷ ㄴㄱ", "def test_multiply(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"0\") _test('ㄴㄱ ㄴ", "_test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄷㅎㄷ', \"2.5\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄷㅎㄷ', \"2.5+0i\")", "ㄷ ㄷㅎㄷ', \"2.5\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄷㅎㄷ', \"2.5+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ)", "ㄷㅎㄷ ㅎㅎㄴ', \"b''\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㅁㅈㅎㄱ ㄱ ㄴ", "\"0i\") _test('ㄱ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ', \"-1+0i\") _test('ㄴ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ ㄱ", "ㄷ ㅅㅈㅎㄷ ㄷㅎㄷ', \"{0: 1, 1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ", "(ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄱㅎㄹ', \"True\") def test_add(self): _test = self._assert_execute _test('ㄱ ㄴ", "def test_add(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄷㅎㅁ', \"6\") _test('ㄴㄱ ㄴ", "ㄷ ㄱㅎㄷ', \"1.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄱㅎㄷ', \"1+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ)", "_test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄷㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ", "ㄴㄶㄷ', \"1\") _test('ㄴㄱ ㄴ ㄴㄶㄷ', \"-1\") _test('ㄷ ㄴㄱ ㄴㄶㄷ', \"-2\") _test('ㄹ ㄷ ㄴㄶㄷ',", "2: 4}\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄴ ㅎㅎㄴ', \"b''\") _test('(ㄱ", "ㅎㅎㄴ', \"b''\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ)", "\"'불꽃'\", '불\\n꽃') _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄷㅎㄷ', \"{}\") _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄴ ㄷ ㅅㅈㅎㄷ ㅅㅈㅎㄱ ㄷㅎㅁ',", "ㄱㅎㅁ', \"-6\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄱㅎㄷ', \"1.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ", "self._assert_execute _test('ㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㄴㅁㅎㄷ', \"0\")", "ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄱㅎㄷ', \"1+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄱㅎㄷ',", "ㄴㅁㅎㄷ', \"0\") _test('ㄹ ㄷ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㅁㅎㄷ',", "ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄱㅎㄷ', \"1+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄱㅎㄷ', \"5+0i\")", "ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄱㅎㄹ', \"True\") def test_add(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ", "_test = self._assert_execute _test('ㄱ ㄴ ㅅㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㅅㅎㄷ', \"-1\") _test('ㄷ ㄴㄱ", "2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄴ ㄷ ㅅㅈㅎㄷ ㄷㅎㄷ', \"{0: 1, 1: 2}\") _test('ㄱ", "_test('ㄺ ㄷㄱ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㅁㅎㄷ', \"0.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ)", "\"-1\") _test('ㄷ ㄴㄱ ㄴㄶㄷ', \"-2\") _test('ㄹ ㄷ ㄴㄶㄷ', \"1\") _test('ㄺ ㄷ ㄴㄶㄷ', \"-1\")", "_test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄷㅎㄷ', \"{}\") _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄴ ㄷ ㅅㅈㅎㄷ ㅅㅈㅎㄱ ㄷㅎㅁ', \"{1: 2}\")", "ㄴ ㄷ ㅅㅈㅎㄷ ㅅㅈㅎㄱ ㄷㅎㅁ', \"{1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄴ ㄷ ㅅㅈㅎㄷ", "5}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㄷ ㅁ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1,", "ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"''\", '\\n\\n') _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"'불꽃'\",", "ㄴㄶㄷ', \"-1\") _test('ㄷ ㄴㄱ ㄴㄶㄷ', \"-2\") _test('ㄹ ㄷ ㄴㄶㄷ', \"1\") _test('ㄺ ㄷ ㄴㄶㄷ',", "ㄷㄱ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷㄱ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㅁㅎㄷ', \"0.0\")", "(ㄱ ㄴ ㅈㅎㄷ) ㄷㅎㄷ', \"True\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄷㅎㄹ',", "1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㅁ ㅂ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0:", "ㄴ ㄴㄱ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") def test_floor_div(self): _test = self._assert_execute", "ㅁㅀㄴ ㅁㅀㄱ ㄷㅎㄷ', \"[0]\") _test('ㄱ ㅁㅀㄴ ㄴ ㄷ ㅁㅀㄷ ㄷㅎㄷ', \"[0, 1, 2]\")", "ㅄㅎㄷ) ㄷㅎㄷ', \"4+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄷㅎㄷ', \"False\") _test('(ㄱ ㄱ", "class TestArithmetics(TestBase): def test_multiply(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"0\")", "ㄴ ㄴㄶㄷ', \"0\") _test('ㄴ ㄴ ㄴㄶㄷ', \"1\") _test('ㄴㄱ ㄴ ㄴㄶㄷ', \"-1\") _test('ㄷ ㄴㄱ", "ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄷㅎㄷ', \"2.5+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄷㅎㄷ',", "ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") _test('(ㄴ ㄴ ㅄㅎㄷ ㄴㄱ ㅅㅎㄷ ㄷ ㄱㅎㄷ) ㄴ ㄴㄱ", "ㄴ ㄷ ㄹㄱ ㄷㅎㅁ', \"-1\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄷㅎㄷ', \"2.5\") _test('(ㄷ ㄴㄱ", "_test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㄴ ㅁㅈㅎㄴ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ", "_test('ㄹ ㄷㄱ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷㄱ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㅁㅎㄷ',", "self._assert_execute _test('ㄱ ㄴ ㄴㄶㄷ', \"0\") _test('ㄴ ㄴ ㄴㄶㄷ', \"1\") _test('ㄴㄱ ㄴ ㄴㄶㄷ', \"-1\")", "ㅁㅀㄴ ㄷㅎㄴ', \"[0]\") _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"''\", '\\n\\n') _test('ㅀㄱ", "\"[0, 1, 2]\") _test('ㄱ ㅁㅀㄴ ㄷㅎㄴ', \"[0]\") _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ", "ㄴ ㅈㅎㄷ) ㄷㅎㄷ', \"True\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄷㅎㄹ', \"True\")", "ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄷㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄷㅎㄷ',", "ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30\\\\x31'\") def test_exponentiate(self): _test = self._assert_execute _test('ㄱ ㄴ ㅅㅎㄷ', \"0\")", "ㄷㅎㄷ', \"2.5\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄷㅎㄷ', \"2.5+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ", "TestBase class TestArithmetics(TestBase): def test_multiply(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ',", "\"1\") _test('ㄺ ㄷㄱ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㅁㅎㄷ', \"0.0\") _test('(ㄷ ㄴㄱ", "ㄷ ㅅㅈㅎㄷ ㅅㅈㅎㄱ ㄷㅎㅁ', \"{1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄴ ㄷ ㅅㅈㅎㄷ ㄷㅎㄷ',", "\"1\") _test('ㄺ ㄷ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷㄱ ㄴㅁㅎㄷ', \"-1\")", "\"0\") _test('ㄴㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"-6\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄱㅎㄷ', \"1.0\")", "ㄴㄶㄷ', \"-1\") _test('ㄺ ㄷㄱ ㄴㄶㄷ', \"1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㄶㄷ', \"6.0\") _test('(ㄷ", "(ㄷ ㄴ ㅄㅎㄷ) ㄷㅎㄷ', \"4+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄷㅎㄷ', \"False\")", "ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"''\", '\\n\\n') _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ',", "ㄴㄱ ㅅㅎㄷ) ㄷ ㄱㅎㄷ', \"1.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄱㅎㄷ', \"1+0i\") _test('(ㄷ", "2: 3, 4: 5}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㄷ ㅁ ㅅㅈㅎㄷ", "ㄷㅎㄷ', \"[]\") _test('ㄱ ㅁㅀㄴ ㅁㅀㄱ ㄷㅎㄷ', \"[0]\") _test('ㄱ ㅁㅀㄴ ㄴ ㄷ ㅁㅀㄷ ㄷㅎㄷ',", "\"True\") def test_floor_div(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㄶㄷ', \"0\") _test('ㄴ ㄴ ㄴㄶㄷ',", "ㅄㅎㄷ) ㄱㅎㄷ', \"5+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ", "ㅂ ㅂㅎㄷㅎㄷ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b''\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ", "ㄴㄱ ㄴㅁㅎㄷ', \"0\") _test('ㄹ ㄷ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ ㄷㄱ", "ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"'불꽃'\", '불\\n꽃') _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄷㅎㄷ', \"{}\") _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄴ ㄷ", "ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄷㅎㄷ', \"True\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ)", "_test('ㅁㅀㄱ ㅁㅀㄱ ㄷㅎㄷ', \"[]\") _test('ㄱ ㅁㅀㄴ ㅁㅀㄱ ㄷㅎㄷ', \"[0]\") _test('ㄱ ㅁㅀㄴ ㄴ ㄷ", "_test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㄷ ㅁ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2:", "ㅄㅎㄷ ㄷ ㅅㅎㄷ', \"-1+0i\") _test('ㄴ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ ㄱ ㄷ ㅄㅎㄷ ㅂ", "ㅅㅎㄷ', \"0i\") _test('ㄱ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ', \"-1+0i\") _test('ㄴ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ", "ㄷㄱ ㄴㄶㄷ', \"1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㄶㄷ', \"6.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ", "ㅁㅀㄱ ㄷㅎㄷ', \"[0]\") _test('ㄱ ㅁㅀㄴ ㄴ ㄷ ㅁㅀㄷ ㄷㅎㄷ', \"[0, 1, 2]\") _test('ㄱ", "ㄷㅎㄹ', \"{0: 1, 2: 4}\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄴ", "\"1\") _test('ㄴㄱ ㄴ ㄴㄶㄷ', \"-1\") _test('ㄷ ㄴㄱ ㄴㄶㄷ', \"-2\") _test('ㄹ ㄷ ㄴㄶㄷ', \"1\")", "(ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄷㅎㄹ', \"True\") _test('ㅁㅀㄱ ㅁㅀㄱ ㄷㅎㄷ', \"[]\") _test('ㄱ ㅁㅀㄴ ㅁㅀㄱ", "ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄱㅎㄹ', \"True\") def test_add(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ", "1, 2: 4}\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄴ ㅎㅎㄴ', \"b''\")", "ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") _test('(ㄴ ㄴ ㅄㅎㄷ ㄴㄱ ㅅㅎㄷ ㄷ ㄱㅎㄷ)", "ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"''\", '\\n\\n') _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ", "ㄴ ㄴㅎㄷ) ㄷㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄷㅎㄷ', \"True\") _test('(ㄱ", "_test('ㄷ ㄴㄱ ㄴㅁㅎㄷ', \"0\") _test('ㄹ ㄷ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ", "\"4+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄷㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ", "ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30'\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ)", "_test('ㄺ ㄷㄱ ㄴㄶㄷ', \"1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㄶㄷ', \"6.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ)", "ㄷ ㅁㅀㄷ ㄷㅎㄷ', \"[0, 1, 2]\") _test('ㄱ ㅁㅀㄴ ㄷㅎㄴ', \"[0]\") _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ", "ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"'불꽃'\", '불\\n꽃') _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄷㅎㄷ', \"{}\") _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ", "ㄷ ㄹ ㅅㅈㅎㄷ ㅁ ㅂ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 3, 4: 5}\")", "ㅂㅎㅀㄷ', \"True\") def test_floor_div(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㄶㄷ', \"0\") _test('ㄴ ㄴ", "ㅅㅈㅎㄷ ㄷㅎㄷ', \"{0: 1, 1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㅁ", "ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30'\")", "ㅁ ㅂ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 3, 4: 5}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ", "ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄷㅎㄷ', \"2.5+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄷㅎㄷ', \"4+0i\")", "\"[]\") _test('ㄱ ㅁㅀㄴ ㅁㅀㄱ ㄷㅎㄷ', \"[0]\") _test('ㄱ ㅁㅀㄴ ㄴ ㄷ ㅁㅀㄷ ㄷㅎㄷ', \"[0,", "ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷㄱ ㄴㅁㅎㄷ',", "ㄷㅎㄷ', \"{}\") _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄴ ㄷ ㅅㅈㅎㄷ ㅅㅈㅎㄱ ㄷㅎㅁ', \"{1: 2}\") _test('ㄱ ㄴ", "(ㄷ ㄴ ㅄㅎㄷ) ㄱㅎㄷ', \"5+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄱㅎㄷ', \"False\")", "ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㄴ ㅁㅈㅎㄴ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30\\\\x31'\")", "= self._assert_execute _test('ㄱ ㄴ ㅅㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㅅㅎㄷ', \"-1\") _test('ㄷ ㄴㄱ ㅅㅎㄷ',", "ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄷ ㄴㄱ ㄴㅁㅎㄷ', \"0\") _test('ㄹ ㄷ", "ㄱㅇㄱㅎㄷㅎㄴ) (ㄴ ㅁㅈㅎㄴ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30\\\\x31'\") def test_exponentiate(self): _test =", "\"False\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄱㅎㄹ', \"True\") def test_add(self): _test", "\"-1\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄷㅎㄷ', \"2.5\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄷㅎㄷ',", "ㅅㅈㅎㄷ ㄴ ㄷ ㅅㅈㅎㄷ ㄷㅎㄷ', \"{0: 1, 1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ", "ㄱㅇㄱㅎㄴ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b''\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ)", "ㄴㄱ ㅅㅎㄷ ㄷ ㄱㅎㄷ) ㄴ ㄴㄱ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") def", "_test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄷㅎㄷ', \"4+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ", "ㄱㅇㄱㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b''\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㅁㅈㅎㄱ ㄱ", "ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㄴㅎㄷ)", "ㄴ ㅅㅎㄷ', \"0i\") _test('ㄱ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ', \"-1+0i\") _test('ㄴ ㄴ ㅄㅎㄷ ㄷ", "ㄴ ㄷ ㄹ ㄱㅎㅁ', \"-6\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄱㅎㄷ', \"1.0\") _test('(ㄷ ㄴㄱ", "(ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b''\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㅁㅈㅎㄱ", "self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄷㅎㅁ', \"6\") _test('ㄴㄱ ㄴ ㄷ ㄹㄱ ㄷㅎㅁ', \"-1\")", "_test('ㄷ ㄴㄱ ㅅㅎㄷ', \"0.5\") _test('ㄴㄱ ㄴㄱ ㅅㅎㄷ', \"-1.0\") _test('ㄱ ㅄㅎㄴ ㄴ ㅅㅎㄷ', \"0i\")", "\"-1\") _test('ㄹ ㄷㄱ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷㄱ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ)", "_test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"''\", '\\n\\n') _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ", "ㅅㅈㅎㄷ ㅁ ㅂ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 3, 4: 5}\") _test('ㄱ ㄴ", "\"True\") def test_add(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄷㅎㅁ', \"6\") _test('ㄴㄱ", "ㅄㅎㄷ ㄷ ㅅㅎㄷ ㄱ ㄷ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") _test('(ㄴ ㄴ", "ㅁㅀㄷ ㄷㅎㄷ', \"[0, 1, 2]\") _test('ㄱ ㅁㅀㄴ ㄷㅎㄴ', \"[0]\") _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ", "self._assert_execute _test('ㄱ ㄴ ㅅㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㅅㅎㄷ', \"-1\") _test('ㄷ ㄴㄱ ㅅㅎㄷ', \"0.5\")", "\"True\") _test('ㅁㅀㄱ ㅁㅀㄱ ㄷㅎㄷ', \"[]\") _test('ㄱ ㅁㅀㄴ ㅁㅀㄱ ㄷㅎㄷ', \"[0]\") _test('ㄱ ㅁㅀㄴ ㄴ", "ㄴ ㅅㅎㄷ', \"-1\") _test('ㄷ ㄴㄱ ㅅㅎㄷ', \"0.5\") _test('ㄴㄱ ㄴㄱ ㅅㅎㄷ', \"-1.0\") _test('ㄱ ㅄㅎㄴ", "ㄷㅎㅁ', \"{1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄴ ㄷ ㅅㅈㅎㄷ ㄷㅎㄷ', \"{0: 1, 1:", "\"-1\") _test('ㄺ ㄷㄱ ㄴㄶㄷ', \"1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㄶㄷ', \"6.0\") _test('(ㄷ ㄴㄱ", "ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄴ ㅎㅎㄴ', \"b''\") _test('(ㄱ ㄴ ㅂ ㅂ ㅂㅎㄷㅎㄷ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) (ㅁㅈㅎㄱ", "ㅅㅈㅎㄷ ㄷ ㅁ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 4}\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㅁㅈㅎㄱ", "2]\") _test('ㄱ ㅁㅀㄴ ㄷㅎㄴ', \"[0]\") _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"''\",", "ㄷ ㄹ ㄷㅎㅁ', \"6\") _test('ㄴㄱ ㄴ ㄷ ㄹㄱ ㄷㅎㅁ', \"-1\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ)", "ㄴㅎㄷ) ㄷㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄷㅎㄷ', \"True\") _test('(ㄱ ㄱ", "2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㅁ ㅂ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1,", "ㅂㅎㄷ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄴ ㅎㅎㄴ', \"b''\") _test('(ㄱ ㄴ ㅂ ㅂ ㅂㅎㄷㅎㄷ)", "import TestBase class TestArithmetics(TestBase): def test_multiply(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ", "ㄷㅎㄴ ㅎㅎㄴ', \"b''\") _test('(ㄱ ㄴ ㅂ ㅂ ㅂㅎㄷㅎㄷ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) ㄷㅎㄷ", "ㅄㅎㄷ ㄴㄱ ㅅㅎㄷ ㄷ ㄱㅎㄷ) ㄴ ㄴㄱ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\")", "\"{0: 1, 1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㅁ ㅂ ㅅㅈㅎㄷ", "(ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30'\") _test('(ㅂ ㅂ", "\"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄷㅎㄷ', \"True\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ", "ㅅㅎㄷ', \"0.5\") _test('ㄴㄱ ㄴㄱ ㅅㅎㄷ', \"-1.0\") _test('ㄱ ㅄㅎㄴ ㄴ ㅅㅎㄷ', \"0i\") _test('ㄱ ㄴ", "self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"0\") _test('ㄴㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"-6\")", "\"{0: 1, 2: 3, 4: 5}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㄷ", "ㄴ ㅂ ㅂ ㅂㅎㄷㅎㄷ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b''\") _test('(ㅂ ㅂ", "ㄷㄱ ㄴㄶㄷ', \"-1\") _test('ㄺ ㄷㄱ ㄴㄶㄷ', \"1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㄶㄷ', \"6.0\")", "ㄴㄱ ㅅㅎㄷ) ㄷ ㄷㅎㄷ', \"2.5\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄷㅎㄷ', \"2.5+0i\") _test('(ㄷ", "ㄴ ㄷ ㄹ ㄱㅎㅁ', \"0\") _test('ㄴㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"-6\") _test('(ㄷ ㄴㄱ", "<filename>test/test_builtins/test_arithmetics.py from test.test_base import TestBase class TestArithmetics(TestBase): def test_multiply(self): _test = self._assert_execute _test('ㄱ", "_test('ㄱ ㅄㅎㄴ ㄴ ㅅㅎㄷ', \"0i\") _test('ㄱ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ', \"-1+0i\") _test('ㄴ ㄴ", "_test('ㄱ ㄴ ㄷ ㄹ ㄷㅎㅁ', \"6\") _test('ㄴㄱ ㄴ ㄷ ㄹㄱ ㄷㅎㅁ', \"-1\") _test('(ㄷ", "_test('ㄴㄱ ㄴㄱ ㅅㅎㄷ', \"-1.0\") _test('ㄱ ㅄㅎㄴ ㄴ ㅅㅎㄷ', \"0i\") _test('ㄱ ㄴ ㅄㅎㄷ ㄷ", "_test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"0\") _test('ㄴㄱ ㄴ ㄷ ㄹ", "def test_modulo(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴ ㄴ ㄴㅁㅎㄷ', \"0\")", "_test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄷㅎㄹ', \"True\") _test('ㅁㅀㄱ ㅁㅀㄱ ㄷㅎㄷ', \"[]\")", "ㄹㄱ ㄷㅎㅁ', \"-1\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄷㅎㄷ', \"2.5\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ", "ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ', \"-1+0i\") _test('ㄴ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ ㄱ ㄷ ㅄㅎㄷ", "\"1.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄱㅎㄷ', \"1+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ", "ㄱㅎㄷ) ㄴ ㄴㄱ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") def test_floor_div(self): _test =", "_test('ㄴㄱ ㄴ ㄷ ㄹㄱ ㄷㅎㅁ', \"-1\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄷㅎㄷ', \"2.5\") _test('(ㄷ", "\"1+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄱㅎㄷ', \"5+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ", "\"True\") _test('(ㄴ ㄴ ㅄㅎㄷ ㄴㄱ ㅅㅎㄷ ㄷ ㄱㅎㄷ) ㄴ ㄴㄱ ㅄㅎㄷ ㅂ ㅅ", "test_multiply(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"0\") _test('ㄴㄱ ㄴ ㄷ", "\"0.5\") _test('ㄴㄱ ㄴㄱ ㅅㅎㄷ', \"-1.0\") _test('ㄱ ㅄㅎㄴ ㄴ ㅅㅎㄷ', \"0i\") _test('ㄱ ㄴ ㅄㅎㄷ", "ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30'\") _test('(ㅂ ㅂ ㅂㅎㄷ)", "_test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ ㄴㄶㄷ', \"0.0\") def test_modulo(self): _test = self._assert_execute _test('ㄱ ㄴ", "\"1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㄶㄷ', \"6.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ ㄴㄶㄷ', \"0.0\")", "\"[0]\") _test('ㄱ ㅁㅀㄴ ㄴ ㄷ ㅁㅀㄷ ㄷㅎㄷ', \"[0, 1, 2]\") _test('ㄱ ㅁㅀㄴ ㄷㅎㄴ',", "_test('ㄱ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ', \"-1+0i\") _test('ㄴ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ ㄱ ㄷ", "\"-1+0i\") _test('ㄴ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ ㄱ ㄷ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ',", "ㄱㅎㄹ', \"True\") def test_add(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄷㅎㅁ', \"6\")", "_test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"'불꽃'\", '불\\n꽃') _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄷㅎㄷ', \"{}\")", "ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") def test_floor_div(self): _test = self._assert_execute _test('ㄱ ㄴ", "test_add(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄷㅎㅁ', \"6\") _test('ㄴㄱ ㄴ ㄷ", "ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄱㅎㄹ', \"True\") def test_add(self): _test = self._assert_execute _test('ㄱ", "\"{}\") _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄴ ㄷ ㅅㅈㅎㄷ ㅅㅈㅎㄱ ㄷㅎㅁ', \"{1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ", "ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄷㅎㄹ', \"True\") _test('ㅁㅀㄱ ㅁㅀㄱ ㄷㅎㄷ', \"[]\") _test('ㄱ ㅁㅀㄴ ㅁㅀㄱ ㄷㅎㄷ',", "ㄷㅎㄷ', \"True\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄷㅎㄹ', \"True\") _test('ㅁㅀㄱ ㅁㅀㄱ", "\"True\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄷㅎㄹ', \"True\") _test('ㅁㅀㄱ ㅁㅀㄱ ㄷㅎㄷ',", "\"{0: 1, 2: 4}\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄴ ㅎㅎㄴ',", "_test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ", "\"b''\") _test('(ㄱ ㄴ ㅂ ㅂ ㅂㅎㄷㅎㄷ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b''\")", "4}\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄴ ㅎㅎㄴ', \"b''\") _test('(ㄱ ㄴ", "_test('ㄴㄱ ㄴ ㅅㅎㄷ', \"-1\") _test('ㄷ ㄴㄱ ㅅㅎㄷ', \"0.5\") _test('ㄴㄱ ㄴㄱ ㅅㅎㄷ', \"-1.0\") _test('ㄱ", "ㅎㅎㄴ', \"b'\\\\x30\\\\x31'\") def test_exponentiate(self): _test = self._assert_execute _test('ㄱ ㄴ ㅅㅎㄷ', \"0\") _test('ㄴㄱ ㄴ", "test_floor_div(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㄶㄷ', \"0\") _test('ㄴ ㄴ ㄴㄶㄷ', \"1\") _test('ㄴㄱ", "ㄱㅎㄷ', \"5+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ)", "'불\\n꽃') _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄷㅎㄷ', \"{}\") _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄴ ㄷ ㅅㅈㅎㄷ ㅅㅈㅎㄱ ㄷㅎㅁ', \"{1:", "ㄴㄶㄷ', \"6.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ ㄴㄶㄷ', \"0.0\") def test_modulo(self): _test = self._assert_execute", "ㄴㄶㄷ', \"-2\") _test('ㄹ ㄷ ㄴㄶㄷ', \"1\") _test('ㄺ ㄷ ㄴㄶㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㄶㄷ',", "ㄷㅎㅁ', \"-1\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄷㅎㄷ', \"2.5\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ", "ㄷㄱ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㅁㅎㄷ', \"0.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ", "ㅄㅎㄴ ㄴ ㅅㅎㄷ', \"0i\") _test('ㄱ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ', \"-1+0i\") _test('ㄴ ㄴ ㅄㅎㄷ", "ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄱㅎㄷ',", "(ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30'\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ", "_test('ㄹ ㄷㄱ ㄴㄶㄷ', \"-1\") _test('ㄺ ㄷㄱ ㄴㄶㄷ', \"1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㄶㄷ',", "= self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄷㅎㅁ', \"6\") _test('ㄴㄱ ㄴ ㄷ ㄹㄱ ㄷㅎㅁ',", "\"0\") _test('ㄴㄱ ㄴ ㅅㅎㄷ', \"-1\") _test('ㄷ ㄴㄱ ㅅㅎㄷ', \"0.5\") _test('ㄴㄱ ㄴㄱ ㅅㅎㄷ', \"-1.0\")", "ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") def test_floor_div(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㄶㄷ',", "ㄴ ㅅㅈㅎㄷ ㄴ ㄷ ㅅㅈㅎㄷ ㄷㅎㄷ', \"{0: 1, 1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ", "_test('ㄺ ㄷ ㄴㄶㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㄶㄷ', \"-1\") _test('ㄺ ㄷㄱ ㄴㄶㄷ', \"1\") _test('ㄹ", "_test('ㄺ ㄷ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷㄱ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ", "\"2.5+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄷㅎㄷ', \"4+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ", "_test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄱㅎㄷ', \"1.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄱㅎㄷ', \"1+0i\")", "ㄹ ㄴㄶㄷ', \"0.0\") def test_modulo(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴ", "(ㅈㅈㅎㄱ) ㄷㅎㄹ', \"True\") _test('ㅁㅀㄱ ㅁㅀㄱ ㄷㅎㄷ', \"[]\") _test('ㄱ ㅁㅀㄴ ㅁㅀㄱ ㄷㅎㄷ', \"[0]\") _test('ㄱ", "_test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄴ ㄷ ㅅㅈㅎㄷ ㅅㅈㅎㄱ ㄷㅎㅁ', \"{1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄴ", "ㄴㄶㄷ', \"1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㄶㄷ', \"6.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ ㄴㄶㄷ',", "ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 3, 4: 5}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ", "ㄷ ㅄㅎㄴ ㄷㅎㄷ', \"2.5+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄷㅎㄷ', \"4+0i\") _test('(ㄱ", "ㄴ ㅄㅎㄷ) ㄱㅎㄷ', \"5+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ", "\"-1\") _test('ㄹ ㄷㄱ ㄴㄶㄷ', \"-1\") _test('ㄺ ㄷㄱ ㄴㄶㄷ', \"1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ)", "_test('ㄷ ㄴㄱ ㄴㄶㄷ', \"-2\") _test('ㄹ ㄷ ㄴㄶㄷ', \"1\") _test('ㄺ ㄷ ㄴㄶㄷ', \"-1\") _test('ㄹ", "ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄷㅎㄷ', \"4+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ)", "ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄷ ㄴㄱ", "ㅂ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 3, 4: 5}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ", "ㄹ ㄱㅎㅁ', \"0\") _test('ㄴㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"-6\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ", "\"2.5\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄷㅎㄷ', \"2.5+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ", "_test('ㄹ ㄷ ㄴㄶㄷ', \"1\") _test('ㄺ ㄷ ㄴㄶㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㄶㄷ', \"-1\") _test('ㄺ", "ㄷ ㄴㄶㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㄶㄷ', \"-1\") _test('ㄺ ㄷㄱ ㄴㄶㄷ', \"1\") _test('ㄹ (ㄷ", "ㄷㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄷㅎㄷ', \"True\") _test('(ㄱ ㄱ ㄴㅎㄷ)", "ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄷ ㄴㄱ ㄴㅁㅎㄷ', \"0\") _test('ㄹ ㄷ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷ", "ㄷ ㄴㄶㄷ', \"1\") _test('ㄺ ㄷ ㄴㄶㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㄶㄷ', \"-1\") _test('ㄺ ㄷㄱ", "_test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ',", "\"0\") _test('ㄹ ㄷ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㅁㅎㄷ', \"1\")", "\"5+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ", "ㄷㅎㄷ', \"2.5+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄷㅎㄷ', \"4+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ)", "test_modulo(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴㄱ", "ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄱㅎㄹ', \"True\") def test_add(self): _test = self._assert_execute", "_test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄷㅎㄷ', \"True\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ", "_test('ㄴㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"-6\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄱㅎㄷ', \"1.0\") _test('(ㄷ", "ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30'\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㄴ ㅁㅈㅎㄴ ㄱ", "ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㄴ ㅁㅈㅎㄴ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ',", "_test('(ㄴ ㄴ ㅄㅎㄷ ㄴㄱ ㅅㅎㄷ ㄷ ㄱㅎㄷ) ㄴ ㄴㄱ ㅄㅎㄷ ㅂ ㅅ ㄱ", "TestArithmetics(TestBase): def test_multiply(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"0\") _test('ㄴㄱ", "ㄷㅎㄷ', \"[0]\") _test('ㄱ ㅁㅀㄴ ㄴ ㄷ ㅁㅀㄷ ㄷㅎㄷ', \"[0, 1, 2]\") _test('ㄱ ㅁㅀㄴ", "ㄷ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷㄱ", "ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"'불꽃'\", '불\\n꽃') _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄷㅎㄷ', \"{}\") _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄴ", "ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30\\\\x31'\") def test_exponentiate(self): _test = self._assert_execute _test('ㄱ ㄴ ㅅㅎㄷ',", "ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㄷ ㅁ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 4}\") _test('(ㅂ", "ㄴㄶㄷ', \"0\") _test('ㄴ ㄴ ㄴㄶㄷ', \"1\") _test('ㄴㄱ ㄴ ㄴㄶㄷ', \"-1\") _test('ㄷ ㄴㄱ ㄴㄶㄷ',", "_test('ㄴ ㄴ ㄴㄶㄷ', \"1\") _test('ㄴㄱ ㄴ ㄴㄶㄷ', \"-1\") _test('ㄷ ㄴㄱ ㄴㄶㄷ', \"-2\") _test('ㄹ", "ㄴㅁㅎㄷ', \"-1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㅁㅎㄷ', \"0.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ ㄴㅁㅎㄷ',", "ㅄㅎㄴ ㄱㅎㄷ', \"1+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄱㅎㄷ', \"5+0i\") _test('(ㄱ ㄱ", "ㄴㅁㅎㄷ', \"0\") _test('ㄴ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄷ ㄴㄱ ㄴㅁㅎㄷ',", "_test('ㄴㄱ ㄴ ㄴㄶㄷ', \"-1\") _test('ㄷ ㄴㄱ ㄴㄶㄷ', \"-2\") _test('ㄹ ㄷ ㄴㄶㄷ', \"1\") _test('ㄺ", "ㄷ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") _test('(ㄴ ㄴ ㅄㅎㄷ ㄴㄱ ㅅㅎㄷ ㄷ", "ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㅁ ㅂ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 3, 4:", "ㄷ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷㄱ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ (ㄷ", "ㅅㅎㄷ', \"-1+0i\") _test('ㄴ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ ㄱ ㄷ ㅄㅎㄷ ㅂ ㅅ ㄱ", "ㅁ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 4}\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㅁㅈㅎㄱ ㄱ ㄴ", "ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄷㅎㄹ', \"True\") _test('ㅁㅀㄱ ㅁㅀㄱ ㄷㅎㄷ', \"[]\") _test('ㄱ ㅁㅀㄴ ㅁㅀㄱ ㄷㅎㄷ', \"[0]\")", "(ㅈㅈㅎㄱ) ㄱㅎㄹ', \"True\") def test_add(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄷㅎㅁ',", "ㄴㄱ ㅅㅎㄷ', \"-1.0\") _test('ㄱ ㅄㅎㄴ ㄴ ㅅㅎㄷ', \"0i\") _test('ㄱ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ',", "ㄴㄶㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㄶㄷ', \"-1\") _test('ㄺ ㄷㄱ ㄴㄶㄷ', \"1\") _test('ㄹ (ㄷ ㄴㄱ", "_test('ㄹ ㄷ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㅁㅎㄷ', \"1\") _test('ㄺ", "ㅎㅎㄴ', \"b'\\\\x30'\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㄴ ㅁㅈㅎㄴ ㄱ ㄴ", "\"0\") _test('ㄴㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄷ ㄴㄱ ㄴㅁㅎㄷ', \"0\") _test('ㄹ ㄷ ㄴㅁㅎㄷ', \"1\")", "ㄴㅁㅎㄷ', \"0\") _test('ㄷ ㄴㄱ ㄴㅁㅎㄷ', \"0\") _test('ㄹ ㄷ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷ ㄴㅁㅎㄷ',", "ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄴ ㅎㅎㄴ', \"b''\") _test('(ㄱ ㄴ ㅂ ㅂ ㅂㅎㄷㅎㄷ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ)", "ㅂㅎㅀㄷ', \"True\") _test('(ㄴ ㄴ ㅄㅎㄷ ㄴㄱ ㅅㅎㄷ ㄷ ㄱㅎㄷ) ㄴ ㄴㄱ ㅄㅎㄷ ㅂ", "1, 2]\") _test('ㄱ ㅁㅀㄴ ㄷㅎㄴ', \"[0]\") _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ',", "_test('ㄱ ㄴ ㅅㅈㅎㄷ ㄴ ㄷ ㅅㅈㅎㄷ ㄷㅎㄷ', \"{0: 1, 1: 2}\") _test('ㄱ ㄴ", "ㅅㅎㄷ', \"-1\") _test('ㄷ ㄴㄱ ㅅㅎㄷ', \"0.5\") _test('ㄴㄱ ㄴㄱ ㅅㅎㄷ', \"-1.0\") _test('ㄱ ㅄㅎㄴ ㄴ", "ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄷㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ)", "_test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ", "ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄷㅎㄷ', \"4+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄷㅎㄷ',", "ㅂ ㅂㅎㄷ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄴ ㅎㅎㄴ', \"b''\") _test('(ㄱ ㄴ ㅂ ㅂ", "(ㄱ ㄴ ㄴㅎㄷ) ㄷㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄷㅎㄷ', \"True\")", "ㄷㅎㄷ', \"{0: 1, 1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㅁ ㅂ", "ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ)", "ㄱㅎㅁ', \"0\") _test('ㄴㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"-6\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄱㅎㄷ',", "ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30'\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ", "ㄷ ㅅㅎㄷ ㄱ ㄷ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") _test('(ㄴ ㄴ ㅄㅎㄷ", "ㄷ ㅁ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 4}\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㅁㅈㅎㄱ ㄱ", "ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷㄱ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㅁㅎㄷ', \"0.0\") _test('(ㄷ", "ㄹ ㄱㅎㅁ', \"-6\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄱㅎㄷ', \"1.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ", "\"0\") _test('ㄷ ㄴㄱ ㄴㅁㅎㄷ', \"0\") _test('ㄹ ㄷ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷ ㄴㅁㅎㄷ', \"-1\")", "\"''\", '\\n\\n') _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"'불꽃'\", '불\\n꽃') _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ", "ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄱㅎㄷ', \"5+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄱㅎㄷ',", "_test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄷㅎㄷ', \"2.5+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ)", "ㄱㅇㄱㅎㄷㅎㄴ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30'\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ", "ㅈㅎㄷ) ㄷㅎㄷ', \"True\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄷㅎㄹ', \"True\") _test('ㅁㅀㄱ", "ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㄴ ㅁㅈㅎㄴ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30\\\\x31'\") def test_exponentiate(self):", "\"-1.0\") _test('ㄱ ㅄㅎㄴ ㄴ ㅅㅎㄷ', \"0i\") _test('ㄱ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ', \"-1+0i\") _test('ㄴ", "ㄱ ㅂㅎㅀㄷ', \"True\") def test_floor_div(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㄶㄷ', \"0\") _test('ㄴ", "ㅅㅎㄷ ㄱ ㄷ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") _test('(ㄴ ㄴ ㅄㅎㄷ ㄴㄱ", "'\\n\\n') _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"'불꽃'\", '불\\n꽃') _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄷㅎㄷ',", "ㄷ ㄹㄱ ㄷㅎㅁ', \"-1\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄷㅎㄷ', \"2.5\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ)", "(ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㄶㄷ', \"6.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ ㄴㄶㄷ', \"0.0\") def test_modulo(self):", "ㄱ ㅂㅎㅀㄷ', \"True\") _test('(ㄴ ㄴ ㅄㅎㄷ ㄴㄱ ㅅㅎㄷ ㄷ ㄱㅎㄷ) ㄴ ㄴㄱ ㅄㅎㄷ", "_test('ㄱ ㅁㅀㄴ ㅁㅀㄱ ㄷㅎㄷ', \"[0]\") _test('ㄱ ㅁㅀㄴ ㄴ ㄷ ㅁㅀㄷ ㄷㅎㄷ', \"[0, 1,", "ㅅㅎㄷ) ㄴㄶㄷ', \"6.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ ㄴㄶㄷ', \"0.0\") def test_modulo(self): _test =", "def test_exponentiate(self): _test = self._assert_execute _test('ㄱ ㄴ ㅅㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㅅㅎㄷ', \"-1\")", "(ㄴ ㅁㅈㅎㄴ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30\\\\x31'\") def test_exponentiate(self): _test = self._assert_execute", "ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄷㅎㄹ', \"True\") _test('ㅁㅀㄱ ㅁㅀㄱ ㄷㅎㄷ', \"[]\") _test('ㄱ ㅁㅀㄴ", "from test.test_base import TestBase class TestArithmetics(TestBase): def test_multiply(self): _test = self._assert_execute _test('ㄱ ㄴ", "\"-2\") _test('ㄹ ㄷ ㄴㄶㄷ', \"1\") _test('ㄺ ㄷ ㄴㄶㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㄶㄷ', \"-1\")", "ㄷ ㄹ ㄱㅎㅁ', \"0\") _test('ㄴㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"-6\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ)", "ㅅㅎㄷ) ㄷ ㄷㅎㄷ', \"2.5\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄷㅎㄷ', \"2.5+0i\") _test('(ㄷ ㄴㄱ", "\"-1\") _test('ㄷ ㄴㄱ ㅅㅎㄷ', \"0.5\") _test('ㄴㄱ ㄴㄱ ㅅㅎㄷ', \"-1.0\") _test('ㄱ ㅄㅎㄴ ㄴ ㅅㅎㄷ',", "ㄱㅎㄷ', \"1+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄱㅎㄷ', \"5+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ)", "ㄳㅎㄶ ㄱㅀㄹ', \"'불꽃'\", '불\\n꽃') _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄷㅎㄷ', \"{}\") _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄴ ㄷ ㅅㅈㅎㄷ", "ㄷ ㄹ ㅅㅈㅎㄷ ㄷ ㅁ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 4}\") _test('(ㅂ ㅂ", "ㄴㄱ ㅅㅎㄷ) ㄹ ㄴㄶㄷ', \"0.0\") def test_modulo(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㅁㅎㄷ',", "\"{1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄴ ㄷ ㅅㅈㅎㄷ ㄷㅎㄷ', \"{0: 1, 1: 2}\")", "_test('ㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄷ", "_test('ㄱ ㅁㅀㄴ ㄷㅎㄴ', \"[0]\") _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"''\", '\\n\\n')", "_test('(ㄱ ㄴ ㅂ ㅂ ㅂㅎㄷㅎㄷ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b''\") _test('(ㅂ", "ㄴㄱ ㅅㅎㄷ', \"0.5\") _test('ㄴㄱ ㄴㄱ ㅅㅎㄷ', \"-1.0\") _test('ㄱ ㅄㅎㄴ ㄴ ㅅㅎㄷ', \"0i\") _test('ㄱ", "ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") def test_floor_div(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㄶㄷ', \"0\")", "ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄴ ㅎㅎㄴ', \"b''\") _test('(ㄱ ㄴ ㅂ ㅂ ㅂㅎㄷㅎㄷ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ)", "\"6.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ ㄴㄶㄷ', \"0.0\") def test_modulo(self): _test = self._assert_execute _test('ㄱ", "\"1\") _test('ㄺ ㄷ ㄴㄶㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㄶㄷ', \"-1\") _test('ㄺ ㄷㄱ ㄴㄶㄷ', \"1\")", "_test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄱㅎㄹ', \"True\") def test_add(self): _test =", "(ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b''\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ", "ㄷ ㅄㅎㄴ ㄱㅎㄷ', \"1+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄱㅎㄷ', \"5+0i\") _test('(ㄱ", "(ㄱ ㄴ ㄴㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄱㅎㄷ', \"False\")", "ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 4}\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ)", "\"b''\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ", "_test('(ㅂ ㅂ ㅂㅎㄷ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄴ ㅎㅎㄴ', \"b''\") _test('(ㄱ ㄴ ㅂ", "ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30\\\\x31'\") def test_exponentiate(self): _test = self._assert_execute _test('ㄱ ㄴ ㅅㅎㄷ', \"0\") _test('ㄴㄱ", "ㄷㅎㅁ', \"6\") _test('ㄴㄱ ㄴ ㄷ ㄹㄱ ㄷㅎㅁ', \"-1\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄷㅎㄷ',", "ㅈㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄱㅎㄹ', \"True\") def", "ㄴ ㄴㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ", "ㅅㅈㅎㄱ ㄴ ㄷ ㅅㅈㅎㄷ ㅅㅈㅎㄱ ㄷㅎㅁ', \"{1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄴ ㄷ", "ㅅㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㅅㅎㄷ', \"-1\") _test('ㄷ ㄴㄱ ㅅㅎㄷ', \"0.5\") _test('ㄴㄱ ㄴㄱ ㅅㅎㄷ',", "ㄹ ㄷㅎㅁ', \"6\") _test('ㄴㄱ ㄴ ㄷ ㄹㄱ ㄷㅎㅁ', \"-1\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ", "ㄷ ㄱㅎㄷ) ㄴ ㄴㄱ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") def test_floor_div(self): _test", "ㄴ ㄷ ㄹ ㄷㅎㅁ', \"6\") _test('ㄴㄱ ㄴ ㄷ ㄹㄱ ㄷㅎㅁ', \"-1\") _test('(ㄷ ㄴㄱ", "\"b'\\\\x30\\\\x31'\") def test_exponentiate(self): _test = self._assert_execute _test('ㄱ ㄴ ㅅㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㅅㅎㄷ',", "ㄱㅀㄹ', \"''\", '\\n\\n') _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"'불꽃'\", '불\\n꽃') _test('ㅅㅈㅎㄱ", "_test('ㄱ ㅁㅀㄴ ㄴ ㄷ ㅁㅀㄷ ㄷㅎㄷ', \"[0, 1, 2]\") _test('ㄱ ㅁㅀㄴ ㄷㅎㄴ', \"[0]\")", "1, 2: 3, 4: 5}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㄷ ㅁ", "ㄴ ㄷ ㅅㅈㅎㄷ ㄷㅎㄷ', \"{0: 1, 1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ", "_test = self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄷㅎㅁ', \"6\") _test('ㄴㄱ ㄴ ㄷ ㄹㄱ", "ㄴㄱ ㄴㄶㄷ', \"-2\") _test('ㄹ ㄷ ㄴㄶㄷ', \"1\") _test('ㄺ ㄷ ㄴㄶㄷ', \"-1\") _test('ㄹ ㄷㄱ", "ㅅㅈㅎㄷ ㅅㅈㅎㄱ ㄷㅎㅁ', \"{1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄴ ㄷ ㅅㅈㅎㄷ ㄷㅎㄷ', \"{0:", "= self._assert_execute _test('ㄱ ㄴ ㄴㄶㄷ', \"0\") _test('ㄴ ㄴ ㄴㄶㄷ', \"1\") _test('ㄴㄱ ㄴ ㄴㄶㄷ',", "_test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄱㅎㄷ', \"5+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ", "ㄴ ㅄㅎㄷ ㄴㄱ ㅅㅎㄷ ㄷ ㄱㅎㄷ) ㄴ ㄴㄱ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ',", "ㅂ ㅂ ㅂㅎㄷㅎㄷ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b''\") _test('(ㅂ ㅂ ㅂㅎㄷ)", "\"0\") _test('ㄴ ㄴ ㄴㄶㄷ', \"1\") _test('ㄴㄱ ㄴ ㄴㄶㄷ', \"-1\") _test('ㄷ ㄴㄱ ㄴㄶㄷ', \"-2\")", "ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄷㅎㄷ', \"True\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ)", "ㄴㅁㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄷ ㄴㄱ ㄴㅁㅎㄷ', \"0\") _test('ㄹ ㄷ ㄴㅁㅎㄷ',", "ㄷㅎㄷ', \"4+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄷㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ)", "\"-6\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄱㅎㄷ', \"1.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄱㅎㄷ',", "ㅅㅈㅎㄱ ㄷㅎㄷ', \"{}\") _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄴ ㄷ ㅅㅈㅎㄷ ㅅㅈㅎㄱ ㄷㅎㅁ', \"{1: 2}\") _test('ㄱ", "ㄴㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ", "ㅂㅎㄷㅎㄷ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b''\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ", "ㄴ ㅄㅎㄷ) ㄷㅎㄷ', \"4+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ) ㄷㅎㄷ', \"False\") _test('(ㄱ", "def test_floor_div(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㄶㄷ', \"0\") _test('ㄴ ㄴ ㄴㄶㄷ', \"1\")", "_test('ㄱ ㄴ ㄴㄶㄷ', \"0\") _test('ㄴ ㄴ ㄴㄶㄷ', \"1\") _test('ㄴㄱ ㄴ ㄴㄶㄷ', \"-1\") _test('ㄷ", "_test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㅁ ㅂ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2:", "ㄴ ㄴㄶㄷ', \"1\") _test('ㄴㄱ ㄴ ㄴㄶㄷ', \"-1\") _test('ㄷ ㄴㄱ ㄴㄶㄷ', \"-2\") _test('ㄹ ㄷ", "ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30\\\\x31'\") def test_exponentiate(self): _test = self._assert_execute _test('ㄱ ㄴ", "ㄳㅎㄶ ㄱㅀㄹ', \"''\", '\\n\\n') _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"'불꽃'\", '불\\n꽃')", "test.test_base import TestBase class TestArithmetics(TestBase): def test_multiply(self): _test = self._assert_execute _test('ㄱ ㄴ ㄷ", "(ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㄴ ㅁㅈㅎㄴ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30\\\\x31'\") def", "ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30'\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㄴ", "\"6\") _test('ㄴㄱ ㄴ ㄷ ㄹㄱ ㄷㅎㅁ', \"-1\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄷㅎㄷ', \"2.5\")", "ㄴ ㅈㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄱㅎㄹ', \"True\")", "4: 5}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㄷ ㅁ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0:", "ㄴㄶㄷ', \"1\") _test('ㄺ ㄷ ㄴㄶㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㄶㄷ', \"-1\") _test('ㄺ ㄷㄱ ㄴㄶㄷ',", "_test = self._assert_execute _test('ㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴㄱ ㄴ", "_test('ㄴ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄷ ㄴㄱ ㄴㅁㅎㄷ', \"0\") _test('ㄹ", "ㄴㄱ ㅅㅎㄷ) ㄴㄶㄷ', \"6.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ ㄴㄶㄷ', \"0.0\") def test_modulo(self): _test", "ㅅㅎㄷ', \"-1.0\") _test('ㄱ ㅄㅎㄴ ㄴ ㅅㅎㄷ', \"0i\") _test('ㄱ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ', \"-1+0i\")", "ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㅁ ㅂ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 3,", "ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ)", "3, 4: 5}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㄷ ㅁ ㅅㅈㅎㄷ ㄷㅎㄹ',", "ㄴ ㄴㄶㄷ', \"-1\") _test('ㄷ ㄴㄱ ㄴㄶㄷ', \"-2\") _test('ㄹ ㄷ ㄴㄶㄷ', \"1\") _test('ㄺ ㄷ", "ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ ㄱ ㄷ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") _test('(ㄴ", "ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30'\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㄴ ㅁㅈㅎㄴ", "ㅅㅎㄷ) ㄹ ㄴㄶㄷ', \"0.0\") def test_modulo(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㅁㅎㄷ', \"0\")", "ㅅㅎㄷ ㄷ ㄱㅎㄷ) ㄴ ㄴㄱ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") def test_floor_div(self):", "ㅅㅈㅎㄱ ㄷㅎㅁ', \"{1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄴ ㄷ ㅅㅈㅎㄷ ㄷㅎㄷ', \"{0: 1,", "ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ)", "ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30'\") _test('(ㅂ", "\"False\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ", "ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄷㅎㄹ', \"True\") _test('ㅁㅀㄱ ㅁㅀㄱ ㄷㅎㄷ', \"[]\") _test('ㄱ", "ㅁㅀㄴ ㄴ ㄷ ㅁㅀㄷ ㄷㅎㄷ', \"[0, 1, 2]\") _test('ㄱ ㅁㅀㄴ ㄷㅎㄴ', \"[0]\") _test('ㅀㄱ", "_test('ㄴ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ ㄱ ㄷ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\")", "\"[0]\") _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"''\", '\\n\\n') _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ", "(ㅁㅈㅎㄱ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄴ ㅎㅎㄴ', \"b''\") _test('(ㄱ ㄴ ㅂ ㅂ ㅂㅎㄷㅎㄷ) (ㅁㅈㅎㄱ", "ㅁㅀㄱ ㄷㅎㄷ', \"[]\") _test('ㄱ ㅁㅀㄴ ㅁㅀㄱ ㄷㅎㄷ', \"[0]\") _test('ㄱ ㅁㅀㄴ ㄴ ㄷ ㅁㅀㄷ", "ㄷ ㄹ ㄱㅎㅁ', \"-6\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㄱㅎㄷ', \"1.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ)", "ㄴㅁㅎㄷ', \"-1\") _test('ㄹ ㄷㄱ ㄴㅁㅎㄷ', \"1\") _test('ㄺ ㄷㄱ ㄴㅁㅎㄷ', \"-1\") _test('ㄹ (ㄷ ㄴㄱ", "_test('ㄱ ㄴ ㅅㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㅅㅎㄷ', \"-1\") _test('ㄷ ㄴㄱ ㅅㅎㄷ', \"0.5\") _test('ㄴㄱ", "ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") _test('(ㄴ ㄴ ㅄㅎㄷ ㄴㄱ ㅅㅎㄷ ㄷ ㄱㅎㄷ) ㄴ", "ㄹ ㅅㅈㅎㄷ ㄷ ㅁ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 4}\") _test('(ㅂ ㅂ ㅂㅎㄷ)", "ㄴㄶㄷ', \"0.0\") def test_modulo(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴ ㄴ", "ㄷㅎㄷ', \"[0, 1, 2]\") _test('ㄱ ㅁㅀㄴ ㄷㅎㄴ', \"[0]\") _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ", "ㄱㅎㄷ', \"1.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄱㅎㄷ', \"1+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ", "1, 1: 2}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㅁ ㅂ ㅅㅈㅎㄷ ㄷㅎㄹ',", "_test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㄶㄷ', \"6.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ ㄴㄶㄷ', \"0.0\") def", "ㄷ ㅅㅎㄷ', \"-1+0i\") _test('ㄴ ㄴ ㅄㅎㄷ ㄷ ㅅㅎㄷ ㄱ ㄷ ㅄㅎㄷ ㅂ ㅅ", "ㄹ ㅅㅈㅎㄷ ㅁ ㅂ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 3, 4: 5}\") _test('ㄱ", "\"-1\") _test('ㄹ (ㄷ ㄴㄱ ㅅㅎㄷ) ㄴㅁㅎㄷ', \"0.0\") _test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄹ ㄴㅁㅎㄷ', \"0.5\")", "ㅁㅈㅎㄴ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30\\\\x31'\") def test_exponentiate(self): _test = self._assert_execute _test('ㄱ", "ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㄴ ㅁㅈㅎㄴ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ', \"b'\\\\x30\\\\x31'\") def test_exponentiate(self): _test", "ㅎㅎㄴ', \"b''\") _test('(ㄱ ㄴ ㅂ ㅂ ㅂㅎㄷㅎㄷ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) (ㅁㅈㅎㄱ ㄱㅇㄱㅎㄴ) ㄷㅎㄷ ㅎㅎㄴ',", "= self._assert_execute _test('ㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㄴㅁㅎㄷ',", "_test = self._assert_execute _test('ㄱ ㄴ ㄴㄶㄷ', \"0\") _test('ㄴ ㄴ ㄴㄶㄷ', \"1\") _test('ㄴㄱ ㄴ", "\"0.0\") def test_modulo(self): _test = self._assert_execute _test('ㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴ ㄴ ㄴㅁㅎㄷ',", "= self._assert_execute _test('ㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"0\") _test('ㄴㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ',", "\"b'\\\\x30'\") _test('(ㅂ ㅂ ㅂㅎㄷ) (ㄳㄱ ㄴ ㄴ ㄱㅇㄱㅎㄷㅎㄴ) (ㄴ ㅁㅈㅎㄴ ㄱ ㄴ ㄱㅇㄱㅎㄷㅎㄴ)", "ㄴ ㄷ ㅁㅀㄷ ㄷㅎㄷ', \"[0, 1, 2]\") _test('ㄱ ㅁㅀㄴ ㄷㅎㄴ', \"[0]\") _test('ㅀㄱ ㅀㄱ", "ㄱ ㄷ ㅄㅎㄷ ㅂ ㅅ ㄱ ㅂㅎㅀㄷ', \"True\") _test('(ㄴ ㄴ ㅄㅎㄷ ㄴㄱ ㅅㅎㄷ", "ㄴ ㅅㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㅅㅎㄷ', \"-1\") _test('ㄷ ㄴㄱ ㅅㅎㄷ', \"0.5\") _test('ㄴㄱ ㄴㄱ", "_test('(ㄷ ㄴㄱ ㅅㅎㄷ) ㄷ ㅄㅎㄴ ㄱㅎㄷ', \"1+0i\") _test('(ㄷ ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ)", "ㄴㄱ ㅄㅎㄷ) (ㄷ ㄴ ㅄㅎㄷ) ㄱㅎㄷ', \"5+0i\") _test('(ㄱ ㄱ ㅈㅎㄷ) (ㄱ ㄴ ㄴㅎㄷ)", "ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄱㅎㄹ', \"True\") def test_add(self):", "ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ ㄷ ㅁ ㅅㅈㅎㄷ ㄷㅎㄹ', \"{0: 1, 2: 4}\")", "_test('ㄴㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄷ ㄴㄱ ㄴㅁㅎㄷ', \"0\") _test('ㄹ ㄷ ㄴㅁㅎㄷ', \"1\") _test('ㄺ", "_test('ㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"0\") _test('ㄴㄱ ㄴ ㄷ ㄹ ㄱㅎㅁ', \"-6\") _test('(ㄷ", "ㄷㅎㄹ', \"True\") _test('ㅁㅀㄱ ㅁㅀㄱ ㄷㅎㄷ', \"[]\") _test('ㄱ ㅁㅀㄴ ㅁㅀㄱ ㄷㅎㄷ', \"[0]\") _test('ㄱ ㅁㅀㄴ", "ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"'불꽃'\", '불\\n꽃') _test('ㅅㅈㅎㄱ ㅅㅈㅎㄱ ㄷㅎㄷ', \"{}\") _test('ㅅㅈㅎㄱ", "(ㄱ ㄴ ㅈㅎㄷ) ㄱㅎㄷ', \"False\") _test('(ㄱ ㄱ ㄴㅎㄷ) (ㄱ ㄴ ㅈㅎㄷ) (ㅈㅈㅎㄱ) ㄱㅎㄹ',", "ㄷㅎㄹ', \"{0: 1, 2: 3, 4: 5}\") _test('ㄱ ㄴ ㅅㅈㅎㄷ ㄷ ㄹ ㅅㅈㅎㄷ", "test_exponentiate(self): _test = self._assert_execute _test('ㄱ ㄴ ㅅㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㅅㅎㄷ', \"-1\") _test('ㄷ", "\"0\") _test('ㄴ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄴㄱ ㄴ ㄴㅁㅎㄷ', \"0\") _test('ㄷ ㄴㄱ ㄴㅁㅎㄷ', \"0\")", "ㄷㅎㄴ', \"[0]\") _test('ㅀㄱ ㅀㄱ ㄱㅇㄱ ㄴㅇㄱ ㄷㅎㄷ ㄳㅎㄶ ㄱㅀㄹ', \"''\", '\\n\\n') _test('ㅀㄱ ㅀㄱ" ]
[ "client.call(\"ak.wwise.core.object.get\", { \"from\": { \"name\": [\"GameParameter:a\" + str(n) for n in range(5000)], }", "WaapiClient, connect, CannotConnectToWaapiException class LargePayload(unittest.TestCase): def test_large_rpc(self): with WaapiClient() as client: result =", "unittest from waapi import WaapiClient, connect, CannotConnectToWaapiException class LargePayload(unittest.TestCase): def test_large_rpc(self): with WaapiClient()", "def test_large_rpc(self): with WaapiClient() as client: result = client.call(\"ak.wwise.core.object.get\", { \"from\": { \"name\":", "result = client.call(\"ak.wwise.core.object.get\", { \"from\": { \"name\": [\"GameParameter:a\" + str(n) for n in", "waapi import WaapiClient, connect, CannotConnectToWaapiException class LargePayload(unittest.TestCase): def test_large_rpc(self): with WaapiClient() as client:", "\"name\": [\"GameParameter:a\" + str(n) for n in range(5000)], } }) self.assertTrue(client.is_connected()) if __name__", "= client.call(\"ak.wwise.core.object.get\", { \"from\": { \"name\": [\"GameParameter:a\" + str(n) for n in range(5000)],", "{ \"name\": [\"GameParameter:a\" + str(n) for n in range(5000)], } }) self.assertTrue(client.is_connected()) if", "client: result = client.call(\"ak.wwise.core.object.get\", { \"from\": { \"name\": [\"GameParameter:a\" + str(n) for n", "import unittest from waapi import WaapiClient, connect, CannotConnectToWaapiException class LargePayload(unittest.TestCase): def test_large_rpc(self): with", "{ \"from\": { \"name\": [\"GameParameter:a\" + str(n) for n in range(5000)], } })", "+ str(n) for n in range(5000)], } }) self.assertTrue(client.is_connected()) if __name__ == \"__main__\":", "class LargePayload(unittest.TestCase): def test_large_rpc(self): with WaapiClient() as client: result = client.call(\"ak.wwise.core.object.get\", { \"from\":", "as client: result = client.call(\"ak.wwise.core.object.get\", { \"from\": { \"name\": [\"GameParameter:a\" + str(n) for", "<reponame>kakyoism/waapi-client-python<filename>waapi/test/test_large_payload.py import unittest from waapi import WaapiClient, connect, CannotConnectToWaapiException class LargePayload(unittest.TestCase): def test_large_rpc(self):", "from waapi import WaapiClient, connect, CannotConnectToWaapiException class LargePayload(unittest.TestCase): def test_large_rpc(self): with WaapiClient() as", "connect, CannotConnectToWaapiException class LargePayload(unittest.TestCase): def test_large_rpc(self): with WaapiClient() as client: result = client.call(\"ak.wwise.core.object.get\",", "CannotConnectToWaapiException class LargePayload(unittest.TestCase): def test_large_rpc(self): with WaapiClient() as client: result = client.call(\"ak.wwise.core.object.get\", {", "[\"GameParameter:a\" + str(n) for n in range(5000)], } }) self.assertTrue(client.is_connected()) if __name__ ==", "WaapiClient() as client: result = client.call(\"ak.wwise.core.object.get\", { \"from\": { \"name\": [\"GameParameter:a\" + str(n)", "import WaapiClient, connect, CannotConnectToWaapiException class LargePayload(unittest.TestCase): def test_large_rpc(self): with WaapiClient() as client: result", "with WaapiClient() as client: result = client.call(\"ak.wwise.core.object.get\", { \"from\": { \"name\": [\"GameParameter:a\" +", "str(n) for n in range(5000)], } }) self.assertTrue(client.is_connected()) if __name__ == \"__main__\": LargePayload().test_large_rpc()", "test_large_rpc(self): with WaapiClient() as client: result = client.call(\"ak.wwise.core.object.get\", { \"from\": { \"name\": [\"GameParameter:a\"", "LargePayload(unittest.TestCase): def test_large_rpc(self): with WaapiClient() as client: result = client.call(\"ak.wwise.core.object.get\", { \"from\": {", "\"from\": { \"name\": [\"GameParameter:a\" + str(n) for n in range(5000)], } }) self.assertTrue(client.is_connected())" ]
[ "print(\"{}: {}\".format(cat, arr.shape)) label_vectors = {} for cat, n in zip(classes_to_generate, [lesion_n, pleural_n,", "Effusion', 'Pleural Other', 'Fracture', 'Support Devices'] tf.InteractiveSession() # Import pretrained Chexpert GAN. with", "file: G, D, Gs = pickle.load(file) real_labels = pd.read_csv(real_data_path + \"CheXpert-v1.0-small/train_preprocessed.csv\") classes_to_generate =", "cat in classes_to_generate: labels = label_vectors[cat] batch = 1 used_labels = [] used_imgname", "PIL.Image import imageio # import tfutils import matplotlib.pyplot as plt import os import", "Other\"]) fracture = sum(real_labels[\"Fracture\"]) lesion_n, pleural_n, fracture_n = int(lesion*1.65), int(pleural*3.65), int(fracture*1.95) total_gen =", "255.0).astype(np.uint8) # [-1,1] => [0,255] images = images.transpose(0, 2, 3, 1) # NCHW", "['No Finding', 'Enlarged Cardiomediastinum', 'Cardiomegaly', 'Lung Opacity', 'Lung Lesion', 'Edema', 'Consolidation', 'Pneumonia', 'Atelectasis',", "batch: (n + 1) * batch, :] used_labels.append(label_vec) images = Gs.run(latent_vec, label_vec) images", "new_labels for cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) label_vectors = {} for", "image_idx) used_imgname.append(store_name) store_path = os.path.join(data_dir, store_name) imageio.imwrite(store_path, save_images[idx]) print(\"Done with {}\".format(cat)) print(len(labels)) print(len(used_labels))", "in range(int(total_num / batch)): if n % 1000 == 0: print(\"{}/{}\".format(n, total_num)) latent_vec", "(fracture+fracture_n)/(total + total_gen))) sys.stdout.flush() label_vectors = {} for cat, n in zip(classes_to_generate, [lesion_n,", "label_vectors = {} for cat, n in zip(classes_to_generate, [lesion_n, pleural_n, fracture_n]): relevant_labels =", "used_imgname = [] latents_raw = np.random.RandomState(1000).randn(labels.shape[0], *Gs.input_shapes[0][1:]) total_num = latents_raw.shape[0] print(\"Generating {}\".format(cat)) sys.stdout.flush()", "tensorflow as tf import PIL.Image import imageio # import tfutils import matplotlib.pyplot as", "print(len(used_labels)) print(len(used_imgname)) sys.stdout.flush() with open(output_data_path + \"gan_image_labels.pkl\", \"wb\") as handle: pickle.dump(labels_save, handle) sys.stdout.flush()", "not os.path.exists(data_dir): os.makedirs(data_dir) for idx in range(save_images.shape[0]): image_idx = idx + batch *", "1] new_labels = relevant_labels.sample(n, replace=True)[names].to_numpy() label_vectors[cat] = new_labels for cat, arr in label_vectors.items():", "{}\".format(cat)) print(len(labels)) print(len(used_labels)) print(len(used_imgname)) sys.stdout.flush() with open(output_data_path + \"gan_image_labels.pkl\", \"wb\") as handle: pickle.dump(labels_save,", "zip(classes_to_generate, [lesion_n, pleural_n, fracture_n]): relevant_labels = real_labels[real_labels[cat] == 1] new_labels = relevant_labels.sample(n, replace=True)[names].to_numpy()", "fracture_n print(\"Lesion: {}/{} + {} --> {}/{}\".format(lesion, lesion/total, lesion_n, lesion+lesion_n, (lesion+lesion_n)/(total+total_gen))) print(\"Pleural: {}/{}", "+ total_gen))) print(\"Fracture: {}/{} + {} --> {}/{}\".format(fracture, fracture/total, fracture_n, fracture+fracture_n, (fracture+fracture_n)/(total +", "+ 1) * batch, :] label_vec = labels[n * batch: (n + 1)", ":] store_name = 'fake_{}_{}.png'.format(cat, image_idx) used_imgname.append(store_name) store_path = os.path.join(data_dir, store_name) imageio.imwrite(store_path, save_images[idx]) print(\"Done", "{}/{}\".format(pleural, pleural/total, pleural_n, pleural+pleural_n, (pleural+pleural_n)/(total + total_gen))) print(\"Fracture: {}/{} + {} --> {}/{}\".format(fracture,", "real_labels = pd.read_csv(real_data_path + \"CheXpert-v1.0-small/train_preprocessed.csv\") classes_to_generate = [\"Lung Lesion\", \"Pleural Other\", \"Fracture\"] total", "GAN. with open(network_path + \"network-final.pkl\", 'rb') as file: G, D, Gs = pickle.load(file)", "= real_labels[real_labels[cat] == 1] new_labels = relevant_labels.sample(n, replace=True)[names].to_numpy() label_vectors[cat] = new_labels for cat,", "== 0: print(\"{}/{}\".format(n, total_num)) latent_vec = latents_raw[n * batch: (n + 1) *", "import numpy as np import pandas as pd import tensorflow as tf import", "total_num)) latent_vec = latents_raw[n * batch: (n + 1) * batch, :] label_vec", "= \"/om/user/shobhita/src/chexpert/CheXpert GAN/\" output_data_path = \"/om/user/shobhita/src/chexpert/gan_fake_data/\" real_data_path = \"/om/user/shobhita/src/chexpert/data/\" names = ['No Finding',", "store_name) imageio.imwrite(store_path, save_images[idx]) print(\"Done with {}\".format(cat)) print(len(labels)) print(len(used_labels)) print(len(used_imgname)) sys.stdout.flush() with open(output_data_path +", "np.squeeze(images, axis=-1) data_dir = output_data_path if not os.path.exists(data_dir): os.makedirs(data_dir) for idx in range(save_images.shape[0]):", "= images.transpose(0, 2, 3, 1) # NCHW => NHWC save_images = np.squeeze(images, axis=-1)", "= latents_raw.shape[0] print(\"Generating {}\".format(cat)) sys.stdout.flush() for n in range(int(total_num / batch)): if n", "[] latents_raw = np.random.RandomState(1000).randn(labels.shape[0], *Gs.input_shapes[0][1:]) total_num = latents_raw.shape[0] print(\"Generating {}\".format(cat)) sys.stdout.flush() for n", "lesion = sum(real_labels[\"Lung Lesion\"]) pleural = sum(real_labels[\"Pleural Other\"]) fracture = sum(real_labels[\"Fracture\"]) lesion_n, pleural_n,", "+ \"network-final.pkl\", 'rb') as file: G, D, Gs = pickle.load(file) real_labels = pd.read_csv(real_data_path", "import tfutils import matplotlib.pyplot as plt import os import sys from IPython.core.interactiveshell import", "import InteractiveShell InteractiveShell.ast_node_interactivity = \"all\" network_path = \"/om/user/shobhita/src/chexpert/CheXpert GAN/\" output_data_path = \"/om/user/shobhita/src/chexpert/gan_fake_data/\" real_data_path", "{}/{}\".format(lesion, lesion/total, lesion_n, lesion+lesion_n, (lesion+lesion_n)/(total+total_gen))) print(\"Pleural: {}/{} + {} --> {}/{}\".format(pleural, pleural/total, pleural_n,", "plt import os import sys from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = \"all\" network_path", "'rb') as file: G, D, Gs = pickle.load(file) real_labels = pd.read_csv(real_data_path + \"CheXpert-v1.0-small/train_preprocessed.csv\")", "axis=-1) data_dir = output_data_path if not os.path.exists(data_dir): os.makedirs(data_dir) for idx in range(save_images.shape[0]): image_idx", "= {} for cat, n in zip(classes_to_generate, [lesion_n, pleural_n, fracture_n]): relevant_labels = real_labels[real_labels[cat]", "0: print(\"{}/{}\".format(n, total_num)) latent_vec = latents_raw[n * batch: (n + 1) * batch,", "n % 1000 == 0: print(\"{}/{}\".format(n, total_num)) latent_vec = latents_raw[n * batch: (n", "cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) labels_save = {} for cat in", "= np.random.RandomState(1000).randn(labels.shape[0], *Gs.input_shapes[0][1:]) total_num = latents_raw.shape[0] print(\"Generating {}\".format(cat)) sys.stdout.flush() for n in range(int(total_num", "{}/{} + {} --> {}/{}\".format(lesion, lesion/total, lesion_n, lesion+lesion_n, (lesion+lesion_n)/(total+total_gen))) print(\"Pleural: {}/{} + {}", "store_path = os.path.join(data_dir, store_name) imageio.imwrite(store_path, save_images[idx]) print(\"Done with {}\".format(cat)) print(len(labels)) print(len(used_labels)) print(len(used_imgname)) sys.stdout.flush()", "Import pretrained Chexpert GAN. with open(network_path + \"network-final.pkl\", 'rb') as file: G, D,", "sys from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = \"all\" network_path = \"/om/user/shobhita/src/chexpert/CheXpert GAN/\" output_data_path", "= {} for cat in classes_to_generate: labels = label_vectors[cat] batch = 1 used_labels", "fracture_n, fracture+fracture_n, (fracture+fracture_n)/(total + total_gen))) sys.stdout.flush() label_vectors = {} for cat, n in", "image_idx = idx + batch * n labels_save[\"{}_{}\".format(cat, image_idx)] = labels[image_idx, :] store_name", "'Atelectasis', 'Pneumothorax', 'Pleural Effusion', 'Pleural Other', 'Fracture', 'Support Devices'] tf.InteractiveSession() # Import pretrained", "= [] latents_raw = np.random.RandomState(1000).randn(labels.shape[0], *Gs.input_shapes[0][1:]) total_num = latents_raw.shape[0] print(\"Generating {}\".format(cat)) sys.stdout.flush() for", "+ {} --> {}/{}\".format(lesion, lesion/total, lesion_n, lesion+lesion_n, (lesion+lesion_n)/(total+total_gen))) print(\"Pleural: {}/{} + {} -->", "new_labels = relevant_labels.sample(n, replace=True)[names].to_numpy() label_vectors[cat] = new_labels for cat, arr in label_vectors.items(): print(\"{}:", "print(\"Done with {}\".format(cat)) print(len(labels)) print(len(used_labels)) print(len(used_imgname)) sys.stdout.flush() with open(output_data_path + \"gan_image_labels.pkl\", \"wb\") as", "== 1] new_labels = relevant_labels.sample(n, replace=True)[names].to_numpy() label_vectors[cat] = new_labels for cat, arr in", "fracture+fracture_n, (fracture+fracture_n)/(total + total_gen))) sys.stdout.flush() label_vectors = {} for cat, n in zip(classes_to_generate,", "int(fracture*1.95) total_gen = total + lesion_n + pleural_n + fracture_n print(\"Lesion: {}/{} +", "sys.stdout.flush() label_vectors = {} for cat, n in zip(classes_to_generate, [lesion_n, pleural_n, fracture_n]): relevant_labels", "0.0, 255.0).astype(np.uint8) # [-1,1] => [0,255] images = images.transpose(0, 2, 3, 1) #", "os.makedirs(data_dir) for idx in range(save_images.shape[0]): image_idx = idx + batch * n labels_save[\"{}_{}\".format(cat,", "if n % 1000 == 0: print(\"{}/{}\".format(n, total_num)) latent_vec = latents_raw[n * batch:", "sys.stdout.flush() for n in range(int(total_num / batch)): if n % 1000 == 0:", "sum(real_labels[\"Lung Lesion\"]) pleural = sum(real_labels[\"Pleural Other\"]) fracture = sum(real_labels[\"Fracture\"]) lesion_n, pleural_n, fracture_n =", "total + lesion_n + pleural_n + fracture_n print(\"Lesion: {}/{} + {} --> {}/{}\".format(lesion,", "import os import sys from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = \"all\" network_path =", "= [] used_imgname = [] latents_raw = np.random.RandomState(1000).randn(labels.shape[0], *Gs.input_shapes[0][1:]) total_num = latents_raw.shape[0] print(\"Generating", "import pandas as pd import tensorflow as tf import PIL.Image import imageio #", "InteractiveShell InteractiveShell.ast_node_interactivity = \"all\" network_path = \"/om/user/shobhita/src/chexpert/CheXpert GAN/\" output_data_path = \"/om/user/shobhita/src/chexpert/gan_fake_data/\" real_data_path =", "in classes_to_generate: labels = label_vectors[cat] batch = 1 used_labels = [] used_imgname =", "labels_save = {} for cat in classes_to_generate: labels = label_vectors[cat] batch = 1", "= idx + batch * n labels_save[\"{}_{}\".format(cat, image_idx)] = labels[image_idx, :] store_name =", "{}/{} + {} --> {}/{}\".format(fracture, fracture/total, fracture_n, fracture+fracture_n, (fracture+fracture_n)/(total + total_gen))) sys.stdout.flush() label_vectors", "used_labels.append(label_vec) images = Gs.run(latent_vec, label_vec) images = np.clip(np.rint((images + 1.0) / 2.0 *", "--> {}/{}\".format(lesion, lesion/total, lesion_n, lesion+lesion_n, (lesion+lesion_n)/(total+total_gen))) print(\"Pleural: {}/{} + {} --> {}/{}\".format(pleural, pleural/total,", "IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = \"all\" network_path = \"/om/user/shobhita/src/chexpert/CheXpert GAN/\" output_data_path = \"/om/user/shobhita/src/chexpert/gan_fake_data/\"", "+ pleural_n + fracture_n print(\"Lesion: {}/{} + {} --> {}/{}\".format(lesion, lesion/total, lesion_n, lesion+lesion_n,", "label_vec = labels[n * batch: (n + 1) * batch, :] used_labels.append(label_vec) images", "tf import PIL.Image import imageio # import tfutils import matplotlib.pyplot as plt import", "classes_to_generate: labels = label_vectors[cat] batch = 1 used_labels = [] used_imgname = []", "\"/om/user/shobhita/src/chexpert/CheXpert GAN/\" output_data_path = \"/om/user/shobhita/src/chexpert/gan_fake_data/\" real_data_path = \"/om/user/shobhita/src/chexpert/data/\" names = ['No Finding', 'Enlarged", "as plt import os import sys from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = \"all\"", "labels_save[\"{}_{}\".format(cat, image_idx)] = labels[image_idx, :] store_name = 'fake_{}_{}.png'.format(cat, image_idx) used_imgname.append(store_name) store_path = os.path.join(data_dir,", "+ total_gen))) sys.stdout.flush() label_vectors = {} for cat, n in zip(classes_to_generate, [lesion_n, pleural_n,", "output_data_path = \"/om/user/shobhita/src/chexpert/gan_fake_data/\" real_data_path = \"/om/user/shobhita/src/chexpert/data/\" names = ['No Finding', 'Enlarged Cardiomediastinum', 'Cardiomegaly',", "arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) labels_save = {} for cat in classes_to_generate:", "for cat, n in zip(classes_to_generate, [lesion_n, pleural_n, fracture_n]): relevant_labels = real_labels[real_labels[cat] == 1]", "{} for cat in classes_to_generate: labels = label_vectors[cat] batch = 1 used_labels =", "in range(save_images.shape[0]): image_idx = idx + batch * n labels_save[\"{}_{}\".format(cat, image_idx)] = labels[image_idx,", "import PIL.Image import imageio # import tfutils import matplotlib.pyplot as plt import os", "Gs = pickle.load(file) real_labels = pd.read_csv(real_data_path + \"CheXpert-v1.0-small/train_preprocessed.csv\") classes_to_generate = [\"Lung Lesion\", \"Pleural", "as tf import PIL.Image import imageio # import tfutils import matplotlib.pyplot as plt", "'Consolidation', 'Pneumonia', 'Atelectasis', 'Pneumothorax', 'Pleural Effusion', 'Pleural Other', 'Fracture', 'Support Devices'] tf.InteractiveSession() #", "np import pandas as pd import tensorflow as tf import PIL.Image import imageio", "'Enlarged Cardiomediastinum', 'Cardiomegaly', 'Lung Opacity', 'Lung Lesion', 'Edema', 'Consolidation', 'Pneumonia', 'Atelectasis', 'Pneumothorax', 'Pleural", "latents_raw.shape[0] print(\"Generating {}\".format(cat)) sys.stdout.flush() for n in range(int(total_num / batch)): if n %", "* batch, :] used_labels.append(label_vec) images = Gs.run(latent_vec, label_vec) images = np.clip(np.rint((images + 1.0)", "=> [0,255] images = images.transpose(0, 2, 3, 1) # NCHW => NHWC save_images", "pd.read_csv(real_data_path + \"CheXpert-v1.0-small/train_preprocessed.csv\") classes_to_generate = [\"Lung Lesion\", \"Pleural Other\", \"Fracture\"] total = len(real_labels)", "'Lung Opacity', 'Lung Lesion', 'Edema', 'Consolidation', 'Pneumonia', 'Atelectasis', 'Pneumothorax', 'Pleural Effusion', 'Pleural Other',", "= new_labels for cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) labels_save = {}", "'Cardiomegaly', 'Lung Opacity', 'Lung Lesion', 'Edema', 'Consolidation', 'Pneumonia', 'Atelectasis', 'Pneumothorax', 'Pleural Effusion', 'Pleural", "cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) label_vectors = {} for cat, n", "{} for cat, n in zip(classes_to_generate, [lesion_n, pleural_n, fracture_n]): relevant_labels = real_labels[real_labels[cat] ==", "pretrained Chexpert GAN. with open(network_path + \"network-final.pkl\", 'rb') as file: G, D, Gs", "(n + 1) * batch, :] used_labels.append(label_vec) images = Gs.run(latent_vec, label_vec) images =", "# import tfutils import matplotlib.pyplot as plt import os import sys from IPython.core.interactiveshell", "print(\"Fracture: {}/{} + {} --> {}/{}\".format(fracture, fracture/total, fracture_n, fracture+fracture_n, (fracture+fracture_n)/(total + total_gen))) sys.stdout.flush()", "InteractiveShell.ast_node_interactivity = \"all\" network_path = \"/om/user/shobhita/src/chexpert/CheXpert GAN/\" output_data_path = \"/om/user/shobhita/src/chexpert/gan_fake_data/\" real_data_path = \"/om/user/shobhita/src/chexpert/data/\"", "= np.squeeze(images, axis=-1) data_dir = output_data_path if not os.path.exists(data_dir): os.makedirs(data_dir) for idx in", "import tensorflow as tf import PIL.Image import imageio # import tfutils import matplotlib.pyplot", "= latents_raw[n * batch: (n + 1) * batch, :] label_vec = labels[n", "= \"all\" network_path = \"/om/user/shobhita/src/chexpert/CheXpert GAN/\" output_data_path = \"/om/user/shobhita/src/chexpert/gan_fake_data/\" real_data_path = \"/om/user/shobhita/src/chexpert/data/\" names", "import sys from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = \"all\" network_path = \"/om/user/shobhita/src/chexpert/CheXpert GAN/\"", "images = images.transpose(0, 2, 3, 1) # NCHW => NHWC save_images = np.squeeze(images,", "255.0), 0.0, 255.0).astype(np.uint8) # [-1,1] => [0,255] images = images.transpose(0, 2, 3, 1)", "+ \"CheXpert-v1.0-small/train_preprocessed.csv\") classes_to_generate = [\"Lung Lesion\", \"Pleural Other\", \"Fracture\"] total = len(real_labels) lesion", "\"/om/user/shobhita/src/chexpert/gan_fake_data/\" real_data_path = \"/om/user/shobhita/src/chexpert/data/\" names = ['No Finding', 'Enlarged Cardiomediastinum', 'Cardiomegaly', 'Lung Opacity',", "pleural_n, pleural+pleural_n, (pleural+pleural_n)/(total + total_gen))) print(\"Fracture: {}/{} + {} --> {}/{}\".format(fracture, fracture/total, fracture_n,", "os.path.exists(data_dir): os.makedirs(data_dir) for idx in range(save_images.shape[0]): image_idx = idx + batch * n", "store_name = 'fake_{}_{}.png'.format(cat, image_idx) used_imgname.append(store_name) store_path = os.path.join(data_dir, store_name) imageio.imwrite(store_path, save_images[idx]) print(\"Done with", "+ {} --> {}/{}\".format(pleural, pleural/total, pleural_n, pleural+pleural_n, (pleural+pleural_n)/(total + total_gen))) print(\"Fracture: {}/{} +", "(lesion+lesion_n)/(total+total_gen))) print(\"Pleural: {}/{} + {} --> {}/{}\".format(pleural, pleural/total, pleural_n, pleural+pleural_n, (pleural+pleural_n)/(total + total_gen)))", "batch, :] used_labels.append(label_vec) images = Gs.run(latent_vec, label_vec) images = np.clip(np.rint((images + 1.0) /", "classes_to_generate = [\"Lung Lesion\", \"Pleural Other\", \"Fracture\"] total = len(real_labels) lesion = sum(real_labels[\"Lung", "label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) label_vectors = {} for cat, n in zip(classes_to_generate, [lesion_n,", "int(pleural*3.65), int(fracture*1.95) total_gen = total + lesion_n + pleural_n + fracture_n print(\"Lesion: {}/{}", "cat, n in zip(classes_to_generate, [lesion_n, pleural_n, fracture_n]): relevant_labels = real_labels[real_labels[cat] == 1] new_labels", "tfutils import matplotlib.pyplot as plt import os import sys from IPython.core.interactiveshell import InteractiveShell", "[] used_imgname = [] latents_raw = np.random.RandomState(1000).randn(labels.shape[0], *Gs.input_shapes[0][1:]) total_num = latents_raw.shape[0] print(\"Generating {}\".format(cat))", "G, D, Gs = pickle.load(file) real_labels = pd.read_csv(real_data_path + \"CheXpert-v1.0-small/train_preprocessed.csv\") classes_to_generate = [\"Lung", "import imageio # import tfutils import matplotlib.pyplot as plt import os import sys", "% 1000 == 0: print(\"{}/{}\".format(n, total_num)) latent_vec = latents_raw[n * batch: (n +", "fracture_n = int(lesion*1.65), int(pleural*3.65), int(fracture*1.95) total_gen = total + lesion_n + pleural_n +", "[0,255] images = images.transpose(0, 2, 3, 1) # NCHW => NHWC save_images =", "NCHW => NHWC save_images = np.squeeze(images, axis=-1) data_dir = output_data_path if not os.path.exists(data_dir):", "Finding', 'Enlarged Cardiomediastinum', 'Cardiomegaly', 'Lung Opacity', 'Lung Lesion', 'Edema', 'Consolidation', 'Pneumonia', 'Atelectasis', 'Pneumothorax',", "data_dir = output_data_path if not os.path.exists(data_dir): os.makedirs(data_dir) for idx in range(save_images.shape[0]): image_idx =", "\"CheXpert-v1.0-small/train_preprocessed.csv\") classes_to_generate = [\"Lung Lesion\", \"Pleural Other\", \"Fracture\"] total = len(real_labels) lesion =", "len(real_labels) lesion = sum(real_labels[\"Lung Lesion\"]) pleural = sum(real_labels[\"Pleural Other\"]) fracture = sum(real_labels[\"Fracture\"]) lesion_n,", "label_vec) images = np.clip(np.rint((images + 1.0) / 2.0 * 255.0), 0.0, 255.0).astype(np.uint8) #", "replace=True)[names].to_numpy() label_vectors[cat] = new_labels for cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) label_vectors", "real_data_path = \"/om/user/shobhita/src/chexpert/data/\" names = ['No Finding', 'Enlarged Cardiomediastinum', 'Cardiomegaly', 'Lung Opacity', 'Lung", "pleural+pleural_n, (pleural+pleural_n)/(total + total_gen))) print(\"Fracture: {}/{} + {} --> {}/{}\".format(fracture, fracture/total, fracture_n, fracture+fracture_n,", "names = ['No Finding', 'Enlarged Cardiomediastinum', 'Cardiomegaly', 'Lung Opacity', 'Lung Lesion', 'Edema', 'Consolidation',", "\"network-final.pkl\", 'rb') as file: G, D, Gs = pickle.load(file) real_labels = pd.read_csv(real_data_path +", "'fake_{}_{}.png'.format(cat, image_idx) used_imgname.append(store_name) store_path = os.path.join(data_dir, store_name) imageio.imwrite(store_path, save_images[idx]) print(\"Done with {}\".format(cat)) print(len(labels))", "batch * n labels_save[\"{}_{}\".format(cat, image_idx)] = labels[image_idx, :] store_name = 'fake_{}_{}.png'.format(cat, image_idx) used_imgname.append(store_name)", "images = Gs.run(latent_vec, label_vec) images = np.clip(np.rint((images + 1.0) / 2.0 * 255.0),", "os import sys from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = \"all\" network_path = \"/om/user/shobhita/src/chexpert/CheXpert", "lesion_n, pleural_n, fracture_n = int(lesion*1.65), int(pleural*3.65), int(fracture*1.95) total_gen = total + lesion_n +", "sum(real_labels[\"Fracture\"]) lesion_n, pleural_n, fracture_n = int(lesion*1.65), int(pleural*3.65), int(fracture*1.95) total_gen = total + lesion_n", "Cardiomediastinum', 'Cardiomegaly', 'Lung Opacity', 'Lung Lesion', 'Edema', 'Consolidation', 'Pneumonia', 'Atelectasis', 'Pneumothorax', 'Pleural Effusion',", "2, 3, 1) # NCHW => NHWC save_images = np.squeeze(images, axis=-1) data_dir =", "Devices'] tf.InteractiveSession() # Import pretrained Chexpert GAN. with open(network_path + \"network-final.pkl\", 'rb') as", "= total + lesion_n + pleural_n + fracture_n print(\"Lesion: {}/{} + {} -->", "[lesion_n, pleural_n, fracture_n]): relevant_labels = real_labels[real_labels[cat] == 1] new_labels = relevant_labels.sample(n, replace=True)[names].to_numpy() label_vectors[cat]", "(pleural+pleural_n)/(total + total_gen))) print(\"Fracture: {}/{} + {} --> {}/{}\".format(fracture, fracture/total, fracture_n, fracture+fracture_n, (fracture+fracture_n)/(total", "* batch: (n + 1) * batch, :] used_labels.append(label_vec) images = Gs.run(latent_vec, label_vec)", "[\"Lung Lesion\", \"Pleural Other\", \"Fracture\"] total = len(real_labels) lesion = sum(real_labels[\"Lung Lesion\"]) pleural", "range(int(total_num / batch)): if n % 1000 == 0: print(\"{}/{}\".format(n, total_num)) latent_vec =", "n labels_save[\"{}_{}\".format(cat, image_idx)] = labels[image_idx, :] store_name = 'fake_{}_{}.png'.format(cat, image_idx) used_imgname.append(store_name) store_path =", "\"Pleural Other\", \"Fracture\"] total = len(real_labels) lesion = sum(real_labels[\"Lung Lesion\"]) pleural = sum(real_labels[\"Pleural", "1.0) / 2.0 * 255.0), 0.0, 255.0).astype(np.uint8) # [-1,1] => [0,255] images =", "= len(real_labels) lesion = sum(real_labels[\"Lung Lesion\"]) pleural = sum(real_labels[\"Pleural Other\"]) fracture = sum(real_labels[\"Fracture\"])", "= sum(real_labels[\"Lung Lesion\"]) pleural = sum(real_labels[\"Pleural Other\"]) fracture = sum(real_labels[\"Fracture\"]) lesion_n, pleural_n, fracture_n", "\"Fracture\"] total = len(real_labels) lesion = sum(real_labels[\"Lung Lesion\"]) pleural = sum(real_labels[\"Pleural Other\"]) fracture", "= output_data_path if not os.path.exists(data_dir): os.makedirs(data_dir) for idx in range(save_images.shape[0]): image_idx = idx", "{} --> {}/{}\".format(fracture, fracture/total, fracture_n, fracture+fracture_n, (fracture+fracture_n)/(total + total_gen))) sys.stdout.flush() label_vectors = {}", "'Pneumothorax', 'Pleural Effusion', 'Pleural Other', 'Fracture', 'Support Devices'] tf.InteractiveSession() # Import pretrained Chexpert", "label_vectors[cat] = new_labels for cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) labels_save =", "int(lesion*1.65), int(pleural*3.65), int(fracture*1.95) total_gen = total + lesion_n + pleural_n + fracture_n print(\"Lesion:", "= ['No Finding', 'Enlarged Cardiomediastinum', 'Cardiomegaly', 'Lung Opacity', 'Lung Lesion', 'Edema', 'Consolidation', 'Pneumonia',", "np.clip(np.rint((images + 1.0) / 2.0 * 255.0), 0.0, 255.0).astype(np.uint8) # [-1,1] => [0,255]", "print(\"Lesion: {}/{} + {} --> {}/{}\".format(lesion, lesion/total, lesion_n, lesion+lesion_n, (lesion+lesion_n)/(total+total_gen))) print(\"Pleural: {}/{} +", "in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) labels_save = {} for cat in classes_to_generate: labels", "batch: (n + 1) * batch, :] label_vec = labels[n * batch: (n", "= labels[n * batch: (n + 1) * batch, :] used_labels.append(label_vec) images =", "new_labels for cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) labels_save = {} for", "*Gs.input_shapes[0][1:]) total_num = latents_raw.shape[0] print(\"Generating {}\".format(cat)) sys.stdout.flush() for n in range(int(total_num / batch)):", "total_gen))) sys.stdout.flush() label_vectors = {} for cat, n in zip(classes_to_generate, [lesion_n, pleural_n, fracture_n]):", "print(\"{}/{}\".format(n, total_num)) latent_vec = latents_raw[n * batch: (n + 1) * batch, :]", "{}\".format(cat)) sys.stdout.flush() for n in range(int(total_num / batch)): if n % 1000 ==", "= 1 used_labels = [] used_imgname = [] latents_raw = np.random.RandomState(1000).randn(labels.shape[0], *Gs.input_shapes[0][1:]) total_num", "for idx in range(save_images.shape[0]): image_idx = idx + batch * n labels_save[\"{}_{}\".format(cat, image_idx)]", "print(\"Pleural: {}/{} + {} --> {}/{}\".format(pleural, pleural/total, pleural_n, pleural+pleural_n, (pleural+pleural_n)/(total + total_gen))) print(\"Fracture:", "pd import tensorflow as tf import PIL.Image import imageio # import tfutils import", "+ lesion_n + pleural_n + fracture_n print(\"Lesion: {}/{} + {} --> {}/{}\".format(lesion, lesion/total,", "print(\"{}: {}\".format(cat, arr.shape)) labels_save = {} for cat in classes_to_generate: labels = label_vectors[cat]", "label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) labels_save = {} for cat in classes_to_generate: labels =", "total_num = latents_raw.shape[0] print(\"Generating {}\".format(cat)) sys.stdout.flush() for n in range(int(total_num / batch)): if", "[-1,1] => [0,255] images = images.transpose(0, 2, 3, 1) # NCHW => NHWC", "labels[image_idx, :] store_name = 'fake_{}_{}.png'.format(cat, image_idx) used_imgname.append(store_name) store_path = os.path.join(data_dir, store_name) imageio.imwrite(store_path, save_images[idx])", "D, Gs = pickle.load(file) real_labels = pd.read_csv(real_data_path + \"CheXpert-v1.0-small/train_preprocessed.csv\") classes_to_generate = [\"Lung Lesion\",", "images = np.clip(np.rint((images + 1.0) / 2.0 * 255.0), 0.0, 255.0).astype(np.uint8) # [-1,1]", "with open(network_path + \"network-final.pkl\", 'rb') as file: G, D, Gs = pickle.load(file) real_labels", "<reponame>ssundaram21/6.819FinalProjectRAMP import pickle import numpy as np import pandas as pd import tensorflow", "n in zip(classes_to_generate, [lesion_n, pleural_n, fracture_n]): relevant_labels = real_labels[real_labels[cat] == 1] new_labels =", "pandas as pd import tensorflow as tf import PIL.Image import imageio # import", "label_vectors[cat] batch = 1 used_labels = [] used_imgname = [] latents_raw = np.random.RandomState(1000).randn(labels.shape[0],", "total_gen))) print(\"Fracture: {}/{} + {} --> {}/{}\".format(fracture, fracture/total, fracture_n, fracture+fracture_n, (fracture+fracture_n)/(total + total_gen)))", "* batch: (n + 1) * batch, :] label_vec = labels[n * batch:", "pickle import numpy as np import pandas as pd import tensorflow as tf", "{} --> {}/{}\".format(lesion, lesion/total, lesion_n, lesion+lesion_n, (lesion+lesion_n)/(total+total_gen))) print(\"Pleural: {}/{} + {} --> {}/{}\".format(pleural,", "Lesion', 'Edema', 'Consolidation', 'Pneumonia', 'Atelectasis', 'Pneumothorax', 'Pleural Effusion', 'Pleural Other', 'Fracture', 'Support Devices']", "2.0 * 255.0), 0.0, 255.0).astype(np.uint8) # [-1,1] => [0,255] images = images.transpose(0, 2,", "for cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) label_vectors = {} for cat,", "{}/{} + {} --> {}/{}\".format(pleural, pleural/total, pleural_n, pleural+pleural_n, (pleural+pleural_n)/(total + total_gen))) print(\"Fracture: {}/{}", "1 used_labels = [] used_imgname = [] latents_raw = np.random.RandomState(1000).randn(labels.shape[0], *Gs.input_shapes[0][1:]) total_num =", "# NCHW => NHWC save_images = np.squeeze(images, axis=-1) data_dir = output_data_path if not", "Chexpert GAN. with open(network_path + \"network-final.pkl\", 'rb') as file: G, D, Gs =", "Lesion\", \"Pleural Other\", \"Fracture\"] total = len(real_labels) lesion = sum(real_labels[\"Lung Lesion\"]) pleural =", "for n in range(int(total_num / batch)): if n % 1000 == 0: print(\"{}/{}\".format(n,", "output_data_path if not os.path.exists(data_dir): os.makedirs(data_dir) for idx in range(save_images.shape[0]): image_idx = idx +", "1) * batch, :] used_labels.append(label_vec) images = Gs.run(latent_vec, label_vec) images = np.clip(np.rint((images +", "{}\".format(cat, arr.shape)) label_vectors = {} for cat, n in zip(classes_to_generate, [lesion_n, pleural_n, fracture_n]):", "image_idx)] = labels[image_idx, :] store_name = 'fake_{}_{}.png'.format(cat, image_idx) used_imgname.append(store_name) store_path = os.path.join(data_dir, store_name)", "latents_raw[n * batch: (n + 1) * batch, :] label_vec = labels[n *", "relevant_labels = real_labels[real_labels[cat] == 1] new_labels = relevant_labels.sample(n, replace=True)[names].to_numpy() label_vectors[cat] = new_labels for", "tf.InteractiveSession() # Import pretrained Chexpert GAN. with open(network_path + \"network-final.pkl\", 'rb') as file:", "--> {}/{}\".format(fracture, fracture/total, fracture_n, fracture+fracture_n, (fracture+fracture_n)/(total + total_gen))) sys.stdout.flush() label_vectors = {} for", ":] label_vec = labels[n * batch: (n + 1) * batch, :] used_labels.append(label_vec)", "in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) label_vectors = {} for cat, n in zip(classes_to_generate,", "batch = 1 used_labels = [] used_imgname = [] latents_raw = np.random.RandomState(1000).randn(labels.shape[0], *Gs.input_shapes[0][1:])", "GAN/\" output_data_path = \"/om/user/shobhita/src/chexpert/gan_fake_data/\" real_data_path = \"/om/user/shobhita/src/chexpert/data/\" names = ['No Finding', 'Enlarged Cardiomediastinum',", "print(\"Generating {}\".format(cat)) sys.stdout.flush() for n in range(int(total_num / batch)): if n % 1000", "/ batch)): if n % 1000 == 0: print(\"{}/{}\".format(n, total_num)) latent_vec = latents_raw[n", "pleural = sum(real_labels[\"Pleural Other\"]) fracture = sum(real_labels[\"Fracture\"]) lesion_n, pleural_n, fracture_n = int(lesion*1.65), int(pleural*3.65),", "used_labels = [] used_imgname = [] latents_raw = np.random.RandomState(1000).randn(labels.shape[0], *Gs.input_shapes[0][1:]) total_num = latents_raw.shape[0]", "= sum(real_labels[\"Pleural Other\"]) fracture = sum(real_labels[\"Fracture\"]) lesion_n, pleural_n, fracture_n = int(lesion*1.65), int(pleural*3.65), int(fracture*1.95)", "= pd.read_csv(real_data_path + \"CheXpert-v1.0-small/train_preprocessed.csv\") classes_to_generate = [\"Lung Lesion\", \"Pleural Other\", \"Fracture\"] total =", "+ {} --> {}/{}\".format(fracture, fracture/total, fracture_n, fracture+fracture_n, (fracture+fracture_n)/(total + total_gen))) sys.stdout.flush() label_vectors =", "= [\"Lung Lesion\", \"Pleural Other\", \"Fracture\"] total = len(real_labels) lesion = sum(real_labels[\"Lung Lesion\"])", "{}\".format(cat, arr.shape)) labels_save = {} for cat in classes_to_generate: labels = label_vectors[cat] batch", "from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = \"all\" network_path = \"/om/user/shobhita/src/chexpert/CheXpert GAN/\" output_data_path =", "1) # NCHW => NHWC save_images = np.squeeze(images, axis=-1) data_dir = output_data_path if", "fracture_n]): relevant_labels = real_labels[real_labels[cat] == 1] new_labels = relevant_labels.sample(n, replace=True)[names].to_numpy() label_vectors[cat] = new_labels", "1000 == 0: print(\"{}/{}\".format(n, total_num)) latent_vec = latents_raw[n * batch: (n + 1)", "in zip(classes_to_generate, [lesion_n, pleural_n, fracture_n]): relevant_labels = real_labels[real_labels[cat] == 1] new_labels = relevant_labels.sample(n,", "labels = label_vectors[cat] batch = 1 used_labels = [] used_imgname = [] latents_raw", "+ 1.0) / 2.0 * 255.0), 0.0, 255.0).astype(np.uint8) # [-1,1] => [0,255] images", "imageio # import tfutils import matplotlib.pyplot as plt import os import sys from", "os.path.join(data_dir, store_name) imageio.imwrite(store_path, save_images[idx]) print(\"Done with {}\".format(cat)) print(len(labels)) print(len(used_labels)) print(len(used_imgname)) sys.stdout.flush() with open(output_data_path", "* n labels_save[\"{}_{}\".format(cat, image_idx)] = labels[image_idx, :] store_name = 'fake_{}_{}.png'.format(cat, image_idx) used_imgname.append(store_name) store_path", ":] used_labels.append(label_vec) images = Gs.run(latent_vec, label_vec) images = np.clip(np.rint((images + 1.0) / 2.0", "total = len(real_labels) lesion = sum(real_labels[\"Lung Lesion\"]) pleural = sum(real_labels[\"Pleural Other\"]) fracture =", "= os.path.join(data_dir, store_name) imageio.imwrite(store_path, save_images[idx]) print(\"Done with {}\".format(cat)) print(len(labels)) print(len(used_labels)) print(len(used_imgname)) sys.stdout.flush() with", "= 'fake_{}_{}.png'.format(cat, image_idx) used_imgname.append(store_name) store_path = os.path.join(data_dir, store_name) imageio.imwrite(store_path, save_images[idx]) print(\"Done with {}\".format(cat))", "pleural_n, fracture_n = int(lesion*1.65), int(pleural*3.65), int(fracture*1.95) total_gen = total + lesion_n + pleural_n", "# [-1,1] => [0,255] images = images.transpose(0, 2, 3, 1) # NCHW =>", "'Edema', 'Consolidation', 'Pneumonia', 'Atelectasis', 'Pneumothorax', 'Pleural Effusion', 'Pleural Other', 'Fracture', 'Support Devices'] tf.InteractiveSession()", "save_images[idx]) print(\"Done with {}\".format(cat)) print(len(labels)) print(len(used_labels)) print(len(used_imgname)) sys.stdout.flush() with open(output_data_path + \"gan_image_labels.pkl\", \"wb\")", "real_labels[real_labels[cat] == 1] new_labels = relevant_labels.sample(n, replace=True)[names].to_numpy() label_vectors[cat] = new_labels for cat, arr", "lesion+lesion_n, (lesion+lesion_n)/(total+total_gen))) print(\"Pleural: {}/{} + {} --> {}/{}\".format(pleural, pleural/total, pleural_n, pleural+pleural_n, (pleural+pleural_n)/(total +", "=> NHWC save_images = np.squeeze(images, axis=-1) data_dir = output_data_path if not os.path.exists(data_dir): os.makedirs(data_dir)", "arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) label_vectors = {} for cat, n in", "fracture/total, fracture_n, fracture+fracture_n, (fracture+fracture_n)/(total + total_gen))) sys.stdout.flush() label_vectors = {} for cat, n", "+ fracture_n print(\"Lesion: {}/{} + {} --> {}/{}\".format(lesion, lesion/total, lesion_n, lesion+lesion_n, (lesion+lesion_n)/(total+total_gen))) print(\"Pleural:", "batch)): if n % 1000 == 0: print(\"{}/{}\".format(n, total_num)) latent_vec = latents_raw[n *", "relevant_labels.sample(n, replace=True)[names].to_numpy() label_vectors[cat] = new_labels for cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape))", "NHWC save_images = np.squeeze(images, axis=-1) data_dir = output_data_path if not os.path.exists(data_dir): os.makedirs(data_dir) for", "= int(lesion*1.65), int(pleural*3.65), int(fracture*1.95) total_gen = total + lesion_n + pleural_n + fracture_n", "pleural_n + fracture_n print(\"Lesion: {}/{} + {} --> {}/{}\".format(lesion, lesion/total, lesion_n, lesion+lesion_n, (lesion+lesion_n)/(total+total_gen)))", "--> {}/{}\".format(pleural, pleural/total, pleural_n, pleural+pleural_n, (pleural+pleural_n)/(total + total_gen))) print(\"Fracture: {}/{} + {} -->", "arr.shape)) labels_save = {} for cat in classes_to_generate: labels = label_vectors[cat] batch =", "sum(real_labels[\"Pleural Other\"]) fracture = sum(real_labels[\"Fracture\"]) lesion_n, pleural_n, fracture_n = int(lesion*1.65), int(pleural*3.65), int(fracture*1.95) total_gen", "(n + 1) * batch, :] label_vec = labels[n * batch: (n +", "= \"/om/user/shobhita/src/chexpert/data/\" names = ['No Finding', 'Enlarged Cardiomediastinum', 'Cardiomegaly', 'Lung Opacity', 'Lung Lesion',", "= Gs.run(latent_vec, label_vec) images = np.clip(np.rint((images + 1.0) / 2.0 * 255.0), 0.0,", "pickle.load(file) real_labels = pd.read_csv(real_data_path + \"CheXpert-v1.0-small/train_preprocessed.csv\") classes_to_generate = [\"Lung Lesion\", \"Pleural Other\", \"Fracture\"]", "import matplotlib.pyplot as plt import os import sys from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity", "lesion/total, lesion_n, lesion+lesion_n, (lesion+lesion_n)/(total+total_gen))) print(\"Pleural: {}/{} + {} --> {}/{}\".format(pleural, pleural/total, pleural_n, pleural+pleural_n,", "sys.stdout.flush() with open(output_data_path + \"gan_image_labels.pkl\", \"wb\") as handle: pickle.dump(labels_save, handle) sys.stdout.flush() print(\"Done :)\")", "{}/{}\".format(fracture, fracture/total, fracture_n, fracture+fracture_n, (fracture+fracture_n)/(total + total_gen))) sys.stdout.flush() label_vectors = {} for cat,", "print(len(used_imgname)) sys.stdout.flush() with open(output_data_path + \"gan_image_labels.pkl\", \"wb\") as handle: pickle.dump(labels_save, handle) sys.stdout.flush() print(\"Done", "+ batch * n labels_save[\"{}_{}\".format(cat, image_idx)] = labels[image_idx, :] store_name = 'fake_{}_{}.png'.format(cat, image_idx)", "* batch, :] label_vec = labels[n * batch: (n + 1) * batch,", "replace=True)[names].to_numpy() label_vectors[cat] = new_labels for cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) labels_save", "labels[n * batch: (n + 1) * batch, :] used_labels.append(label_vec) images = Gs.run(latent_vec,", "import pickle import numpy as np import pandas as pd import tensorflow as", "= sum(real_labels[\"Fracture\"]) lesion_n, pleural_n, fracture_n = int(lesion*1.65), int(pleural*3.65), int(fracture*1.95) total_gen = total +", "for cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) labels_save = {} for cat", "\"/om/user/shobhita/src/chexpert/data/\" names = ['No Finding', 'Enlarged Cardiomediastinum', 'Cardiomegaly', 'Lung Opacity', 'Lung Lesion', 'Edema',", "= relevant_labels.sample(n, replace=True)[names].to_numpy() label_vectors[cat] = new_labels for cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat,", "range(save_images.shape[0]): image_idx = idx + batch * n labels_save[\"{}_{}\".format(cat, image_idx)] = labels[image_idx, :]", "'Pneumonia', 'Atelectasis', 'Pneumothorax', 'Pleural Effusion', 'Pleural Other', 'Fracture', 'Support Devices'] tf.InteractiveSession() # Import", "Lesion\"]) pleural = sum(real_labels[\"Pleural Other\"]) fracture = sum(real_labels[\"Fracture\"]) lesion_n, pleural_n, fracture_n = int(lesion*1.65),", "as pd import tensorflow as tf import PIL.Image import imageio # import tfutils", "= pickle.load(file) real_labels = pd.read_csv(real_data_path + \"CheXpert-v1.0-small/train_preprocessed.csv\") classes_to_generate = [\"Lung Lesion\", \"Pleural Other\",", "np.random.RandomState(1000).randn(labels.shape[0], *Gs.input_shapes[0][1:]) total_num = latents_raw.shape[0] print(\"Generating {}\".format(cat)) sys.stdout.flush() for n in range(int(total_num /", "open(network_path + \"network-final.pkl\", 'rb') as file: G, D, Gs = pickle.load(file) real_labels =", "latents_raw = np.random.RandomState(1000).randn(labels.shape[0], *Gs.input_shapes[0][1:]) total_num = latents_raw.shape[0] print(\"Generating {}\".format(cat)) sys.stdout.flush() for n in", "'Fracture', 'Support Devices'] tf.InteractiveSession() # Import pretrained Chexpert GAN. with open(network_path + \"network-final.pkl\",", "lesion_n, lesion+lesion_n, (lesion+lesion_n)/(total+total_gen))) print(\"Pleural: {}/{} + {} --> {}/{}\".format(pleural, pleural/total, pleural_n, pleural+pleural_n, (pleural+pleural_n)/(total", "numpy as np import pandas as pd import tensorflow as tf import PIL.Image", "Other', 'Fracture', 'Support Devices'] tf.InteractiveSession() # Import pretrained Chexpert GAN. with open(network_path +", "pleural/total, pleural_n, pleural+pleural_n, (pleural+pleural_n)/(total + total_gen))) print(\"Fracture: {}/{} + {} --> {}/{}\".format(fracture, fracture/total,", "# Import pretrained Chexpert GAN. with open(network_path + \"network-final.pkl\", 'rb') as file: G,", "'Pleural Other', 'Fracture', 'Support Devices'] tf.InteractiveSession() # Import pretrained Chexpert GAN. with open(network_path", "\"all\" network_path = \"/om/user/shobhita/src/chexpert/CheXpert GAN/\" output_data_path = \"/om/user/shobhita/src/chexpert/gan_fake_data/\" real_data_path = \"/om/user/shobhita/src/chexpert/data/\" names =", "if not os.path.exists(data_dir): os.makedirs(data_dir) for idx in range(save_images.shape[0]): image_idx = idx + batch", "'Support Devices'] tf.InteractiveSession() # Import pretrained Chexpert GAN. with open(network_path + \"network-final.pkl\", 'rb')", "= \"/om/user/shobhita/src/chexpert/gan_fake_data/\" real_data_path = \"/om/user/shobhita/src/chexpert/data/\" names = ['No Finding', 'Enlarged Cardiomediastinum', 'Cardiomegaly', 'Lung", "lesion_n + pleural_n + fracture_n print(\"Lesion: {}/{} + {} --> {}/{}\".format(lesion, lesion/total, lesion_n,", "images.transpose(0, 2, 3, 1) # NCHW => NHWC save_images = np.squeeze(images, axis=-1) data_dir", "network_path = \"/om/user/shobhita/src/chexpert/CheXpert GAN/\" output_data_path = \"/om/user/shobhita/src/chexpert/gan_fake_data/\" real_data_path = \"/om/user/shobhita/src/chexpert/data/\" names = ['No", "label_vectors[cat] = new_labels for cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) label_vectors =", "Other\", \"Fracture\"] total = len(real_labels) lesion = sum(real_labels[\"Lung Lesion\"]) pleural = sum(real_labels[\"Pleural Other\"])", "with {}\".format(cat)) print(len(labels)) print(len(used_labels)) print(len(used_imgname)) sys.stdout.flush() with open(output_data_path + \"gan_image_labels.pkl\", \"wb\") as handle:", "'Lung Lesion', 'Edema', 'Consolidation', 'Pneumonia', 'Atelectasis', 'Pneumothorax', 'Pleural Effusion', 'Pleural Other', 'Fracture', 'Support", "+ 1) * batch, :] used_labels.append(label_vec) images = Gs.run(latent_vec, label_vec) images = np.clip(np.rint((images", "arr.shape)) label_vectors = {} for cat, n in zip(classes_to_generate, [lesion_n, pleural_n, fracture_n]): relevant_labels", "fracture = sum(real_labels[\"Fracture\"]) lesion_n, pleural_n, fracture_n = int(lesion*1.65), int(pleural*3.65), int(fracture*1.95) total_gen = total", "= label_vectors[cat] batch = 1 used_labels = [] used_imgname = [] latents_raw =", "= new_labels for cat, arr in label_vectors.items(): print(\"{}: {}\".format(cat, arr.shape)) label_vectors = {}", "for cat in classes_to_generate: labels = label_vectors[cat] batch = 1 used_labels = []", "batch, :] label_vec = labels[n * batch: (n + 1) * batch, :]", "as file: G, D, Gs = pickle.load(file) real_labels = pd.read_csv(real_data_path + \"CheXpert-v1.0-small/train_preprocessed.csv\") classes_to_generate", "'Pleural Effusion', 'Pleural Other', 'Fracture', 'Support Devices'] tf.InteractiveSession() # Import pretrained Chexpert GAN.", "= labels[image_idx, :] store_name = 'fake_{}_{}.png'.format(cat, image_idx) used_imgname.append(store_name) store_path = os.path.join(data_dir, store_name) imageio.imwrite(store_path,", "idx + batch * n labels_save[\"{}_{}\".format(cat, image_idx)] = labels[image_idx, :] store_name = 'fake_{}_{}.png'.format(cat,", "used_imgname.append(store_name) store_path = os.path.join(data_dir, store_name) imageio.imwrite(store_path, save_images[idx]) print(\"Done with {}\".format(cat)) print(len(labels)) print(len(used_labels)) print(len(used_imgname))", "pleural_n, fracture_n]): relevant_labels = real_labels[real_labels[cat] == 1] new_labels = relevant_labels.sample(n, replace=True)[names].to_numpy() label_vectors[cat] =", "Gs.run(latent_vec, label_vec) images = np.clip(np.rint((images + 1.0) / 2.0 * 255.0), 0.0, 255.0).astype(np.uint8)", "= np.clip(np.rint((images + 1.0) / 2.0 * 255.0), 0.0, 255.0).astype(np.uint8) # [-1,1] =>", "n in range(int(total_num / batch)): if n % 1000 == 0: print(\"{}/{}\".format(n, total_num))", "save_images = np.squeeze(images, axis=-1) data_dir = output_data_path if not os.path.exists(data_dir): os.makedirs(data_dir) for idx", "latent_vec = latents_raw[n * batch: (n + 1) * batch, :] label_vec =", "idx in range(save_images.shape[0]): image_idx = idx + batch * n labels_save[\"{}_{}\".format(cat, image_idx)] =", "as np import pandas as pd import tensorflow as tf import PIL.Image import", "total_gen = total + lesion_n + pleural_n + fracture_n print(\"Lesion: {}/{} + {}", "{} --> {}/{}\".format(pleural, pleural/total, pleural_n, pleural+pleural_n, (pleural+pleural_n)/(total + total_gen))) print(\"Fracture: {}/{} + {}", "Opacity', 'Lung Lesion', 'Edema', 'Consolidation', 'Pneumonia', 'Atelectasis', 'Pneumothorax', 'Pleural Effusion', 'Pleural Other', 'Fracture',", "matplotlib.pyplot as plt import os import sys from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity =", "* 255.0), 0.0, 255.0).astype(np.uint8) # [-1,1] => [0,255] images = images.transpose(0, 2, 3,", "print(len(labels)) print(len(used_labels)) print(len(used_imgname)) sys.stdout.flush() with open(output_data_path + \"gan_image_labels.pkl\", \"wb\") as handle: pickle.dump(labels_save, handle)", "3, 1) # NCHW => NHWC save_images = np.squeeze(images, axis=-1) data_dir = output_data_path", "imageio.imwrite(store_path, save_images[idx]) print(\"Done with {}\".format(cat)) print(len(labels)) print(len(used_labels)) print(len(used_imgname)) sys.stdout.flush() with open(output_data_path + \"gan_image_labels.pkl\",", "1) * batch, :] label_vec = labels[n * batch: (n + 1) *", "/ 2.0 * 255.0), 0.0, 255.0).astype(np.uint8) # [-1,1] => [0,255] images = images.transpose(0," ]
[ "\\ (other.func, other.args, other._keys) except AttributeError: # other is not a Command return", "symbol(self): \"\"\"return a unique symbol for this Character\"\"\" # failsafe to ensure that", "self._mode.value, set(self._classes), set(self._include_chars), set(self._exclude_chars) ) @staticmethod def from_dict(filter_dict): \"\"\"returns a Filter pythonic representation", "That is, if a WHITELIST includes the class Wizard, but Bill the Wizard", "setattr(self, cmd.func.__name__, cmd) # set up inventory and equipping items self.inv = inv.Inventory()", "in this player's equip dict [item]: item to Equip [from_inv]: if True, [item]", "frequency: how often will new players spawn as this class - command_label: how", "each ancestor ancestors = filter(lambda x: isinstance(x, CharacterClass), other.__mro__) for char_class in ancestors:", "WHITELIST is selected, only characters whose class is in _classes are allowed through", "BLACKLIST = _FilterMode.BLACKLIST def __init__(self, mode, classes=(), include_chars=(), exclude_chars=()): \"\"\"initialize a Filter with", "a string representation of the equipped items equipped = [] for target, item", "self.set_location(loc) self._parser = self._command_parser def _command_parser(self, line: str): \"\"\"The default parser for a", "self.label = None # by default, add a filter that permits all (empty", ") @staticmethod def from_dict(filter_dict): \"\"\"returns a Filter pythonic representation [filter_dict]\"\"\" return Filter(**filter_dict) def", "to see if this character even has [target] # in its equip slots", "self.message(menu) else: name = args[1] try: self.message(self.cmd_dict[name].help_entry()) except KeyError: self.message(f\"Command '{name}' not recognized.\")", "\"\"\"The default parser for a player. Parses\"\"\" # command is always the first", "else: if mode.lower() == \"whitelist\": self._mode = Filter.WHITELIST elif mode.lower() == \"blacklist\": self._mode", "def exclude(self, other): \"\"\"Set the filter to return 'False' if [other] is supplied", "Filter.BLACKLIST if WHITELIST is selected, only characters whose class is in _classes are", "we must manually bind the methods # TODO: override getattribute__ to solve the", "try to clean the docstring, if one was provided try: self.__doc__ = inspect.cleandoc(self.__doc__)", "(Affects help menu.) [filter] = if provided, determine which Characters / Classes are", "if inv_msg: self.message(inv_msg) @Command.with_traits(name=\"use\") def cmd_use(self, args): \"\"\" Use an item. usage: use", "raise ValueError(\"Unrecognized mode %s\" % repr(mode)) def permits(self, other): \"\"\"returns True if Character/CharacterClass", "a description of your current location. usage: look \"\"\" # TODO: update to", "set_location(self, new_location): \"\"\"sets location, updating the previous and new locations as necessary and", "self.location is not None: self.location.message(f\"{self} died.\", exclude={self}) try: self.location.characters.remove(self) except ValueError: pass self.location", "self.cmd_dict[name] = cmd # because sCommands are not bound properly like a normal", "def set_location(self, new_location): \"\"\"sets location, updating the previous and new locations as necessary", "does not normally support equality for mathematically sound reasons: https://bugs.python.org/issue3564 With this class's", "if inv has items if inv_msg: self.message(inv_msg) @Command.with_traits(name=\"use\") def cmd_use(self, args): \"\"\" Use", "for name, cmd in self.cmd_dict.items(): try: sources[cmd.label].append(name) except KeyError: sources[cmd.label] = [name] #", "for char in exclude_chars: if char in include_chars: raise ValueError(\"Cannot have character in", "have an equip target for this item, cannot equip else: self.message(f\"Cannot equip item", "1: item = found_items[0][0] self.location.inv.remove_item(item) self.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity", "name=item_name) if len(found_items) == 1: self.equip(found_items[0][0]) elif len(found_items) > 1: #TODO handle ambiguity", "# note that a new filter is not created, so any changes to", "how often will new players spawn as this class - command_label: how commands", "[target] is set to None and any item at that position is unequipped", "\".join(args[1::]).lower() # TODO: find a way to provide type=Item found_items = util.find(self.location, name=item_name)", "name, cmd in self.cmd_dict.items(): try: sources[cmd.label].append(name) except KeyError: sources[cmd.label] = [name] # unpack", "# add a frequency field, if not already provided if \"frequency\" not in", "Command): setattr(self, cmd.func.__name__, cmd) # set up inventory and equipping items self.inv =", "an accessible location. usage: go [exit name] \"\"\" ex_name = \" \".join(args[1:]) #", "is even equipped # also duck test to see if this character even", "then the Character's class, then all the Character's ancestor classes \"\"\" if isinstance(other,", "someone forgets to set self._symbol in the __init__ if not hasattr(self, \"_symbol\"): symbol", "in self._exclude_chars: return False # now try the Character's class other = type(other)", "try: return (self.func, self.args, self._keys) == \\ (other.func, other.args, other._keys) except AttributeError: #", "except AttributeError: # other is not a Command return False def __hash__(self): \"\"\"overriding", "set self._symbol in the __init__ if not hasattr(self, \"_symbol\"): symbol = \"{}#{}\".format(type(self).__name__, util.to_base(id(self),", "all in-game characters. This module also defines the 'Filter', used for CharacterClass-based permissions", "Character): if other in self._include_chars: return True elif other in self._exclude_chars: return False", "\"\"\"updates this character's equip_dict such that the [target] is set to None and", "filter(lambda x: isinstance(x, CharacterClass), other.__mro__) for char_class in ancestors: if char_class in self._classes:", "the entities # in the current location for entity in self.location.entities: entity.on_exit(self) entity.remove_cmds(self)", "interact with the exit, # we lie to them and pretend like it", "= self.inv.readable() # only send a message if inv has items if inv_msg:", "the current location for entity in self.location.entities: entity.on_exit(self) entity.remove_cmds(self) except AttributeError: # location", "- set of CharacterClasses tracked by the filter _include_chars - set characters to", "item.target except AttributeError: self.message(f\"{item} cannot be equipped.\") return if target in self.equip_dict: #", "In addition, this class has a convenience method, '.specify' to derive a new", "ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to pick", "longer, user-focused depiction of Character\"\"\" if self._name is None: return f\"A nameless {type(self)}\"", "character will parse 'msg' using its current parser.\"\"\" if msg: self._parser(msg) def update(self):", "is evaluated first, then the Character's class, then all the Character's ancestor classes", "= self._join_parser def despawn(self): \"\"\"method executed when a player dies\"\"\" self.message(\"You died.\") if", "we lie to them and pretend like it doesn't exist else: self.message(f\"No exit", "# search through the items in the equip_dict found_items = [] for _,", "this class appear in help menu \"\"\" def __init__(cls, name, bases, namespace): #", "one was provided try: self.__doc__ = inspect.cleandoc(self.__doc__) except AttributeError: pass # initialize satellite", "CharacterClasses and Characters _classes - set of CharacterClasses tracked by the filter _include_chars", "str = None, label: str = None, filter: Filter = None): \"\"\"decorator to", "# Note! If writing your own method, just do # util.find(location, ex_name, location.Exit,", "other is a Character / CharacterClass if isinstance(other, CharacterClass): if self._mode is Filter.WHITELIST:", "argument, the prior argument will be overriden. \"\"\" args = self.args + tuple(newargs)", "args): \"\"\"Go to an accessible location. usage: go [exit name] \"\"\" ex_name =", "other in self._classes: self._classes.remove(other) else: self._classes.add(other) elif isinstance(other, Character): if other in self._include_chars:", "# check for an already equipped weapon, unequip it if self.equip_dict[target] is not", "up.\") @Command def drop(self, args): \"\"\"Drop an item into the environment\"\"\" if len(args)", "as the basis for all in-game characters. This module also defines the 'Filter',", "are not bound properly like a normal # method, we must manually bind", "old_location = self.location new_location = found_exit.destination new_location.message(f\"{self} entered.\") self.set_location(new_location) # TODO: only show", "that converts methods into commands that can be invoked by characters. \"\"\" import", "(self.func, self.args, self._keys) == \\ (other.func, other.args, other._keys) except AttributeError: # other is", "return classname\"\"\" return cls.classname class Character(metaclass=CharacterClass): \"\"\"Base class for all other CharacterClasses\"\"\" #", "@Command.with_traits(name=\"equip\") def cmd_equip(self, args): \"\"\"Equip an equippable item from your inventory.\"\"\" if len(args)", "= self.func.__name__ self.__doc__ = self.func.__doc__ # try to clean the docstring, if one", "spawn_location self._parser = self._join_parser def despawn(self): \"\"\"method executed when a player dies\"\"\" self.message(\"You", "field is used in creating help menus if \"command_label\" not in namespace: cls.command_label", "command if no name is provided, func.__name__ is used \"\"\" if self.name is", "already provided if \"classname\" not in namespace: cls.classname = util.camel_to_space(name) # add a", "None self.label = None # by default, add a filter that permits all", "args): \"\"\"Show your inventory. usage: inv\"\"\" # create a string representation of the", "only send a message if inv has items if inv_msg: self.message(inv_msg) @Command.with_traits(name=\"use\") def", "= found_exit.destination new_location.message(f\"{self} entered.\") self.set_location(new_location) # TODO: only show the exit if a", "usage: look \"\"\" # TODO: update to allow players to 'inspect' certain objects", "entity.on_enter(self) entity.add_cmds(self) #inventory/item related methods def add_item(self, item, amt=1): \"\"\"add [item] to player's", "return True elif other in self._exclude_chars: return False # now try the Character's", "self._mode is Filter.WHITELIST: self._classes.add(other) else: if other in self._classes: self._classes.remove(other) elif isinstance(other, Character):", "evaluated first, then the Character's class, then all the Character's ancestor classes \"\"\"", "str: \"\"\"return a help message for this command\"\"\" if self.label is not None:", "[] for _, equip_data in self.equip_dict.items(): if equip_data is None: continue item, _", "keywords for comparisons self._keys = frozenset(self.keywords.items()) # propagate the name and doc from", "self._classes: return self._mode.value # \"other\" is neither a CharClass nor Character else: return", "none\") else: equipped.append(f\"{target}: {item[0]}\") equipped.sort() self.message(\"\\n\".join(equipped)) inv_msg = self.inv.readable() # only send a", "cmd_unequip(self, args): \"\"\"Unequip an equipped item. Usage: unequip [item]\"\"\" if len(args) < 2:", "sources: source, names = sources.popitem() output.append(f\"---{source}---\") output.append(\" \".join(names)) return \"\\n\".join(output) # serialization-related methods", "duplication if from_inv: try: self.inv.remove_item(item) # item not found except KeyError: self.message(f\"Cannot equip", "self.inv.remove_item(item) # item not found except KeyError: self.message(f\"Cannot equip {item}-\" \"not found in", "a name is submitted. \"\"\" self.message(f\"Welcome to our SwampyMud! You are a {type(self)}\")", "ex.names: found_exit = ex break else: self.message(f\"No exit with name '{ex_name}'.\") return if", "the controller of this character\"\"\" # place a self.msgs.put_nowait(msg) def command(self, msg): \"\"\"issue", "appear in help menu \"\"\" def __init__(cls, name, bases, namespace): # add the", "source new_cmd.name = self.name new_cmd.label = self.label # note that a new filter", "metaclass and Character class, which serves as the basis for all in-game characters.", "is None: continue item, _ = equip_data if str(item).lower() == item_name: found_items.append(item) if", "/ _exclude_chars take precedence over the _classes. That is, if a WHITELIST includes", "the proper name, if not already provided if \"classname\" not in namespace: cls.classname", "_dead_parser(self, line: str): \"\"\"Parser used when a character has died\"\"\" self.message(\"You have died.", "duck test that the item is even equippable try: target = item.target except", "in the list return not self._mode.value def include(self, other): \"\"\"Set the filter to", "return item_name = \" \".join(args[1::]).lower() # TODO: find a way to provide type=Item", "message for this command\"\"\" if self.label is not None: return f\"{self} [from {self.label}]:\\n{self.__doc__}\"", "Command like a functools.partial object\"\"\" super().__init__() # creating an immutable set of keywords", "def __eq__(self, other): \"\"\"Two commands are equal iff the base functions are equal,", "selected, only characters whose class is in _classes are allowed through the filter.", "often will new players spawn as this class - command_label: how commands from", "= [] for target, item in self.equip_dict.items(): if item is None: equipped.append(f\"{target}: none\")", "if isinstance(cls, CharacterClass): sources[cls.command_label] = [] for name, cmd in self.cmd_dict.items(): try: sources[cmd.label].append(name)", "for base in reversed(cls.__mro__): if not isinstance(base, CharacterClass): continue cls._commands.update(base._local_commands) cls._commands.update(cls._local_commands) # calling", "permissions systems, and 'Command', a wrapper that converts methods into commands that can", "that permits all (empty blacklist) self.filter = Filter(Filter.BLACKLIST) def __eq__(self, other): \"\"\"Two commands", "\"\"\" args = self.args + tuple(newargs) keywords = self.keywords.copy() keywords.update(new_keywords) new_cmd = Command(self.func,", "serialization-related methods @property def symbol(self): \"\"\"return a unique symbol for this Character\"\"\" #", "not found in inventory, the command fails. if False, [item] is not removed", "args are equal, and the (initial) keywords are equal\"\"\" try: return (self.func, self.args,", "that other is a Character / CharacterClass if isinstance(other, CharacterClass): if self._mode is", "equipped.remove_cmds(self) self.equip_dict[target] = None # if item was from character's inventory, return it", "import util from swampymud.util.shadowdict import ShadowDict class Filter: \"\"\"Filter for screening out certain", "import functools import inspect import weakref import asyncio import swampymud.inventory as inv from", "True, the Filter will act as a whitelist if [mode] is False, the", "self.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else:", "a functools.partial object\"\"\" super().__init__() # creating an immutable set of keywords for comparisons", "for cls in reversed(type(self).__mro__): if isinstance(cls, CharacterClass): sources[cls.command_label] = [] for name, cmd", "forgets to set self._symbol in the __init__ if not hasattr(self, \"_symbol\"): symbol =", "find item '{item_name}'.\") @Command.with_traits(name=\"unequip\") def cmd_unequip(self, args): \"\"\"Unequip an equipped item. Usage: unequip", "return \"\\n\".join(output) # serialization-related methods @property def symbol(self): \"\"\"return a unique symbol for", "name is submitted. \"\"\" self.message(f\"Welcome to our SwampyMud! You are a {type(self)}\") self.message(f\"What", "self.message(\"Please specify an item.\") return item_name = args[1] found_items = util.find(self.inv, name=item_name) if", "' '.join(args[1:]) if msg and self.location is not None: self.location.message(f\"{self.view()}: {msg}\") @Command def", "Options may vary per item. \"\"\" # TODO: allow players to use accessible", "\"\"\"Parser for a newly joined player, used for selecting a valid name\"\"\" if", "= {\"mode\" : self._mode.value} if self._classes: data[\"classes\"] = list(self._classes) if self._include_chars: data[\"include_chars\"] =", "this player's equip dict [item]: item to Equip [from_inv]: if True, [item] should", "received %s\" % type(other)) def exclude(self, other): \"\"\"Set the filter to return 'False'", "if not isinstance(base, CharacterClass): continue cls._commands.update(base._local_commands) cls._commands.update(cls._local_commands) # calling the super init super().__init__(name,", "[filter] = if provided, determine which Characters / Classes are permitted to use", "AttributeError: # other is not a Command return False def __hash__(self): \"\"\"overriding hash\"\"\"", "equipped items equipped = [] for target, item in self.equip_dict.items(): if item is", "your current location. usage: look \"\"\" # TODO: update to allow players to", "Command(self.func, *args, **keywords) # propagate the name and source new_cmd.name = self.name new_cmd.label", "a unique symbol for this Character\"\"\" # failsafe to ensure that Character always", "in the current location for entity in self.location.entities: entity.on_exit(self) entity.remove_cmds(self) except AttributeError: #", "for an already equipped weapon, unequip it if self.equip_dict[target] is not None: self.unequip(target)", "found_exit.interact.permits(self): old_location = self.location new_location = found_exit.destination new_location.message(f\"{self} entered.\") self.set_location(new_location) # TODO: only", "specific characters to be excluded \"\"\" self._classes = set(classes) for char in include_chars:", "received update\") def spawn(self, spawn_location): \"\"\"Send a greeting to the character and put", "player will not be available to attack self.location = spawn_location self._parser = self._join_parser", "a message if inv has items if inv_msg: self.message(inv_msg) @Command.with_traits(name=\"use\") def cmd_use(self, args):", "\"\"\" self._classes = set(classes) for char in include_chars: if char in exclude_chars: raise", "update\") def spawn(self, spawn_location): \"\"\"Send a greeting to the character and put them", "try: self.location.characters.remove(self) # remove commands from all the entities # in the current", "method, '.specify' to derive a new Command from an existing one by simply", "tracked by the filter _include_chars - set characters to be included _exclude_chars -", "if one was provided try: self.__doc__ = inspect.cleandoc(self.__doc__) except AttributeError: pass # initialize", "have character in both include\" \" and exclude\") # store characters in a", "all the entities # in the current locations for entity in new_location.entities: entity.on_enter(self)", "from any entities in the location \"\"\" try: self.location.characters.remove(self) # remove commands from", "def __init__(self, mode, classes=(), include_chars=(), exclude_chars=()): \"\"\"initialize a Filter with [mode] if [mode]", "a provided keyword argument conflicts with a prior argument, the prior argument will", "= name cmd.label = label if filter is not None: cmd.filter = filter", "base function self.__name__ = self.func.__name__ self.__doc__ = self.func.__doc__ # try to clean the", "list(self._include_chars) if self._exclude_chars: data[\"exclude_chars\"] = list(self._exclude_chars) return data class Command(functools.partial): \"\"\"A subclass of", "a longer, user-focused depiction of Character\"\"\" if self._name is None: return f\"A nameless", "@staticmethod def from_dict(filter_dict): \"\"\"returns a Filter pythonic representation [filter_dict]\"\"\" return Filter(**filter_dict) def to_dict(self):", "and will not be returned to inventory upon unequip. \"\"\" # duck test", "sound reasons: https://bugs.python.org/issue3564 With this class's equality operators, we aren't trying to solve", "all other CharacterClasses\"\"\" # How this class appears to players classname = \"Default", "import asyncio import swampymud.inventory as inv from swampymud import util from swampymud.util.shadowdict import", "else: self._classes.add(other) elif isinstance(other, Character): if other in self._include_chars: self._include_chars.remove(other) self._exclude_chars.add(other) else: raise", "any entities in the location \"\"\" try: self.location.characters.remove(self) # remove commands from all", "for this item, cannot equip else: self.message(f\"Cannot equip item {item} to {target}.\") return", "representation of the equipped items equipped = [] for target, item in self.equip_dict.items():", "other information (base function, names, etc.) will be propagated. While you can update", "if self._mode is Filter.WHITELIST: self._classes.add(other) else: if other in self._classes: self._classes.remove(other) elif isinstance(other,", "< 2: self.message(\"Provide an item to equip.\") return item_name = \" \".join(args[1::]).lower() #", "cmd.func.__name__, cmd) # set up inventory and equipping items self.inv = inv.Inventory() self.equip_dict", "if mode.lower() == \"whitelist\": self._mode = Filter.WHITELIST elif mode.lower() == \"blacklist\": self._mode =", "server to start\" \" as a new character.\") # string-formatting methods def __repr__(self):", "characters whose class is NOT in _classes are allowed through the filter. Note", "to get the list of CharacterClasses in order for cls in reversed(type(self).__mro__): if", "converts methods into commands that can be invoked by characters. \"\"\" import enum", "< 2: self.message(\"Provide an item to pick up.\") return item_name = \" \".join(args[1::]).lower()", "a filter that permits all (empty blacklist) self.filter = Filter(Filter.BLACKLIST) def __eq__(self, other):", "(base function, names, etc.) will be propagated. While you can update Command.keywords, avoid", "except KeyError: self.message(f\"Command '{name}' not recognized.\") @Command def look(self, args): \"\"\"Gives a description", "Filter with [mode] if [mode] is True, the Filter will act as a", "label: str = None, filter: Filter = None): \"\"\"decorator to easily wrap a", "self._include_chars: return True elif other in self._exclude_chars: return False # now try the", "\"\"\" # TODO: update to allow players to 'inspect' certain objects self.message(self.location.view()) @Command", "if from_inv: try: self.inv.remove_item(item) # item not found except KeyError: self.message(f\"Cannot equip {item}-\"", "ex in self.location._exit_list: if ex_name in ex.names: found_exit = ex break else: self.message(f\"No", "self.location self.location = None self.set_location(loc) self._parser = self._command_parser def _command_parser(self, line: str): \"\"\"The", "self.location._exit_list: if ex_name in ex.names: found_exit = ex break else: self.message(f\"No exit with", "is unsupported. \"\"\" def __init__(self, *args, **kwargs): \"\"\"initialize a Command like a functools.partial", "\"\"\" ex_name = \" \".join(args[1:]) # Manually iterating over our location's list of", "data[\"classes\"] = list(self._classes) if self._include_chars: data[\"include_chars\"] = list(self._include_chars) if self._exclude_chars: data[\"exclude_chars\"] = list(self._exclude_chars)", "sources[cmd.label].append(name) except KeyError: sources[cmd.label] = [name] # unpack the dictionary in reverse order", "self._mode.value} if self._classes: data[\"classes\"] = list(self._classes) if self._include_chars: data[\"include_chars\"] = list(self._include_chars) if self._exclude_chars:", "the environment\"\"\" if len(args) < 2: self.message(\"Provide an item to drop.\") return item_name", "self.location.characters.remove(self) # remove commands from all the entities # in the current location", "item name. Results={found_items}\") else: self.message(f\"Could not find equipped item '{item_name}'.\") @Command def pickup(self,", "'Command': \"\"\"Derive a new version of this function by applying additional arguments. If", "= [] for _, equip_data in self.equip_dict.items(): if equip_data is None: continue item,", "name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to use.\") # miscellaneous methods", "to all players in your current location. usage: say [msg] \"\"\" msg =", "{\"_type\": type(self), \"name\": self._name} def children(self): \"\"\"pass\"\"\" return [] #TODO: handle items here", "\"\"\"Filter for screening out certain CharacterClasses and Characters _classes - set of CharacterClasses", "use [name] instead of the function's name [label] = the type of the", "commands, with the most recent commands exposed cls._commands = {} for base in", "isinstance(other, CharacterClass): # cycle through each ancestor ancestors = filter(lambda x: isinstance(x, CharacterClass),", "current parser.\"\"\" if msg: self._parser(msg) def update(self): \"\"\"periodically called method that updates character", "target, item in self.equip_dict.items(): if item is None: equipped.append(f\"{target}: none\") else: equipped.append(f\"{target}: {item[0]}\")", "to allow players to 'inspect' certain objects self.message(self.location.view()) @Command def say(self, args): \"\"\"Send", "character's inventory, return it if from_inv: self.inv.add_item(equipped) # default commands @Command def help(self,", "certain objects self.message(self.location.view()) @Command def say(self, args): \"\"\"Send a message to all players", "self.location = spawn_location self._parser = self._join_parser def despawn(self): \"\"\"method executed when a player", "in inventory.\") return # check for an already equipped weapon, unequip it if", "[] for name, cmd in self.cmd_dict.items(): try: sources[cmd.label].append(name) except KeyError: sources[cmd.label] = [name]", "remove_inv, if true, remove item from inventory # this avoids duplication if from_inv:", "be removed from inventory first. If item is not found in inventory, the", "= self.location new_location = found_exit.destination new_location.message(f\"{self} entered.\") self.set_location(new_location) # TODO: only show the", "return cmd = self.cmd_dict[cmd_name] cmd(args) def _dead_parser(self, line: str): \"\"\"Parser used when a", "precedence over the _classes. That is, if a WHITELIST includes the class Wizard,", "representation [filter_dict]\"\"\" return Filter(**filter_dict) def to_dict(self): \"\"\"returns a pythonic representation of this Filter\"\"\"", "return cmd return decorator class CharacterClass(type): \"\"\"metaclass establishing basic Character behaviors CharacterClasses include", "pick up.\") return item_name = \" \".join(args[1::]).lower() # TODO: find a way to", "tuple(newargs) keywords = self.keywords.copy() keywords.update(new_keywords) new_cmd = Command(self.func, *args, **keywords) # propagate the", "test to see if this character even has [target] # in its equip", "NOT in _classes are allowed through the filter. Note that _include_chars / _exclude_chars", "it first if isinstance(item, inv.ItemStack): self.inv.add_item(item.copy(), item.amount) self.inv.add_item(item, amt) def equip(self, item, from_inv=True):", "self.__doc__ = self.func.__doc__ # try to clean the docstring, if one was provided", "methods # TODO: override getattribute__ to solve the super() issue? if isinstance(getattr(self, cmd.func.__name__),", "parsing mode self._parser = self._command_parser def message(self, msg): \"\"\"send a message to the", "have at least 2 characters.\") return if not new_name.isalnum(): self.message(\"Names must be alphanumeric.\")", "# create a string representation of the equipped items equipped = [] for", "# method, we must manually bind the methods # TODO: override getattribute__ to", "= False WHITELIST = _FilterMode.WHITELIST BLACKLIST = _FilterMode.BLACKLIST def __init__(self, mode, classes=(), include_chars=(),", "from having the same name? self._name = new_name # move the player to", "traits [name] = to invoke this Command, the Character must use [name] instead", "= cmd.specify(self) # add command only if filter permits it if cmd.filter.permits(self): self.cmd_dict[name]", "CharacterClass): continue cls._commands.update(base._local_commands) cls._commands.update(cls._local_commands) # calling the super init super().__init__(name, bases, namespace) def", "whitelist if [mode] is False, the Filter will act as a blacklist [classes]", "1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item", "help menu.) [filter] = if provided, determine which Characters / Classes are permitted", "item from inventory # this avoids duplication if from_inv: try: self.inv.remove_item(item) # item", "in its equip slots try: if self.equip_dict[target] is None: self.message(f\"No item equipped on", "if other in self._include_chars: return True elif other in self._exclude_chars: return False #", "[mode] is True, the Filter will act as a whitelist if [mode] is", "for all in-game characters. This module also defines the 'Filter', used for CharacterClass-based", "will be labeled \"Default Commands\" command_label = \"Default Commands\" # Valid equip slots", "the (initial) keywords are equal\"\"\" try: return (self.func, self.args, self._keys) == \\ (other.func,", "state\"\"\" print(f\"[{self}] received update\") def spawn(self, spawn_location): \"\"\"Send a greeting to the character", "to players classname = \"Default Character\" # Starting location for this class starting_location", "\".join(args[1:]) # Manually iterating over our location's list of exits # Note! If", "except AttributeError: # location was none pass self.location = new_location self.location.add_char(self) # add", "if ex_name in ex.names: found_exit = ex break else: self.message(f\"No exit with name", "\"\\n\".join(output) # serialization-related methods @property def symbol(self): \"\"\"return a unique symbol for this", "base in reversed(cls.__mro__): if not isinstance(base, CharacterClass): continue cls._commands.update(base._local_commands) cls._commands.update(cls._local_commands) # calling the", "list(self._exclude_chars) return data class Command(functools.partial): \"\"\"A subclass of functools.partial that supports equality. The", "len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item) self.location.inv.add_item(item) elif len(found_items) > 1: #TODO", "any item at that position is unequipped [target]: an EquipTarget\"\"\" # test if", "\"\"\"periodically called method that updates character state\"\"\" print(f\"[{self}] received update\") def spawn(self, spawn_location):", "this Command, the Character must use [name] instead of the function's name [label]", "location was none pass self.location = new_location self.location.add_char(self) # add commands from all", "if self._name is None: return f\"{type(self).__name__}()\" return f\"{type(self).__name__}(name={self})\" def __str__(self): \"\"\"return the Character's", "items if inv_msg: self.message(inv_msg) @Command.with_traits(name=\"use\") def cmd_use(self, args): \"\"\" Use an item. usage:", "self.__name__ = self.func.__name__ self.__doc__ = self.func.__doc__ # try to clean the docstring, if", "even has [target] # in its equip slots try: if self.equip_dict[target] is None:", "keywords, so changing keywords after initialization is unsupported. \"\"\" def __init__(self, *args, **kwargs):", "can be invoked by characters. \"\"\" import enum import functools import inspect import", "prior argument, the prior argument will be overriden. \"\"\" args = self.args +", "bases, namespace) def __str__(cls): \"\"\"overriding str to return classname\"\"\" return cls.classname class Character(metaclass=CharacterClass):", "a blacklist [classes] are those classes to be whitelisted/blacklisted [include_chars] are specific characters", "# prevent them from getting garbage collected self._include_chars = weakref.WeakSet(include_chars) self._exclude_chars = weakref.WeakSet(exclude_chars)", "a whitelist if [mode] is False, the Filter will act as a blacklist", "two partially-applied functions have the same arguments and underlying functions. Optional fields, \"name\",", "Parses\"\"\" # command is always the first word args = line.split() cmd_name =", "item to equip.\") return item_name = \" \".join(args[1::]).lower() # search through the items", "return False # now try the Character's class other = type(other) if isinstance(other,", "set characters to be included _exclude_chars - set characters to be excluded _mode", "in self._classes: return self._mode.value # \"other\" is neither a CharClass nor Character else:", "to solve an undecidable problem, but just confirm that two partially-applied functions have", "if isinstance(mode, self._FilterMode): self._mode = mode elif isinstance(mode, bool): if mode: self._mode =", "to player's inventory\"\"\" # if the item is an ItemStack, unpack it first", "the filter _include_chars - set characters to be included _exclude_chars - set characters", "'{ex_name}' is inaccessible to you.\") # if the char can't see or interact", "is not None: cmd.filter = filter return cmd return decorator class CharacterClass(type): \"\"\"metaclass", "starting_location = None # Commands from this class will be labeled \"Default Commands\"", "f\"{cls} Commands\" # commands that were implemented for this class cls._local_commands = {}", "that were implemented for this class cls._local_commands = {} for value in namespace.values():", "should be in loc = self.location self.location = None self.set_location(loc) self._parser = self._command_parser", "note that a new filter is not created, so any changes to the", "cmd = self.cmd_dict[cmd_name] cmd(args) def _dead_parser(self, line: str): \"\"\"Parser used when a character", "methods def set_location(self, new_location): \"\"\"sets location, updating the previous and new locations as", "other in self._classes: self._classes.remove(other) elif isinstance(other, Character): if other in self._exclude_chars: self._exclude_chars.remove(other) self._include_chars.add(other)", "show the exit if a character can see it? old_location.message(f\"{self} left through exit", "= found_items[0][0] self.inv.remove_item(item) self.location.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item", "character even has [target] # in its equip slots try: if self.equip_dict[target] is", "to equip.\") return item_name = \" \".join(args[1::]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items)", "new_name.isalnum(): self.message(\"Names must be alphanumeric.\") return # TODO: perform some kind of check", "not None: return f\"{self} [from {self.label}]:\\n{self.__doc__}\" return f\"{self}:\\n{self.__doc__}\" @staticmethod def with_traits(name: str =", "< 2: self.message(\"Names must have at least 2 characters.\") return if not new_name.isalnum():", "\"\"\"return a pythonic representation of this Character\"\"\" return {\"_type\": type(self), \"name\": self._name} def", "\" and exclude\") for char in exclude_chars: if char in include_chars: raise ValueError(\"Cannot", "if item was from character's inventory, return it if from_inv: self.inv.add_item(equipped) # default", "self._symbol @classmethod def load(cls, data): name = data[\"name\"] if \"name\" in data else", "handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to", "attack self.location = spawn_location self._parser = self._join_parser def despawn(self): \"\"\"method executed when a", "or interact with the exit, # we lie to them and pretend like", "len(args) < 2: self.message(\"Provide an item to equip.\") return item_name = \" \".join(args[1::]).lower()", "used for CharacterClass-based permissions systems, and 'Command', a wrapper that converts methods into", "is not None: self.unequip(target) item.on_equip(self) item.add_cmds(self) self.equip_dict[item.target] = item, from_inv # class doesn't", "be included [exclude_chars] are specific characters to be excluded \"\"\" self._classes = set(classes)", "doing so. All comparisons are based on the INITIAL keywords, so changing keywords", "If item is not found in inventory, the command fails. if False, [item]", "__init__(cls, name, bases, namespace): # add the proper name, if not already provided", "players in your current location. usage: say [msg] \"\"\" msg = ' '.join(args[1:])", "name, bases, namespace): # add the proper name, if not already provided if", "cycle through each ancestor ancestors = filter(lambda x: isinstance(x, CharacterClass), other.__mro__) for char_class", "for selecting a valid name\"\"\" if len(new_name) < 2: self.message(\"Names must have at", "SwampyMud! You are a {type(self)}\") self.message(f\"What should we call you?\") # set player", "self._include_chars = weakref.WeakSet(include_chars) self._exclude_chars = weakref.WeakSet(exclude_chars) if isinstance(mode, self._FilterMode): self._mode = mode elif", "= [] while sources: source, names = sources.popitem() output.append(f\"---{source}---\") output.append(\" \".join(names)) return \"\\n\".join(output)", "None: return f\"A nameless {type(self)}\" return f\"{self._name} the {type(self)}\" #location manipulation methods def", "exclude_chars=()): \"\"\"initialize a Filter with [mode] if [mode] is True, the Filter will", "with name '{ex_name}'.\") @Command.with_traits(name=\"equip\") def cmd_equip(self, args): \"\"\"Equip an equippable item from your", "not cmd_name in self.cmd_dict: self.message(\"Command \\'%s\\' not recognized.\" % cmd_name) return cmd =", "def __str__(self): \"\"\"returns the name of this command if no name is provided,", "inspect import weakref import asyncio import swampymud.inventory as inv from swampymud import util", "your inventory. usage: inv\"\"\" # create a string representation of the equipped items", "inventory, the command fails. if False, [item] is not removed from inventory and", "wrapper that converts methods into commands that can be invoked by characters. \"\"\"", "will not be returned to inventory upon unequip. \"\"\" # duck test that", "in include_chars: raise ValueError(\"Cannot have character in both include\" \" and exclude\") #", "sources[cmd.label] = [name] # unpack the dictionary in reverse order output = []", "a representation of Character\"\"\" if self._name is None: return f\"{type(self).__name__}()\" return f\"{type(self).__name__}(name={self})\" def", "in the equip_dict found_items = [] for _, equip_data in self.equip_dict.items(): if equip_data", "\" received %s\" % type(other)) def exclude(self, other): \"\"\"Set the filter to return", "self._include_chars.remove(other) self._exclude_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" f\" received {type(other)}\") def __repr__(self): \"\"\"overriding repr()\"\"\"", "Commands collected by CharacterClass self.cmd_dict = ShadowDict() for (name, cmd) in self._commands.items(): cmd", "return {\"_type\": type(self), \"name\": self._name} def children(self): \"\"\"pass\"\"\" return [] #TODO: handle items", "item] Options may vary per item. \"\"\" # TODO: allow players to use", "save(self): \"\"\"return a pythonic representation of this Character\"\"\" return {\"_type\": type(self), \"name\": self._name}", "dict [item]: item to Equip [from_inv]: if True, [item] should be removed from", "[mode] if [mode] is True, the Filter will act as a whitelist if", "new_location.message(f\"{self} entered.\") self.set_location(new_location) # TODO: only show the exit if a character can", "the Character's class, then all the Character's ancestor classes \"\"\" if isinstance(other, Character):", "will new players spawn as this class - command_label: how commands from this", "weakref import asyncio import swampymud.inventory as inv from swampymud import util from swampymud.util.shadowdict", "Character's name\"\"\" if self._name: return self._name return \"[nameless character]\" def view(self): \"\"\"return a", "not recognized.\") @Command def look(self, args): \"\"\"Gives a description of your current location.", "same name? self._name = new_name # move the player to the actual location", "characters in a WeakSet, so that the Filter will not # prevent them", "list of exits # Note! If writing your own method, just do #", "try: self.inv.remove_item(item) # item not found except KeyError: self.message(f\"Cannot equip {item}-\" \"not found", "even equipped # also duck test to see if this character even has", "type(other)) def exclude(self, other): \"\"\"Set the filter to return 'False' if [other] is", "# util.find(location, ex_name, location.Exit, char=my_char) # I'm only writing this to avoid a", "for CharacterClass-based permissions systems, and 'Command', a wrapper that converts methods into commands", "the Character must use [name] instead of the function's name [label] = the", "None # Commands from this class will be labeled \"Default Commands\" command_label =", "self.args, self._keys) == \\ (other.func, other.args, other._keys) except AttributeError: # other is not", "the first word args = line.split() cmd_name = args[0] if not cmd_name in", "Use an item. usage: use [item] [options for item] Options may vary per", "they should be in loc = self.location self.location = None self.set_location(loc) self._parser =", "== \"blacklist\": self._mode = Filter.BLACKLIST else: raise ValueError(\"Unrecognized mode %s\" % repr(mode)) def", "# add a \"command_label\", if not already provided # this field is used", "= Filter.BLACKLIST else: if mode.lower() == \"whitelist\": self._mode = Filter.WHITELIST elif mode.lower() ==", "representation of this Character\"\"\" return {\"_type\": type(self), \"name\": self._name} def children(self): \"\"\"pass\"\"\" return", "create a string representation of the equipped items equipped = [] for target,", "self.message(f\"Could not find item '{item_name}' to use.\") # miscellaneous methods def help_menu(self) ->", "not MOVE them # thus, player will not be available to attack self.location", "the Character's class other = type(other) if isinstance(other, CharacterClass): # cycle through each", "not a Command return False def __hash__(self): \"\"\"overriding hash\"\"\" return hash((self.func, self.args, self._keys))", "get the list of CharacterClasses in order for cls in reversed(type(self).__mro__): if isinstance(cls,", "previous and new locations as necessary and gathering commands from any entities in", "= Filter.WHITELIST else: self._mode = Filter.BLACKLIST else: if mode.lower() == \"whitelist\": self._mode =", "equipped = [] for target, item in self.equip_dict.items(): if item is None: equipped.append(f\"{target}:", "return item_name = \" \".join(args[1::]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items) == 1:", "equipped # also duck test to see if this character even has [target]", "check to prevent players # from having the same name? self._name = new_name", "self._name is None: return f\"A nameless {type(self)}\" return f\"{self._name} the {type(self)}\" #location manipulation", "isinstance(other, CharacterClass): if self._mode is Filter.WHITELIST: self._classes.add(other) else: if other in self._classes: self._classes.remove(other)", "both include\" \" and exclude\") # store characters in a WeakSet, so that", "not bound properly like a normal # method, we must manually bind the", "{target}.\") return def unequip(self, target): \"\"\"updates this character's equip_dict such that the [target]", "item not found except KeyError: self.message(f\"Cannot equip {item}-\" \"not found in inventory.\") return", "self._include_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" \" received %s\" % type(other)) def exclude(self, other):", "else: self.message(f\"Could not find item '{item_name}' to pick up.\") @Command def drop(self, args):", "[name] instead of the function's name [label] = the type of the command.", "if self.location is not None: self.location.message(f\"{self} died.\", exclude={self}) try: self.location.characters.remove(self) except ValueError: pass", "new filter is not created, so any changes to the # old NewCommand", "self._classes: data[\"classes\"] = list(self._classes) if self._include_chars: data[\"include_chars\"] = list(self._include_chars) if self._exclude_chars: data[\"exclude_chars\"] =", "parse 'msg' using its current parser.\"\"\" if msg: self._parser(msg) def update(self): \"\"\"periodically called", "parser.\"\"\" if msg: self._parser(msg) def update(self): \"\"\"periodically called method that updates character state\"\"\"", "spawn_location, but do not MOVE them # thus, player will not be available", "slot '{target}'.\") return equipped, from_inv = self.equip_dict[target] equipped.on_unequip(self) equipped.remove_cmds(self) self.equip_dict[target] = None #", "inv.Inventory() self.equip_dict = inv.EquipTarget.make_dict(*self.equip_slots) # put character in default command parsing mode self._parser", "if BLACKLIST is selected, only characters whose class is NOT in _classes are", "Wizard is in _exclude_chars, Bill will not be permitted through the filter. \"\"\"", "the list of CharacterClasses in order for cls in reversed(type(self).__mro__): if isinstance(cls, CharacterClass):", "of the equipped items equipped = [] for target, item in self.equip_dict.items(): if", "args): \"\"\"Gives a description of your current location. usage: look \"\"\" # TODO:", "put character in default command parsing mode self._parser = self._command_parser def message(self, msg):", "has died\"\"\" self.message(\"You have died. Reconnect to this server to start\" \" as", "move the player to the actual location they should be in loc =", "Command): value.label = cls.command_label cls._local_commands[str(value)] = value # all commands, with the most", "be excluded _mode - Filter.WHITELIST or Filter.BLACKLIST if WHITELIST is selected, only characters", "def load(cls, data): name = data[\"name\"] if \"name\" in data else None return", "of CharacterClasses tracked by the filter _include_chars - set characters to be included", "methods def __repr__(self): \"\"\"return a representation of Character\"\"\" if self._name is None: return", "isinstance(getattr(self, cmd.func.__name__), Command): setattr(self, cmd.func.__name__, cmd) # set up inventory and equipping items", "None, label: str = None, filter: Filter = None): \"\"\"decorator to easily wrap", "self.location.inv.remove_item(item) self.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\")", "TODO: allow players to use accessible items in location? if len(args) < 2:", "Optional fields, \"name\", \"label\", and \"field\" are also provided. These fields store player-relevant", "in namespace: cls.classname = util.camel_to_space(name) # add a frequency field, if not already", "self.message(f\"Cannot equip item {item} to {target}.\") return def unequip(self, target): \"\"\"updates this character's", "an item to pick up.\") return item_name = \" \".join(args[1::]).lower() # TODO: find", "\"\"\" self.message(f\"Welcome to our SwampyMud! You are a {type(self)}\") self.message(f\"What should we call", "an EquipTarget\"\"\" # test if anything is even equipped # also duck test", "unequip [item]\"\"\" if len(args) < 2: self.message(\"Provide an item to equip.\") return item_name", "players to 'inspect' certain objects self.message(self.location.view()) @Command def say(self, args): \"\"\"Send a message", "and source new_cmd.name = self.name new_cmd.label = self.label # note that a new", "is in _exclude_chars, Bill will not be permitted through the filter. \"\"\" class", "to equip.\") return item_name = \" \".join(args[1::]).lower() # search through the items in", "str): \"\"\"Parser used when a character has died\"\"\" self.message(\"You have died. Reconnect to", "if [other] is supplied to permit()\"\"\" # check that other is a Character", "msg): \"\"\"send a message to the controller of this character\"\"\" # place a", "\"name\", \"label\", and \"field\" are also provided. These fields store player-relevant information that", "after a name is submitted. \"\"\" self.message(f\"Welcome to our SwampyMud! You are a", "equip slots try: if self.equip_dict[target] is None: self.message(f\"No item equipped on target {target}.\")", "in self._exclude_chars: self._exclude_chars.remove(other) self._include_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" \" received %s\" % type(other))", "of functools.partial that supports equality. The default implementation of functools.partial does not normally", "can see it? old_location.message(f\"{self} left through exit \" f\"'{ex_name}'.\") else: if found_exit.perceive.permits(self): self.message(f\"Exit", "if other in self._classes: self._classes.remove(other) else: self._classes.add(other) elif isinstance(other, Character): if other in", "command. \"\"\" def decorator(func): cmd = Command(func) cmd.name = name cmd.label = label", "util.find(location, ex_name, location.Exit, char=my_char) # I'm only writing this to avoid a cyclic", "def cmd_equip(self, args): \"\"\"Equip an equippable item from your inventory.\"\"\" if len(args) <", "Command, and visa versa new_cmd.filter = self.filter return new_cmd def __str__(self): \"\"\"returns the", "in include_chars: if char in exclude_chars: raise ValueError(\"Cannot have character in both include\"", "None: return self.func.__name__ return self.name def help_entry(self) -> str: \"\"\"return a help message", "ValueError(\"Expected Character/CharacterClass,\" f\" received {type(other)}\") def __repr__(self): \"\"\"overriding repr()\"\"\" return \"Filter({!r}, {!r}, {!r},", "self.inv.add_item(item.copy(), item.amount) self.inv.add_item(item, amt) def equip(self, item, from_inv=True): \"\"\"place [item] in this player's", "char=my_char) # I'm only writing this to avoid a cyclic dependency. for ex", "normal # method, we must manually bind the methods # TODO: override getattribute__", "all (empty blacklist) self.filter = Filter(Filter.BLACKLIST) def __eq__(self, other): \"\"\"Two commands are equal", "if False, [item] is not removed from inventory and will not be returned", "== 1: item = found_items[0][0] self.inv.remove_item(item) item.on_use(self, args[2:]) # replace the item self.inv.add_item(item)", "self._name return \"[nameless character]\" def view(self): \"\"\"return a longer, user-focused depiction of Character\"\"\"", "else: self.message(f\"Could not find item '{item_name}' to use.\") # miscellaneous methods def help_menu(self)", "= self.label # note that a new filter is not created, so any", "self.message(\"You have died. Reconnect to this server to start\" \" as a new", "elif isinstance(other, Character): if other in self._include_chars: self._include_chars.remove(other) self._exclude_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\"", "# build dict from Commands collected by CharacterClass self.cmd_dict = ShadowDict() for (name,", "the current locations for entity in new_location.entities: entity.on_enter(self) entity.add_cmds(self) #inventory/item related methods def", "character in both include\" \" and exclude\") for char in exclude_chars: if char", "was none pass self.location = new_location self.location.add_char(self) # add commands from all the", "and Character class, which serves as the basis for all in-game characters. This", "basic Character behaviors CharacterClasses include the following important attributes: - classname: how the", "f\"{self}:\\n{self.__doc__}\" @staticmethod def with_traits(name: str = None, label: str = None, filter: Filter", "= args[0] if not cmd_name in self.cmd_dict: self.message(\"Command \\'%s\\' not recognized.\" % cmd_name)", "this class's equality operators, we aren't trying to solve an undecidable problem, but", "other._keys) except AttributeError: # other is not a Command return False def __hash__(self):", "called method that updates character state\"\"\" print(f\"[{self}] received update\") def spawn(self, spawn_location): \"\"\"Send", "that updates character state\"\"\" print(f\"[{self}] received update\") def spawn(self, spawn_location): \"\"\"Send a greeting", "this to avoid a cyclic dependency. for ex in self.location._exit_list: if ex_name in", "class's equality operators, we aren't trying to solve an undecidable problem, but just", "accessible location. usage: go [exit name] \"\"\" ex_name = \" \".join(args[1:]) # Manually", "= {} # walk the mro, to get the list of CharacterClasses in", "cmd return decorator class CharacterClass(type): \"\"\"metaclass establishing basic Character behaviors CharacterClasses include the", "= self._dead_parser # default user-input parsers def _join_parser(self, new_name: str): \"\"\"Parser for a", "locations for entity in new_location.entities: entity.on_enter(self) entity.add_cmds(self) #inventory/item related methods def add_item(self, item,", "None: self.message(f\"No item equipped on target {target}.\") return except KeyError: self.message(f\"{type(self)} does not", "field, if not already provided if \"frequency\" not in namespace: cls.frequency = 1", "1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find equipped", "return cls.classname class Character(metaclass=CharacterClass): \"\"\"Base class for all other CharacterClasses\"\"\" # How this", "ex_name = \" \".join(args[1:]) # Manually iterating over our location's list of exits", "list of all commands is shown. \"\"\" if len(args) < 2: # TODO:", "the Character's name\"\"\" if self._name: return self._name return \"[nameless character]\" def view(self): \"\"\"return", "the equipped items equipped = [] for target, item in self.equip_dict.items(): if item", "from inventory # this avoids duplication if from_inv: try: self.inv.remove_item(item) # item not", "CharacterClasses tracked by the filter _include_chars - set characters to be included _exclude_chars", "= data[\"name\"] if \"name\" in data else None return cls(name) def post_load(self, data):", "self._classes: self._classes.remove(other) elif isinstance(other, Character): if other in self._exclude_chars: self._exclude_chars.remove(other) self._include_chars.add(other) else: raise", "self.func.__doc__ # try to clean the docstring, if one was provided try: self.__doc__", "# TODO: update to allow players to 'inspect' certain objects self.message(self.location.view()) @Command def", "\"\"\" def decorator(func): cmd = Command(func) cmd.name = name cmd.label = label if", "[item]\"\"\" if len(args) < 2: self.message(\"Provide an item to equip.\") return item_name =", "return (self.func, self.args, self._keys) == \\ (other.func, other.args, other._keys) except AttributeError: # other", "[spawn_location]: where the character should spawn after a name is submitted. \"\"\" self.message(f\"Welcome", "self._mode = Filter.WHITELIST else: self._mode = Filter.BLACKLIST else: if mode.lower() == \"whitelist\": self._mode", "view(self): \"\"\"return a longer, user-focused depiction of Character\"\"\" if self._name is None: return", "keywords after initialization is unsupported. \"\"\" def __init__(self, *args, **kwargs): \"\"\"initialize a Command", "are a {type(self)}\") self.message(f\"What should we call you?\") # set player location to", "[item] [options for item] Options may vary per item. \"\"\" # TODO: allow", "= _FilterMode.WHITELIST BLACKLIST = _FilterMode.BLACKLIST def __init__(self, mode, classes=(), include_chars=(), exclude_chars=()): \"\"\"initialize a", "isinstance(other, Character): if other in self._include_chars: return True elif other in self._exclude_chars: return", "# now try the Character's class other = type(other) if isinstance(other, CharacterClass): #", "not None: self.location.message(f\"{self} died.\", exclude={self}) try: self.location.characters.remove(self) except ValueError: pass self.location = None", "1: item = found_items[0][0] self.inv.remove_item(item) self.location.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity", "\"\"\"Base class for all other CharacterClasses\"\"\" # How this class appears to players", "raise ValueError(\"Expected Character/CharacterClass,\" \" received %s\" % type(other)) def exclude(self, other): \"\"\"Set the", "exit \" f\"'{ex_name}'.\") else: if found_exit.perceive.permits(self): self.message(f\"Exit '{ex_name}' is inaccessible to you.\") #", "except AttributeError: pass # initialize satellite data self.name = None self.label = None", "cmd = Command(func) cmd.name = name cmd.label = label if filter is not", "\"_symbol\"): symbol = \"{}#{}\".format(type(self).__name__, util.to_base(id(self), 62)) setattr(self, \"_symbol\", symbol) return self._symbol @classmethod def", "take precedence over the _classes. That is, if a WHITELIST includes the class", "target = item.target except AttributeError: self.message(f\"{item} cannot be equipped.\") return if target in", "namespace): # add the proper name, if not already provided if \"classname\" not", "permitted to use this command. \"\"\" def decorator(func): cmd = Command(func) cmd.name =", "character has died\"\"\" self.message(\"You have died. Reconnect to this server to start\" \"", "= f\"{cls} Commands\" # commands that were implemented for this class cls._local_commands =", "this avoids duplication if from_inv: try: self.inv.remove_item(item) # item not found except KeyError:", "/ CharacterClass if isinstance(other, CharacterClass): if self._mode == Filter.WHITELIST: if other in self._classes:", "function by applying additional arguments. If a provided keyword argument conflicts with a", "\"{}#{}\".format(type(self).__name__, util.to_base(id(self), 62)) setattr(self, \"_symbol\", symbol) return self._symbol @classmethod def load(cls, data): name", "is an ItemStack, unpack it first if isinstance(item, inv.ItemStack): self.inv.add_item(item.copy(), item.amount) self.inv.add_item(item, amt)", "-> str: \"\"\"return a help message for this command\"\"\" if self.label is not", "self._mode = Filter.BLACKLIST else: if mode.lower() == \"whitelist\": self._mode = Filter.WHITELIST elif mode.lower()", "if Character/CharacterClass is allowed in the individual Character is evaluated first, then the", "inventory and equipping items self.inv = inv.Inventory() self.equip_dict = inv.EquipTarget.make_dict(*self.equip_slots) # put character", "for _, equip_data in self.equip_dict.items(): if equip_data is None: continue item, _ =", "arguments. If a provided keyword argument conflicts with a prior argument, the prior", "args): \"\"\" Use an item. usage: use [item] [options for item] Options may", "new_name: str): \"\"\"Parser for a newly joined player, used for selecting a valid", "cmd(args) def _dead_parser(self, line: str): \"\"\"Parser used when a character has died\"\"\" self.message(\"You", "them from getting garbage collected self._include_chars = weakref.WeakSet(include_chars) self._exclude_chars = weakref.WeakSet(exclude_chars) if isinstance(mode,", "= [name] # unpack the dictionary in reverse order output = [] while", "equip.\") return item_name = \" \".join(args[1::]).lower() # search through the items in the", "and any item at that position is unequipped [target]: an EquipTarget\"\"\" # test", "are specific characters to be excluded \"\"\" self._classes = set(classes) for char in", "new_location = found_exit.destination new_location.message(f\"{self} entered.\") self.set_location(new_location) # TODO: only show the exit if", "# this field is used in creating help menus if \"command_label\" not in", "__repr__(self): \"\"\"overriding repr()\"\"\" return \"Filter({!r}, {!r}, {!r}, {!r})\".format( self._mode.value, set(self._classes), set(self._include_chars), set(self._exclude_chars) )", "in-game characters. This module also defines the 'Filter', used for CharacterClass-based permissions systems,", "\"\"\" if self.name is None: return self.func.__name__ return self.name def help_entry(self) -> str:", "not be available to attack self.location = spawn_location self._parser = self._join_parser def despawn(self):", "nameless {type(self)}\" return f\"{self._name} the {type(self)}\" #location manipulation methods def set_location(self, new_location): \"\"\"sets", "despawn(self): \"\"\"method executed when a player dies\"\"\" self.message(\"You died.\") if self.location is not", "on target {target}.\") return except KeyError: self.message(f\"{type(self)} does not possess\" f\" equip slot", "if the item is an ItemStack, unpack it first if isinstance(item, inv.ItemStack): self.inv.add_item(item.copy(),", "str: sources = {} # walk the mro, to get the list of", "label if filter is not None: cmd.filter = filter return cmd return decorator", "go(self, args): \"\"\"Go to an accessible location. usage: go [exit name] \"\"\" ex_name", "item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to use.\") # miscellaneous", "undecidable problem, but just confirm that two partially-applied functions have the same arguments", "[item] is not removed from inventory and will not be returned to inventory", "to inventory upon unequip. \"\"\" # duck test that the item is even", "inv.EquipTarget.make_dict(*self.equip_slots) # put character in default command parsing mode self._parser = self._command_parser def", "cannot be found in the list return not self._mode.value def include(self, other): \"\"\"Set", "serves as the basis for all in-game characters. This module also defines the", "other = type(other) if isinstance(other, CharacterClass): # cycle through each ancestor ancestors =", "character state\"\"\" print(f\"[{self}] received update\") def spawn(self, spawn_location): \"\"\"Send a greeting to the", "equipped weapon, unequip it if self.equip_dict[target] is not None: self.unequip(target) item.on_equip(self) item.add_cmds(self) self.equip_dict[item.target]", "<reponame>ufosc/MuddySwamp \"\"\"Module defining the CharacterClass metaclass and Character class, which serves as the", "self._symbol in the __init__ if not hasattr(self, \"_symbol\"): symbol = \"{}#{}\".format(type(self).__name__, util.to_base(id(self), 62))", "screening out certain CharacterClasses and Characters _classes - set of CharacterClasses tracked by", "this class equip_slots = [] def __init__(self, name=None): super().__init__() self._name = name self.location", "self.name = None self.label = None # by default, add a filter that", "to the character and put them into a name-selection mode. [spawn_location]: where the", "per item. \"\"\" # TODO: allow players to use accessible items in location?", "of check to prevent players # from having the same name? self._name =", "cls._commands.update(cls._local_commands) # calling the super init super().__init__(name, bases, namespace) def __str__(cls): \"\"\"overriding str", "str): \"\"\"The default parser for a player. Parses\"\"\" # command is always the", "= filter return cmd return decorator class CharacterClass(type): \"\"\"metaclass establishing basic Character behaviors", "exit, # we lie to them and pretend like it doesn't exist else:", "add a \"command_label\", if not already provided # this field is used in", "\"_symbol\", symbol) return self._symbol @classmethod def load(cls, data): name = data[\"name\"] if \"name\"", "-> 'Command': \"\"\"Derive a new version of this function by applying additional arguments.", "unpack it first if isinstance(item, inv.ItemStack): self.inv.add_item(item.copy(), item.amount) self.inv.add_item(item, amt) def equip(self, item,", "loc = self.location self.location = None self.set_location(loc) self._parser = self._command_parser def _command_parser(self, line:", "{type(self)}\" #location manipulation methods def set_location(self, new_location): \"\"\"sets location, updating the previous and", "class appears to the players - frequency: how often will new players spawn", "be overriden. \"\"\" args = self.args + tuple(newargs) keywords = self.keywords.copy() keywords.update(new_keywords) new_cmd", "\"\"\"Go to an accessible location. usage: go [exit name] \"\"\" ex_name = \"", "new_cmd.label = self.label # note that a new filter is not created, so", "for value in namespace.values(): if isinstance(value, Command): value.label = cls.command_label cls._local_commands[str(value)] = value", "will change to the old Command, and visa versa new_cmd.filter = self.filter return", "only if filter permits it if cmd.filter.permits(self): self.cmd_dict[name] = cmd # because sCommands", "invoked by characters. \"\"\" import enum import functools import inspect import weakref import", "of keywords for comparisons self._keys = frozenset(self.keywords.items()) # propagate the name and doc", "string-formatting methods def __repr__(self): \"\"\"return a representation of Character\"\"\" if self._name is None:", "\" as a new character.\") # string-formatting methods def __repr__(self): \"\"\"return a representation", "self.inv.add_item(equipped) # default commands @Command def help(self, args): \"\"\"Show relevant help information for", "self.location = None self.msgs = asyncio.Queue() # build dict from Commands collected by", "is always the first word args = line.split() cmd_name = args[0] if not", "Character/CharacterClass is allowed in the individual Character is evaluated first, then the Character's", "raise ValueError(\"Expected Character/CharacterClass,\" f\" received {type(other)}\") def __repr__(self): \"\"\"overriding repr()\"\"\" return \"Filter({!r}, {!r},", "is None: self.message(f\"No item equipped on target {target}.\") return except KeyError: self.message(f\"{type(self)} does", "2: self.message(\"Provide an item to pick up.\") return item_name = \" \".join(args[1::]).lower() #", "and \"field\" are also provided. These fields store player-relevant information that are NOT", "exclude\") for char in exclude_chars: if char in include_chars: raise ValueError(\"Cannot have character", "include(self, other): \"\"\"Set the filter to return 'True' if [other] is supplied to", "data[\"include_chars\"] = list(self._include_chars) if self._exclude_chars: data[\"exclude_chars\"] = list(self._exclude_chars) return data class Command(functools.partial): \"\"\"A", "= \" \".join(args[1:]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: item =", "bound properly like a normal # method, we must manually bind the methods", "\"\"\"return a longer, user-focused depiction of Character\"\"\" if self._name is None: return f\"A", "if [mode] is True, the Filter will act as a whitelist if [mode]", "\"\"\"return a unique symbol for this Character\"\"\" # failsafe to ensure that Character", "players spawn as this class - command_label: how commands from this class appear", "cls._local_commands = {} for value in namespace.values(): if isinstance(value, Command): value.label = cls.command_label", "is not None: return f\"{self} [from {self.label}]:\\n{self.__doc__}\" return f\"{self}:\\n{self.__doc__}\" @staticmethod def with_traits(name: str", "= equip_data if str(item).lower() == item_name: found_items.append(item) if len(found_items) == 1: self.unequip(found_items[0].target) elif", "\"\"\"returns True if Character/CharacterClass is allowed in the individual Character is evaluated first,", "of this character\"\"\" # place a self.msgs.put_nowait(msg) def command(self, msg): \"\"\"issue 'msg' to", "new_cmd = Command(self.func, *args, **keywords) # propagate the name and source new_cmd.name =", "self.help_menu() self.message(menu) else: name = args[1] try: self.message(self.cmd_dict[name].help_entry()) except KeyError: self.message(f\"Command '{name}' not", "failsafe to ensure that Character always has a symbol # even if someone", "def __init__(self, *args, **kwargs): \"\"\"initialize a Command like a functools.partial object\"\"\" super().__init__() #", "# even if someone forgets to set self._symbol in the __init__ if not", "not find item '{item_name}'.\") @Command.with_traits(name=\"unequip\") def cmd_unequip(self, args): \"\"\"Unequip an equipped item. Usage:", "= inv.Inventory() self.equip_dict = inv.EquipTarget.make_dict(*self.equip_slots) # put character in default command parsing mode", "see if this character even has [target] # in its equip slots try:", "used when a character has died\"\"\" self.message(\"You have died. Reconnect to this server", "for target, item in self.equip_dict.items(): if item is None: equipped.append(f\"{target}: none\") else: equipped.append(f\"{target}:", "new_cmd.filter = self.filter return new_cmd def __str__(self): \"\"\"returns the name of this command", "# commands that were implemented for this class cls._local_commands = {} for value", "BLACKLIST = False WHITELIST = _FilterMode.WHITELIST BLACKLIST = _FilterMode.BLACKLIST def __init__(self, mode, classes=(),", "walk the mro, to get the list of CharacterClasses in order for cls", "getattribute__ to solve the super() issue? if isinstance(getattr(self, cmd.func.__name__), Command): setattr(self, cmd.func.__name__, cmd)", "iff the base functions are equal, the args are equal, and the (initial)", "be found in the list return not self._mode.value def include(self, other): \"\"\"Set the", "if isinstance(other, CharacterClass): if self._mode is Filter.WHITELIST: self._classes.add(other) else: if other in self._classes:", "item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to pick up.\") @Command", "f\" equip slot '{target}'.\") return equipped, from_inv = self.equip_dict[target] equipped.on_unequip(self) equipped.remove_cmds(self) self.equip_dict[target] =", "at least 2 characters.\") return if not new_name.isalnum(): self.message(\"Names must be alphanumeric.\") return", "if other in self._include_chars: self._include_chars.remove(other) self._exclude_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" f\" received {type(other)}\")", "args = line.split() cmd_name = args[0] if not cmd_name in self.cmd_dict: self.message(\"Command \\'%s\\'", "Command(functools.partial): \"\"\"A subclass of functools.partial that supports equality. The default implementation of functools.partial", "Filter = None): \"\"\"decorator to easily wrap a function additional traits [name] =", "= ' '.join(args[1:]) if msg and self.location is not None: self.location.message(f\"{self.view()}: {msg}\") @Command", "ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}'.\") @Command.with_traits(name=\"unequip\") def", "not possess\" f\" equip slot '{target}'.\") return equipped, from_inv = self.equip_dict[target] equipped.on_unequip(self) equipped.remove_cmds(self)", "_FilterMode.WHITELIST BLACKLIST = _FilterMode.BLACKLIST def __init__(self, mode, classes=(), include_chars=(), exclude_chars=()): \"\"\"initialize a Filter", "include\" \" and exclude\") # store characters in a WeakSet, so that the", "are permitted to use this command. \"\"\" def decorator(func): cmd = Command(func) cmd.name", "inv_msg: self.message(inv_msg) @Command.with_traits(name=\"use\") def cmd_use(self, args): \"\"\" Use an item. usage: use [item]", "and put them into a name-selection mode. [spawn_location]: where the character should spawn", "ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to drop.\")", "call you?\") # set player location to spawn_location, but do not MOVE them", "pretend like it doesn't exist else: self.message(f\"No exit with name '{ex_name}'.\") @Command.with_traits(name=\"equip\") def", "how the class appears to the players - frequency: how often will new", "manually bind the methods # TODO: override getattribute__ to solve the super() issue?", "len(args) < 2: self.message(\"Provide an item to drop.\") return item_name = \" \".join(args[1:]).lower()", "These fields store player-relevant information that are NOT factored into comparisons. In addition,", "up inventory and equipping items self.inv = inv.Inventory() self.equip_dict = inv.EquipTarget.make_dict(*self.equip_slots) # put", "if True, [item] should be removed from inventory first. If item is not", "commands from all the entities # in the current location for entity in", "in self._classes: self._classes.remove(other) else: self._classes.add(other) elif isinstance(other, Character): if other in self._include_chars: self._include_chars.remove(other)", "Filter.WHITELIST: self._classes.add(other) else: if other in self._classes: self._classes.remove(other) elif isinstance(other, Character): if other", "supplied to permit()\"\"\" # check that other is a Character / CharacterClass if", "if this character even has [target] # in its equip slots try: if", "not in namespace: cls.frequency = 1 # add a \"command_label\", if not already", "#TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find equipped item", "base functions are equal, the args are equal, and the (initial) keywords are", "super init super().__init__(name, bases, namespace) def __str__(cls): \"\"\"overriding str to return classname\"\"\" return", "'{item_name}' to use.\") # miscellaneous methods def help_menu(self) -> str: sources = {}", "if target in self.equip_dict: # check remove_inv, if true, remove item from inventory", "CharacterClass metaclass and Character class, which serves as the basis for all in-game", "of functools.partial does not normally support equality for mathematically sound reasons: https://bugs.python.org/issue3564 With", "are specific characters to be included [exclude_chars] are specific characters to be excluded", "cls in reversed(type(self).__mro__): if isinstance(cls, CharacterClass): sources[cls.command_label] = [] for name, cmd in", "methods into commands that can be invoked by characters. \"\"\" import enum import", "upon unequip. \"\"\" # duck test that the item is even equippable try:", "\"other\" is neither a CharClass nor Character else: return False # the character", "inv\"\"\" # create a string representation of the equipped items equipped = []", "= \"Default Commands\" # Valid equip slots for characters of this class equip_slots", "if msg: self._parser(msg) def update(self): \"\"\"periodically called method that updates character state\"\"\" print(f\"[{self}]", "1: self.unequip(found_items[0].target) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\")", "into commands that can be invoked by characters. \"\"\" import enum import functools", "this class cls._local_commands = {} for value in namespace.values(): if isinstance(value, Command): value.label", "this character even has [target] # in its equip slots try: if self.equip_dict[target]", "symbol for this Character\"\"\" # failsafe to ensure that Character always has a", "only characters whose class is NOT in _classes are allowed through the filter.", "visa versa new_cmd.filter = self.filter return new_cmd def __str__(self): \"\"\"returns the name of", "with a prior argument, the prior argument will be overriden. \"\"\" args =", "player-relevant information that are NOT factored into comparisons. In addition, this class has", "class CharacterClass(type): \"\"\"metaclass establishing basic Character behaviors CharacterClasses include the following important attributes:", "Character): if other in self._exclude_chars: self._exclude_chars.remove(other) self._include_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" \" received", "return f\"{self} [from {self.label}]:\\n{self.__doc__}\" return f\"{self}:\\n{self.__doc__}\" @staticmethod def with_traits(name: str = None, label:", "self.location.message(f\"{self} died.\", exclude={self}) try: self.location.characters.remove(self) except ValueError: pass self.location = None self._parser =", "default parser for a player. Parses\"\"\" # command is always the first word", "is a Character / CharacterClass if isinstance(other, CharacterClass): if self._mode is Filter.WHITELIST: self._classes.add(other)", "inspect.cleandoc(self.__doc__) except AttributeError: pass # initialize satellite data self.name = None self.label =", "\"\"\" def __init__(cls, name, bases, namespace): # add the proper name, if not", "f\"A nameless {type(self)}\" return f\"{self._name} the {type(self)}\" #location manipulation methods def set_location(self, new_location):", "that _include_chars / _exclude_chars take precedence over the _classes. That is, if a", "in help menu \"\"\" def __init__(cls, name, bases, namespace): # add the proper", "self._classes.add(other) else: if other in self._classes: self._classes.remove(other) elif isinstance(other, Character): if other in", "update(self): \"\"\"periodically called method that updates character state\"\"\" print(f\"[{self}] received update\") def spawn(self,", "def help_menu(self) -> str: sources = {} # walk the mro, to get", "\"\"\"Pick up item from the environment.\"\"\" if len(args) < 2: self.message(\"Provide an item", "a pythonic representation of this Filter\"\"\" data = {\"mode\" : self._mode.value} if self._classes:", "which Characters / Classes are permitted to use this command. \"\"\" def decorator(func):", "this class - command_label: how commands from this class appear in help menu", "# store characters in a WeakSet, so that the Filter will not #", "def save(self): \"\"\"return a pythonic representation of this Character\"\"\" return {\"_type\": type(self), \"name\":", "# set player location to spawn_location, but do not MOVE them # thus,", "self.location is not None: self.location.message(f\"{self.view()}: {msg}\") @Command def go(self, args): \"\"\"Go to an", "# duck test that the item is even equippable try: target = item.target", "filter to return 'False' if [other] is supplied to permit()\"\"\" # check that", "= util.find(self.inv, name=item_name) if len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item) item.on_use(self, args[2:])", "\"\"\"Derive a new version of this function by applying additional arguments. If a", "cmd_name in self.cmd_dict: self.message(\"Command \\'%s\\' not recognized.\" % cmd_name) return cmd = self.cmd_dict[cmd_name]", "if cmd.filter.permits(self): self.cmd_dict[name] = cmd # because sCommands are not bound properly like", "will not be available to attack self.location = spawn_location self._parser = self._join_parser def", "ShadowDict class Filter: \"\"\"Filter for screening out certain CharacterClasses and Characters _classes -", "set(self._include_chars), set(self._exclude_chars) ) @staticmethod def from_dict(filter_dict): \"\"\"returns a Filter pythonic representation [filter_dict]\"\"\" return", "the Filter will not # prevent them from getting garbage collected self._include_chars =", "the docstring, if one was provided try: self.__doc__ = inspect.cleandoc(self.__doc__) except AttributeError: pass", "def symbol(self): \"\"\"return a unique symbol for this Character\"\"\" # failsafe to ensure", "provided, func.__name__ is used \"\"\" if self.name is None: return self.func.__name__ return self.name", "keywords = self.keywords.copy() keywords.update(new_keywords) new_cmd = Command(self.func, *args, **keywords) # propagate the name", "a pythonic representation of this Character\"\"\" return {\"_type\": type(self), \"name\": self._name} def children(self):", "to clean the docstring, if one was provided try: self.__doc__ = inspect.cleandoc(self.__doc__) except", "item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to drop.\") @Command.with_traits(name=\"inv\") def", "Filter will not # prevent them from getting garbage collected self._include_chars = weakref.WeakSet(include_chars)", "clean the docstring, if one was provided try: self.__doc__ = inspect.cleandoc(self.__doc__) except AttributeError:", "a newly joined player, used for selecting a valid name\"\"\" if len(new_name) <", "args[2:]) # replace the item self.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity", "mode. [spawn_location]: where the character should spawn after a name is submitted. \"\"\"", "item self.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\")", "to be included _exclude_chars - set characters to be excluded _mode - Filter.WHITELIST", "= {} for value in namespace.values(): if isinstance(value, Command): value.label = cls.command_label cls._local_commands[str(value)]", "even equippable try: target = item.target except AttributeError: self.message(f\"{item} cannot be equipped.\") return", "a cyclic dependency. for ex in self.location._exit_list: if ex_name in ex.names: found_exit =", "cls(name) def post_load(self, data): pass def save(self): \"\"\"return a pythonic representation of this", "self._classes.remove(other) else: self._classes.add(other) elif isinstance(other, Character): if other in self._include_chars: self._include_chars.remove(other) self._exclude_chars.add(other) else:", "gathering commands from any entities in the location \"\"\" try: self.location.characters.remove(self) # remove", "should spawn after a name is submitted. \"\"\" self.message(f\"Welcome to our SwampyMud! You", "must manually bind the methods # TODO: override getattribute__ to solve the super()", "def __repr__(self): \"\"\"return a representation of Character\"\"\" if self._name is None: return f\"{type(self).__name__}()\"", "util.find(self.location, name=item_name) if len(found_items) == 1: item = found_items[0][0] self.location.inv.remove_item(item) self.inv.add_item(item) elif len(found_items)", "from your inventory.\"\"\" if len(args) < 2: self.message(\"Provide an item to equip.\") return", "permit()\"\"\" # check that other is a Character / CharacterClass if isinstance(other, CharacterClass):", "return it if from_inv: self.inv.add_item(equipped) # default commands @Command def help(self, args): \"\"\"Show", "= self._command_parser def message(self, msg): \"\"\"send a message to the controller of this", "self.filter return new_cmd def __str__(self): \"\"\"returns the name of this command if no", "order output = [] while sources: source, names = sources.popitem() output.append(f\"---{source}---\") output.append(\" \".join(names))", "provided, determine which Characters / Classes are permitted to use this command. \"\"\"", "= inspect.cleandoc(self.__doc__) except AttributeError: pass # initialize satellite data self.name = None self.label", "will parse 'msg' using its current parser.\"\"\" if msg: self._parser(msg) def update(self): \"\"\"periodically", "Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to drop.\") @Command.with_traits(name=\"inv\") def cmd_inv(self, args):", "your own method, just do # util.find(location, ex_name, location.Exit, char=my_char) # I'm only", "self.unequip(target) item.on_equip(self) item.add_cmds(self) self.equip_dict[item.target] = item, from_inv # class doesn't have an equip", "len(found_items) == 1: item = found_items[0][0] self.location.inv.remove_item(item) self.inv.add_item(item) elif len(found_items) > 1: #TODO", "like a normal # method, we must manually bind the methods # TODO:", "characters to be excluded _mode - Filter.WHITELIST or Filter.BLACKLIST if WHITELIST is selected,", "creating an immutable set of keywords for comparisons self._keys = frozenset(self.keywords.items()) # propagate", "def _command_parser(self, line: str): \"\"\"The default parser for a player. Parses\"\"\" # command", "test that the item is even equippable try: target = item.target except AttributeError:", "- Filter.WHITELIST or Filter.BLACKLIST if WHITELIST is selected, only characters whose class is", "dies\"\"\" self.message(\"You died.\") if self.location is not None: self.location.message(f\"{self} died.\", exclude={self}) try: self.location.characters.remove(self)", "f\" received {type(other)}\") def __repr__(self): \"\"\"overriding repr()\"\"\" return \"Filter({!r}, {!r}, {!r}, {!r})\".format( self._mode.value,", "[msg] \"\"\" msg = ' '.join(args[1:]) if msg and self.location is not None:", "include_chars: raise ValueError(\"Cannot have character in both include\" \" and exclude\") # store", "False, the Filter will act as a blacklist [classes] are those classes to", "set of keywords for comparisons self._keys = frozenset(self.keywords.items()) # propagate the name and", "sources = {} # walk the mro, to get the list of CharacterClasses", "by simply adding additional arguments. All other information (base function, names, etc.) will", "item at that position is unequipped [target]: an EquipTarget\"\"\" # test if anything", "name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to drop.\") @Command.with_traits(name=\"inv\") def cmd_inv(self,", "conflicts with a prior argument, the prior argument will be overriden. \"\"\" args", "an existing one by simply adding additional arguments. All other information (base function,", "+ tuple(newargs) keywords = self.keywords.copy() keywords.update(new_keywords) new_cmd = Command(self.func, *args, **keywords) # propagate", "exit with name '{ex_name}'.\") @Command.with_traits(name=\"equip\") def cmd_equip(self, args): \"\"\"Equip an equippable item from", "def __init__(self, name=None): super().__init__() self._name = name self.location = None self.msgs = asyncio.Queue()", "look(self, args): \"\"\"Gives a description of your current location. usage: look \"\"\" #", "it? old_location.message(f\"{self} left through exit \" f\"'{ex_name}'.\") else: if found_exit.perceive.permits(self): self.message(f\"Exit '{ex_name}' is", "not find item '{item_name}' to drop.\") @Command.with_traits(name=\"inv\") def cmd_inv(self, args): \"\"\"Show your inventory.", "exclude(self, other): \"\"\"Set the filter to return 'False' if [other] is supplied to", "== 1: item = found_items[0][0] self.inv.remove_item(item) self.location.inv.add_item(item) elif len(found_items) > 1: #TODO handle", "exclude={self}) try: self.location.characters.remove(self) except ValueError: pass self.location = None self._parser = self._dead_parser #", "def cmd_unequip(self, args): \"\"\"Unequip an equipped item. Usage: unequip [item]\"\"\" if len(args) <", "this field is used in creating help menus if \"command_label\" not in namespace:", "self.args, self._keys)) def specify(self, *newargs, **new_keywords) -> 'Command': \"\"\"Derive a new version of", "return def unequip(self, target): \"\"\"updates this character's equip_dict such that the [target] is", "a name-selection mode. [spawn_location]: where the character should spawn after a name is", "a Filter with [mode] if [mode] is True, the Filter will act as", "item_name = args[1] found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: item =", "this class starting_location = None # Commands from this class will be labeled", "applying additional arguments. If a provided keyword argument conflicts with a prior argument,", "greeting to the character and put them into a name-selection mode. [spawn_location]: where", "even if someone forgets to set self._symbol in the __init__ if not hasattr(self,", "if self.name is None: return self.func.__name__ return self.name def help_entry(self) -> str: \"\"\"return", "bind the methods # TODO: override getattribute__ to solve the super() issue? if", "the Wizard is in _exclude_chars, Bill will not be permitted through the filter.", "that a new filter is not created, so any changes to the #", "None # by default, add a filter that permits all (empty blacklist) self.filter", "value # all commands, with the most recent commands exposed cls._commands = {}", "def cmd_use(self, args): \"\"\" Use an item. usage: use [item] [options for item]", "# add commands from all the entities # in the current locations for", "will act as a whitelist if [mode] is False, the Filter will act", "func.__name__ is used \"\"\" if self.name is None: return self.func.__name__ return self.name def", "location. usage: look \"\"\" # TODO: update to allow players to 'inspect' certain", "= ShadowDict() for (name, cmd) in self._commands.items(): cmd = cmd.specify(self) # add command", "super().__init__() self._name = name self.location = None self.msgs = asyncio.Queue() # build dict", "new_cmd.name = self.name new_cmd.label = self.label # note that a new filter is", "len(new_name) < 2: self.message(\"Names must have at least 2 characters.\") return if not", "if self._include_chars: data[\"include_chars\"] = list(self._include_chars) if self._exclude_chars: data[\"exclude_chars\"] = list(self._exclude_chars) return data class", "*newargs, **new_keywords) -> 'Command': \"\"\"Derive a new version of this function by applying", "if isinstance(value, Command): value.label = cls.command_label cls._local_commands[str(value)] = value # all commands, with", "\"\"\"issue 'msg' to character. character will parse 'msg' using its current parser.\"\"\" if", "= args[1] found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: item = found_items[0][0]", "systems, and 'Command', a wrapper that converts methods into commands that can be", "equip_slots = [] def __init__(self, name=None): super().__init__() self._name = name self.location = None", "return cls(name) def post_load(self, data): pass def save(self): \"\"\"return a pythonic representation of", "= set(classes) for char in include_chars: if char in exclude_chars: raise ValueError(\"Cannot have", "CharacterClass): if self._mode is Filter.WHITELIST: self._classes.add(other) else: if other in self._classes: self._classes.remove(other) elif", "= self.filter return new_cmd def __str__(self): \"\"\"returns the name of this command if", "filter return cmd return decorator class CharacterClass(type): \"\"\"metaclass establishing basic Character behaviors CharacterClasses", "item = found_items[0][0] self.inv.remove_item(item) item.on_use(self, args[2:]) # replace the item self.inv.add_item(item) elif len(found_items)", "location they should be in loc = self.location self.location = None self.set_location(loc) self._parser", "cmd_name = args[0] if not cmd_name in self.cmd_dict: self.message(\"Command \\'%s\\' not recognized.\" %", "if char in include_chars: raise ValueError(\"Cannot have character in both include\" \" and", "util.find(self.inv, name=item_name) if len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item) item.on_use(self, args[2:]) #", "died. Reconnect to this server to start\" \" as a new character.\") #", "else None return cls(name) def post_load(self, data): pass def save(self): \"\"\"return a pythonic", "def __repr__(self): \"\"\"overriding repr()\"\"\" return \"Filter({!r}, {!r}, {!r}, {!r})\".format( self._mode.value, set(self._classes), set(self._include_chars), set(self._exclude_chars)", "the name of this command if no name is provided, func.__name__ is used", "change to the old Command, and visa versa new_cmd.filter = self.filter return new_cmd", "can update Command.keywords, avoid doing so. All comparisons are based on the INITIAL", "**kwargs): \"\"\"initialize a Command like a functools.partial object\"\"\" super().__init__() # creating an immutable", "2: self.message(\"Provide an item to equip.\") return item_name = \" \".join(args[1::]).lower() found_items =", "= mode elif isinstance(mode, bool): if mode: self._mode = Filter.WHITELIST else: self._mode =", "cls._commands.update(base._local_commands) cls._commands.update(cls._local_commands) # calling the super init super().__init__(name, bases, namespace) def __str__(cls): \"\"\"overriding", "name = args[1] try: self.message(self.cmd_dict[name].help_entry()) except KeyError: self.message(f\"Command '{name}' not recognized.\") @Command def", "None: continue item, _ = equip_data if str(item).lower() == item_name: found_items.append(item) if len(found_items)", "try: sources[cmd.label].append(name) except KeyError: sources[cmd.label] = [name] # unpack the dictionary in reverse", "functools import inspect import weakref import asyncio import swampymud.inventory as inv from swampymud", "{type(self)}\") self.message(f\"What should we call you?\") # set player location to spawn_location, but", "of all commands is shown. \"\"\" if len(args) < 2: # TODO: cache", "2: self.message(\"Please specify an item.\") return item_name = args[1] found_items = util.find(self.inv, name=item_name)", "an equip target for this item, cannot equip else: self.message(f\"Cannot equip item {item}", "found_exit = ex break else: self.message(f\"No exit with name '{ex_name}'.\") return if found_exit.interact.permits(self):", "collected self._include_chars = weakref.WeakSet(include_chars) self._exclude_chars = weakref.WeakSet(exclude_chars) if isinstance(mode, self._FilterMode): self._mode = mode", "f\"{self._name} the {type(self)}\" #location manipulation methods def set_location(self, new_location): \"\"\"sets location, updating the", "{type(self)}\" return f\"{self._name} the {type(self)}\" #location manipulation methods def set_location(self, new_location): \"\"\"sets location,", "MOVE them # thus, player will not be available to attack self.location =", "If no command is supplied, a list of all commands is shown. \"\"\"", "def add_item(self, item, amt=1): \"\"\"add [item] to player's inventory\"\"\" # if the item", "your current location. usage: say [msg] \"\"\" msg = ' '.join(args[1:]) if msg", "except KeyError: self.message(f\"Cannot equip {item}-\" \"not found in inventory.\") return # check for", "object\"\"\" super().__init__() # creating an immutable set of keywords for comparisons self._keys =", "use this command. \"\"\" def decorator(func): cmd = Command(func) cmd.name = name cmd.label", "set characters to be excluded _mode - Filter.WHITELIST or Filter.BLACKLIST if WHITELIST is", "inventory upon unequip. \"\"\" # duck test that the item is even equippable", "new locations as necessary and gathering commands from any entities in the location", "has [target] # in its equip slots try: if self.equip_dict[target] is None: self.message(f\"No", "its current parser.\"\"\" if msg: self._parser(msg) def update(self): \"\"\"periodically called method that updates", "== 1: self.unequip(found_items[0].target) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name.", "have character in both include\" \" and exclude\") for char in exclude_chars: if", "least 2 characters.\") return if not new_name.isalnum(): self.message(\"Names must be alphanumeric.\") return #", "player dies\"\"\" self.message(\"You died.\") if self.location is not None: self.location.message(f\"{self} died.\", exclude={self}) try:", "exit with name '{ex_name}'.\") return if found_exit.interact.permits(self): old_location = self.location new_location = found_exit.destination", "of this class equip_slots = [] def __init__(self, name=None): super().__init__() self._name = name", "[include_chars] are specific characters to be included [exclude_chars] are specific characters to be", "items equipped = [] for target, item in self.equip_dict.items(): if item is None:", "try the Character's class other = type(other) if isinstance(other, CharacterClass): # cycle through", "whitelisted/blacklisted [include_chars] are specific characters to be included [exclude_chars] are specific characters to", "self.equip(found_items[0][0]) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else:", "pickup(self, args): \"\"\"Pick up item from the environment.\"\"\" if len(args) < 2: self.message(\"Provide", "\"\"\"metaclass establishing basic Character behaviors CharacterClasses include the following important attributes: - classname:", "properly like a normal # method, we must manually bind the methods #", "# failsafe to ensure that Character always has a symbol # even if", "bool): if mode: self._mode = Filter.WHITELIST else: self._mode = Filter.BLACKLIST else: if mode.lower()", "util.find(self.inv, name=item_name) if len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item) self.location.inv.add_item(item) elif len(found_items)", "\"\"\"overriding hash\"\"\" return hash((self.func, self.args, self._keys)) def specify(self, *newargs, **new_keywords) -> 'Command': \"\"\"Derive", "that the Filter will not # prevent them from getting garbage collected self._include_chars", "[label] = the type of the command. (Affects help menu.) [filter] = if", "#inventory/item related methods def add_item(self, item, amt=1): \"\"\"add [item] to player's inventory\"\"\" #", "cmd_equip(self, args): \"\"\"Equip an equippable item from your inventory.\"\"\" if len(args) < 2:", "ancestors: if char_class in self._classes: return self._mode.value # \"other\" is neither a CharClass", "new version of this function by applying additional arguments. If a provided keyword", "act as a whitelist if [mode] is False, the Filter will act as", "# other is not a Command return False def __hash__(self): \"\"\"overriding hash\"\"\" return", "in creating help menus if \"command_label\" not in namespace: cls.command_label = f\"{cls} Commands\"", "method that updates character state\"\"\" print(f\"[{self}] received update\") def spawn(self, spawn_location): \"\"\"Send a", "the prior argument will be overriden. \"\"\" args = self.args + tuple(newargs) keywords", "neither a CharClass nor Character else: return False # the character / ancestors", "functools.partial that supports equality. The default implementation of functools.partial does not normally support", "initialization is unsupported. \"\"\" def __init__(self, *args, **kwargs): \"\"\"initialize a Command like a", "do # util.find(location, ex_name, location.Exit, char=my_char) # I'm only writing this to avoid", "ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find equipped item '{item_name}'.\") @Command", "names, etc.) will be propagated. While you can update Command.keywords, avoid doing so.", "\"Default Character\" # Starting location for this class starting_location = None # Commands", "self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to drop.\") @Command.with_traits(name=\"inv\")", "will not # prevent them from getting garbage collected self._include_chars = weakref.WeakSet(include_chars) self._exclude_chars", "this command if no name is provided, func.__name__ is used \"\"\" if self.name", "if len(args) < 2: self.message(\"Provide an item to equip.\") return item_name = \"", "is selected, only characters whose class is in _classes are allowed through the", "= _FilterMode.BLACKLIST def __init__(self, mode, classes=(), include_chars=(), exclude_chars=()): \"\"\"initialize a Filter with [mode]", "def _dead_parser(self, line: str): \"\"\"Parser used when a character has died\"\"\" self.message(\"You have", "a new version of this function by applying additional arguments. If a provided", "and visa versa new_cmd.filter = self.filter return new_cmd def __str__(self): \"\"\"returns the name", "to this server to start\" \" as a new character.\") # string-formatting methods", "equal iff the base functions are equal, the args are equal, and the", "{!r})\".format( self._mode.value, set(self._classes), set(self._include_chars), set(self._exclude_chars) ) @staticmethod def from_dict(filter_dict): \"\"\"returns a Filter pythonic", "individual Character is evaluated first, then the Character's class, then all the Character's", "as necessary and gathering commands from any entities in the location \"\"\" try:", "no command is supplied, a list of all commands is shown. \"\"\" if", "return if found_exit.interact.permits(self): old_location = self.location new_location = found_exit.destination new_location.message(f\"{self} entered.\") self.set_location(new_location) #", "changes to the # old NewCommand will change to the old Command, and", "cmd = cmd.specify(self) # add command only if filter permits it if cmd.filter.permits(self):", "word args = line.split() cmd_name = args[0] if not cmd_name in self.cmd_dict: self.message(\"Command", "self._include_chars: self._include_chars.remove(other) self._exclude_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" f\" received {type(other)}\") def __repr__(self): \"\"\"overriding", "a greeting to the character and put them into a name-selection mode. [spawn_location]:", "filter. \"\"\" class _FilterMode(enum.Enum): \"\"\"Enum representing whether a filter includes or excludes the", "isinstance(other, CharacterClass): if self._mode == Filter.WHITELIST: if other in self._classes: self._classes.remove(other) else: self._classes.add(other)", "if filter permits it if cmd.filter.permits(self): self.cmd_dict[name] = cmd # because sCommands are", "allowed through the filter. if BLACKLIST is selected, only characters whose class is", "item is not found in inventory, the command fails. if False, [item] is", "asyncio.Queue() # build dict from Commands collected by CharacterClass self.cmd_dict = ShadowDict() for", "an ItemStack, unpack it first if isinstance(item, inv.ItemStack): self.inv.add_item(item.copy(), item.amount) self.inv.add_item(item, amt) def", "load(cls, data): name = data[\"name\"] if \"name\" in data else None return cls(name)", "# by default, add a filter that permits all (empty blacklist) self.filter =", "a {type(self)}\") self.message(f\"What should we call you?\") # set player location to spawn_location,", "post_load(self, data): pass def save(self): \"\"\"return a pythonic representation of this Character\"\"\" return", "existing one by simply adding additional arguments. All other information (base function, names,", "the super() issue? if isinstance(getattr(self, cmd.func.__name__), Command): setattr(self, cmd.func.__name__, cmd) # set up", "self._classes.remove(other) elif isinstance(other, Character): if other in self._exclude_chars: self._exclude_chars.remove(other) self._include_chars.add(other) else: raise ValueError(\"Expected", "and Characters _classes - set of CharacterClasses tracked by the filter _include_chars -", "self._dead_parser # default user-input parsers def _join_parser(self, new_name: str): \"\"\"Parser for a newly", "\"\"\"Two commands are equal iff the base functions are equal, the args are", "included [exclude_chars] are specific characters to be excluded \"\"\" self._classes = set(classes) for", "for this class starting_location = None # Commands from this class will be", "CharacterClasses include the following important attributes: - classname: how the class appears to", "underlying functions. Optional fields, \"name\", \"label\", and \"field\" are also provided. These fields", "be included _exclude_chars - set characters to be excluded _mode - Filter.WHITELIST or", "characters of this class equip_slots = [] def __init__(self, name=None): super().__init__() self._name =", "= label if filter is not None: cmd.filter = filter return cmd return", "check that other is a Character / CharacterClass if isinstance(other, CharacterClass): if self._mode", "class Wizard, but Bill the Wizard is in _exclude_chars, Bill will not be", "# place a self.msgs.put_nowait(msg) def command(self, msg): \"\"\"issue 'msg' to character. character will", "help_menu(self) -> str: sources = {} # walk the mro, to get the", "self._mode.value # \"other\" is neither a CharClass nor Character else: return False #", "# this avoids duplication if from_inv: try: self.inv.remove_item(item) # item not found except", "iterating over our location's list of exits # Note! If writing your own", "filter is not None: cmd.filter = filter return cmd return decorator class CharacterClass(type):", "Character's class other = type(other) if isinstance(other, CharacterClass): # cycle through each ancestor", "in self.location.entities: entity.on_exit(self) entity.remove_cmds(self) except AttributeError: # location was none pass self.location =", "versa new_cmd.filter = self.filter return new_cmd def __str__(self): \"\"\"returns the name of this", "try: self.location.characters.remove(self) except ValueError: pass self.location = None self._parser = self._dead_parser # default", "functions. Optional fields, \"name\", \"label\", and \"field\" are also provided. These fields store", "are equal\"\"\" try: return (self.func, self.args, self._keys) == \\ (other.func, other.args, other._keys) except", "provided if \"frequency\" not in namespace: cls.frequency = 1 # add a \"command_label\",", "in namespace: cls.command_label = f\"{cls} Commands\" # commands that were implemented for this", "first if isinstance(item, inv.ItemStack): self.inv.add_item(item.copy(), item.amount) self.inv.add_item(item, amt) def equip(self, item, from_inv=True): \"\"\"place", "Filter pythonic representation [filter_dict]\"\"\" return Filter(**filter_dict) def to_dict(self): \"\"\"returns a pythonic representation of", "[name] # unpack the dictionary in reverse order output = [] while sources:", "item, from_inv # class doesn't have an equip target for this item, cannot", "self._parser(msg) def update(self): \"\"\"periodically called method that updates character state\"\"\" print(f\"[{self}] received update\")", "{self.label}]:\\n{self.__doc__}\" return f\"{self}:\\n{self.__doc__}\" @staticmethod def with_traits(name: str = None, label: str = None,", "= None self.set_location(loc) self._parser = self._command_parser def _command_parser(self, line: str): \"\"\"The default parser", "symbol # even if someone forgets to set self._symbol in the __init__ if", "# if the item is an ItemStack, unpack it first if isinstance(item, inv.ItemStack):", "\"\"\"Send a greeting to the character and put them into a name-selection mode.", "allow players to 'inspect' certain objects self.message(self.location.view()) @Command def say(self, args): \"\"\"Send a", "class doesn't have an equip target for this item, cannot equip else: self.message(f\"Cannot", "None and any item at that position is unequipped [target]: an EquipTarget\"\"\" #", "\"Default Commands\" command_label = \"Default Commands\" # Valid equip slots for characters of", "# miscellaneous methods def help_menu(self) -> str: sources = {} # walk the", "Filter(**filter_dict) def to_dict(self): \"\"\"returns a pythonic representation of this Filter\"\"\" data = {\"mode\"", "a function additional traits [name] = to invoke this Command, the Character must", "character can see it? old_location.message(f\"{self} left through exit \" f\"'{ex_name}'.\") else: if found_exit.perceive.permits(self):", "self._join_parser def despawn(self): \"\"\"method executed when a player dies\"\"\" self.message(\"You died.\") if self.location", "additional traits [name] = to invoke this Command, the Character must use [name]", "new_location.entities: entity.on_enter(self) entity.add_cmds(self) #inventory/item related methods def add_item(self, item, amt=1): \"\"\"add [item] to", "\"not found in inventory.\") return # check for an already equipped weapon, unequip", "self.inv.remove_item(item) item.on_use(self, args[2:]) # replace the item self.inv.add_item(item) elif len(found_items) > 1: #TODO", "the Filter will act as a whitelist if [mode] is False, the Filter", "self.equip_dict[target] = None # if item was from character's inventory, return it if", "the same arguments and underlying functions. Optional fields, \"name\", \"label\", and \"field\" are", "Character is evaluated first, then the Character's class, then all the Character's ancestor", "TODO: only show the exit if a character can see it? old_location.message(f\"{self} left", "other.args, other._keys) except AttributeError: # other is not a Command return False def", "\"\"\"Set the filter to return 'False' if [other] is supplied to permit()\"\"\" #", "from_inv: self.inv.add_item(equipped) # default commands @Command def help(self, args): \"\"\"Show relevant help information", "a frequency field, if not already provided if \"frequency\" not in namespace: cls.frequency", "of the command. (Affects help menu.) [filter] = if provided, determine which Characters", "len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item) item.on_use(self, args[2:]) # replace the item", "Character\"\"\" # failsafe to ensure that Character always has a symbol # even", "except KeyError: sources[cmd.label] = [name] # unpack the dictionary in reverse order output", "None: self.location.message(f\"{self} died.\", exclude={self}) try: self.location.characters.remove(self) except ValueError: pass self.location = None self._parser", "accessible items in location? if len(args) < 2: self.message(\"Please specify an item.\") return", "up.\") return item_name = \" \".join(args[1::]).lower() # TODO: find a way to provide", "cmd.label = label if filter is not None: cmd.filter = filter return cmd", "continue item, _ = equip_data if str(item).lower() == item_name: found_items.append(item) if len(found_items) ==", "is None: return self.func.__name__ return self.name def help_entry(self) -> str: \"\"\"return a help", "enum import functools import inspect import weakref import asyncio import swampymud.inventory as inv", "return hash((self.func, self.args, self._keys)) def specify(self, *newargs, **new_keywords) -> 'Command': \"\"\"Derive a new", "must use [name] instead of the function's name [label] = the type of", "return self._name return \"[nameless character]\" def view(self): \"\"\"return a longer, user-focused depiction of", "the exit if a character can see it? old_location.message(f\"{self} left through exit \"", "say [msg] \"\"\" msg = ' '.join(args[1:]) if msg and self.location is not", "for char_class in ancestors: if char_class in self._classes: return self._mode.value # \"other\" is", "this class has a convenience method, '.specify' to derive a new Command from", "check remove_inv, if true, remove item from inventory # this avoids duplication if", "= new_name # move the player to the actual location they should be", "certain CharacterClasses and Characters _classes - set of CharacterClasses tracked by the filter", "\"blacklist\": self._mode = Filter.BLACKLIST else: raise ValueError(\"Unrecognized mode %s\" % repr(mode)) def permits(self,", "location's list of exits # Note! If writing your own method, just do", "for a newly joined player, used for selecting a valid name\"\"\" if len(new_name)", "CharacterClass), other.__mro__) for char_class in ancestors: if char_class in self._classes: return self._mode.value #", "self._command_parser def _command_parser(self, line: str): \"\"\"The default parser for a player. Parses\"\"\" #", "self.location = new_location self.location.add_char(self) # add commands from all the entities # in", "else: self.message(f\"Could not find item '{item_name}'.\") @Command.with_traits(name=\"unequip\") def cmd_unequip(self, args): \"\"\"Unequip an equipped", "from inventory and will not be returned to inventory upon unequip. \"\"\" #", "is supplied, a list of all commands is shown. \"\"\" if len(args) <", "# item not found except KeyError: self.message(f\"Cannot equip {item}-\" \"not found in inventory.\")", "if self._mode == Filter.WHITELIST: if other in self._classes: self._classes.remove(other) else: self._classes.add(other) elif isinstance(other,", "will be overriden. \"\"\" args = self.args + tuple(newargs) keywords = self.keywords.copy() keywords.update(new_keywords)", "received {type(other)}\") def __repr__(self): \"\"\"overriding repr()\"\"\" return \"Filter({!r}, {!r}, {!r}, {!r})\".format( self._mode.value, set(self._classes),", "_ = equip_data if str(item).lower() == item_name: found_items.append(item) if len(found_items) == 1: self.unequip(found_items[0].target)", "args[1] try: self.message(self.cmd_dict[name].help_entry()) except KeyError: self.message(f\"Command '{name}' not recognized.\") @Command def look(self, args):", "# initialize satellite data self.name = None self.label = None # by default,", "if anything is even equipped # also duck test to see if this", "== 1: self.equip(found_items[0][0]) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name.", "# in the current location for entity in self.location.entities: entity.on_exit(self) entity.remove_cmds(self) except AttributeError:", "cmd) # set up inventory and equipping items self.inv = inv.Inventory() self.equip_dict =", "filter. if BLACKLIST is selected, only characters whose class is NOT in _classes", "through exit \" f\"'{ex_name}'.\") else: if found_exit.perceive.permits(self): self.message(f\"Exit '{ex_name}' is inaccessible to you.\")", "in self.equip_dict: # check remove_inv, if true, remove item from inventory # this", "target): \"\"\"updates this character's equip_dict such that the [target] is set to None", "found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item) self.location.inv.add_item(item)", "\"\"\"send a message to the controller of this character\"\"\" # place a self.msgs.put_nowait(msg)", "for screening out certain CharacterClasses and Characters _classes - set of CharacterClasses tracked", "only show the exit if a character can see it? old_location.message(f\"{self} left through", "found_items.append(item) if len(found_items) == 1: self.unequip(found_items[0].target) elif len(found_items) > 1: #TODO handle ambiguity", "are equal, the args are equal, and the (initial) keywords are equal\"\"\" try:", "self._include_chars: data[\"include_chars\"] = list(self._include_chars) if self._exclude_chars: data[\"exclude_chars\"] = list(self._exclude_chars) return data class Command(functools.partial):", "objects self.message(self.location.view()) @Command def say(self, args): \"\"\"Send a message to all players in", "= args[1] try: self.message(self.cmd_dict[name].help_entry()) except KeyError: self.message(f\"Command '{name}' not recognized.\") @Command def look(self,", "own method, just do # util.find(location, ex_name, location.Exit, char=my_char) # I'm only writing", "to drop.\") return item_name = \" \".join(args[1:]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items)", "for characters of this class equip_slots = [] def __init__(self, name=None): super().__init__() self._name", "'{item_name}' to drop.\") @Command.with_traits(name=\"inv\") def cmd_inv(self, args): \"\"\"Show your inventory. usage: inv\"\"\" #", "Characters _classes - set of CharacterClasses tracked by the filter _include_chars - set", "cls.command_label = f\"{cls} Commands\" # commands that were implemented for this class cls._local_commands", "submitted. \"\"\" self.message(f\"Welcome to our SwampyMud! You are a {type(self)}\") self.message(f\"What should we", "\"\"\"Parser used when a character has died\"\"\" self.message(\"You have died. Reconnect to this", "\" \".join(args[1::]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: self.equip(found_items[0][0]) elif len(found_items)", "for a particular command. usage: help [command] If no command is supplied, a", "instead of the function's name [label] = the type of the command. (Affects", "break else: self.message(f\"No exit with name '{ex_name}'.\") return if found_exit.interact.permits(self): old_location = self.location", "also duck test to see if this character even has [target] # in", "equip {item}-\" \"not found in inventory.\") return # check for an already equipped", "equipping items self.inv = inv.Inventory() self.equip_dict = inv.EquipTarget.make_dict(*self.equip_slots) # put character in default", "# propagate the name and doc from the base function self.__name__ = self.func.__name__", "other.__mro__) for char_class in ancestors: if char_class in self._classes: return self._mode.value # \"other\"", "frequency field, if not already provided if \"frequency\" not in namespace: cls.frequency =", "if len(new_name) < 2: self.message(\"Names must have at least 2 characters.\") return if", "{target}.\") return except KeyError: self.message(f\"{type(self)} does not possess\" f\" equip slot '{target}'.\") return", "unpack the dictionary in reverse order output = [] while sources: source, names", "output.append(\" \".join(names)) return \"\\n\".join(output) # serialization-related methods @property def symbol(self): \"\"\"return a unique", "args[1] found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item)", "not recognized.\" % cmd_name) return cmd = self.cmd_dict[cmd_name] cmd(args) def _dead_parser(self, line: str):", "not self._mode.value def include(self, other): \"\"\"Set the filter to return 'True' if [other]", "self.message(self.location.view()) @Command def say(self, args): \"\"\"Send a message to all players in your", "self._exclude_chars: data[\"exclude_chars\"] = list(self._exclude_chars) return data class Command(functools.partial): \"\"\"A subclass of functools.partial that", "import weakref import asyncio import swampymud.inventory as inv from swampymud import util from", "it if cmd.filter.permits(self): self.cmd_dict[name] = cmd # because sCommands are not bound properly", "not in namespace: cls.classname = util.camel_to_space(name) # add a frequency field, if not", "equal, and the (initial) keywords are equal\"\"\" try: return (self.func, self.args, self._keys) ==", "\" \".join(args[1:]) # Manually iterating over our location's list of exits # Note!", "cls.classname = util.camel_to_space(name) # add a frequency field, if not already provided if", "if found_exit.interact.permits(self): old_location = self.location new_location = found_exit.destination new_location.message(f\"{self} entered.\") self.set_location(new_location) # TODO:", "character]\" def view(self): \"\"\"return a longer, user-focused depiction of Character\"\"\" if self._name is", "inventory.\") return # check for an already equipped weapon, unequip it if self.equip_dict[target]", "swampymud.util.shadowdict import ShadowDict class Filter: \"\"\"Filter for screening out certain CharacterClasses and Characters", "will act as a blacklist [classes] are those classes to be whitelisted/blacklisted [include_chars]", "item {item} to {target}.\") return def unequip(self, target): \"\"\"updates this character's equip_dict such", "sources.popitem() output.append(f\"---{source}---\") output.append(\" \".join(names)) return \"\\n\".join(output) # serialization-related methods @property def symbol(self): \"\"\"return", "@Command.with_traits(name=\"unequip\") def cmd_unequip(self, args): \"\"\"Unequip an equipped item. Usage: unequip [item]\"\"\" if len(args)", "Starting location for this class starting_location = None # Commands from this class", "is inaccessible to you.\") # if the char can't see or interact with", "{!r}, {!r}, {!r})\".format( self._mode.value, set(self._classes), set(self._include_chars), set(self._exclude_chars) ) @staticmethod def from_dict(filter_dict): \"\"\"returns a", "if char in exclude_chars: raise ValueError(\"Cannot have character in both include\" \" and", "creating help menus if \"command_label\" not in namespace: cls.command_label = f\"{cls} Commands\" #", "is used \"\"\" if self.name is None: return self.func.__name__ return self.name def help_entry(self)", "new_name # move the player to the actual location they should be in", "entered.\") self.set_location(new_location) # TODO: only show the exit if a character can see", "name, if not already provided if \"classname\" not in namespace: cls.classname = util.camel_to_space(name)", "None: cmd.filter = filter return cmd return decorator class CharacterClass(type): \"\"\"metaclass establishing basic", "solve the super() issue? if isinstance(getattr(self, cmd.func.__name__), Command): setattr(self, cmd.func.__name__, cmd) # set", "an item to equip.\") return item_name = \" \".join(args[1::]).lower() # search through the", "in the __init__ if not hasattr(self, \"_symbol\"): symbol = \"{}#{}\".format(type(self).__name__, util.to_base(id(self), 62)) setattr(self,", "a Character / CharacterClass if isinstance(other, CharacterClass): if self._mode == Filter.WHITELIST: if other", "self._mode = mode elif isinstance(mode, bool): if mode: self._mode = Filter.WHITELIST else: self._mode", "If writing your own method, just do # util.find(location, ex_name, location.Exit, char=my_char) #", "if len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item) self.location.inv.add_item(item) elif len(found_items) > 1:", "Reconnect to this server to start\" \" as a new character.\") # string-formatting", "is not None: self.location.message(f\"{self.view()}: {msg}\") @Command def go(self, args): \"\"\"Go to an accessible", "ancestors = filter(lambda x: isinstance(x, CharacterClass), other.__mro__) for char_class in ancestors: if char_class", "if len(args) < 2: self.message(\"Please specify an item.\") return item_name = args[1] found_items", "EquipTarget\"\"\" # test if anything is even equipped # also duck test to", "is, if a WHITELIST includes the class Wizard, but Bill the Wizard is", "**keywords) # propagate the name and source new_cmd.name = self.name new_cmd.label = self.label", "so. All comparisons are based on the INITIAL keywords, so changing keywords after", "fails. if False, [item] is not removed from inventory and will not be", "in the location \"\"\" try: self.location.characters.remove(self) # remove commands from all the entities", "if not cmd_name in self.cmd_dict: self.message(\"Command \\'%s\\' not recognized.\" % cmd_name) return cmd", "but Bill the Wizard is in _exclude_chars, Bill will not be permitted through", "them and pretend like it doesn't exist else: self.message(f\"No exit with name '{ex_name}'.\")", "CharacterClasses in order for cls in reversed(type(self).__mro__): if isinstance(cls, CharacterClass): sources[cls.command_label] = []", "exit if a character can see it? old_location.message(f\"{self} left through exit \" f\"'{ex_name}'.\")", "@Command def look(self, args): \"\"\"Gives a description of your current location. usage: look", "def pickup(self, args): \"\"\"Pick up item from the environment.\"\"\" if len(args) < 2:", "a new filter is not created, so any changes to the # old", "= self.help_menu() self.message(menu) else: name = args[1] try: self.message(self.cmd_dict[name].help_entry()) except KeyError: self.message(f\"Command '{name}'", "def unequip(self, target): \"\"\"updates this character's equip_dict such that the [target] is set", "item '{item_name}' to pick up.\") @Command def drop(self, args): \"\"\"Drop an item into", "to start\" \" as a new character.\") # string-formatting methods def __repr__(self): \"\"\"return", "for entity in new_location.entities: entity.on_enter(self) entity.add_cmds(self) #inventory/item related methods def add_item(self, item, amt=1):", "# also duck test to see if this character even has [target] #", "in data else None return cls(name) def post_load(self, data): pass def save(self): \"\"\"return", "from swampymud.util.shadowdict import ShadowDict class Filter: \"\"\"Filter for screening out certain CharacterClasses and", "continue cls._commands.update(base._local_commands) cls._commands.update(cls._local_commands) # calling the super init super().__init__(name, bases, namespace) def __str__(cls):", "if WHITELIST is selected, only characters whose class is in _classes are allowed", "(initial) keywords are equal\"\"\" try: return (self.func, self.args, self._keys) == \\ (other.func, other.args,", "True BLACKLIST = False WHITELIST = _FilterMode.WHITELIST BLACKLIST = _FilterMode.BLACKLIST def __init__(self, mode,", "keyword argument conflicts with a prior argument, the prior argument will be overriden.", "self.location.characters.remove(self) except ValueError: pass self.location = None self._parser = self._dead_parser # default user-input", "blacklist) self.filter = Filter(Filter.BLACKLIST) def __eq__(self, other): \"\"\"Two commands are equal iff the", "the base functions are equal, the args are equal, and the (initial) keywords", "pass # initialize satellite data self.name = None self.label = None # by", "filter: Filter = None): \"\"\"decorator to easily wrap a function additional traits [name]", "# from having the same name? self._name = new_name # move the player", "use [item] [options for item] Options may vary per item. \"\"\" # TODO:", "\"\"\"initialize a Filter with [mode] if [mode] is True, the Filter will act", "name=item_name) if len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item) item.on_use(self, args[2:]) # replace", "self.message(f\"Exit '{ex_name}' is inaccessible to you.\") # if the char can't see or", "'{item_name}'.\") @Command def pickup(self, args): \"\"\"Pick up item from the environment.\"\"\" if len(args)", "excluded _mode - Filter.WHITELIST or Filter.BLACKLIST if WHITELIST is selected, only characters whose", "were implemented for this class cls._local_commands = {} for value in namespace.values(): if", "equipped.sort() self.message(\"\\n\".join(equipped)) inv_msg = self.inv.readable() # only send a message if inv has", "__str__(cls): \"\"\"overriding str to return classname\"\"\" return cls.classname class Character(metaclass=CharacterClass): \"\"\"Base class for", "def _join_parser(self, new_name: str): \"\"\"Parser for a newly joined player, used for selecting", "Valid equip slots for characters of this class equip_slots = [] def __init__(self,", "def specify(self, *newargs, **new_keywords) -> 'Command': \"\"\"Derive a new version of this function", "__init__(self, *args, **kwargs): \"\"\"initialize a Command like a functools.partial object\"\"\" super().__init__() # creating", "Filter.BLACKLIST else: raise ValueError(\"Unrecognized mode %s\" % repr(mode)) def permits(self, other): \"\"\"returns True", "function self.__name__ = self.func.__name__ self.__doc__ = self.func.__doc__ # try to clean the docstring,", "class is NOT in _classes are allowed through the filter. Note that _include_chars", "1 # add a \"command_label\", if not already provided # this field is", "{!r}, {!r})\".format( self._mode.value, set(self._classes), set(self._include_chars), set(self._exclude_chars) ) @staticmethod def from_dict(filter_dict): \"\"\"returns a Filter", "[item] to player's inventory\"\"\" # if the item is an ItemStack, unpack it", "args): \"\"\"Drop an item into the environment\"\"\" if len(args) < 2: self.message(\"Provide an", "= \" \".join(args[1::]).lower() # search through the items in the equip_dict found_items =", "(empty blacklist) self.filter = Filter(Filter.BLACKLIST) def __eq__(self, other): \"\"\"Two commands are equal iff", "update Command.keywords, avoid doing so. All comparisons are based on the INITIAL keywords,", "*args, **keywords) # propagate the name and source new_cmd.name = self.name new_cmd.label =", "item '{item_name}' to use.\") # miscellaneous methods def help_menu(self) -> str: sources =", "2: self.message(\"Provide an item to equip.\") return item_name = \" \".join(args[1::]).lower() # search", "False WHITELIST = _FilterMode.WHITELIST BLACKLIST = _FilterMode.BLACKLIST def __init__(self, mode, classes=(), include_chars=(), exclude_chars=()):", "= list(self._exclude_chars) return data class Command(functools.partial): \"\"\"A subclass of functools.partial that supports equality.", "commands from this class appear in help menu \"\"\" def __init__(cls, name, bases,", "shown. \"\"\" if len(args) < 2: # TODO: cache this or something menu", "with [mode] if [mode] is True, the Filter will act as a whitelist", "exits # Note! If writing your own method, just do # util.find(location, ex_name,", "not be permitted through the filter. \"\"\" class _FilterMode(enum.Enum): \"\"\"Enum representing whether a", "Command.keywords, avoid doing so. All comparisons are based on the INITIAL keywords, so", "recognized.\") @Command def look(self, args): \"\"\"Gives a description of your current location. usage:", "a symbol # even if someone forgets to set self._symbol in the __init__", "invoke this Command, the Character must use [name] instead of the function's name", "and underlying functions. Optional fields, \"name\", \"label\", and \"field\" are also provided. These", "equip_dict found_items = [] for _, equip_data in self.equip_dict.items(): if equip_data is None:", "with the most recent commands exposed cls._commands = {} for base in reversed(cls.__mro__):", "data class Command(functools.partial): \"\"\"A subclass of functools.partial that supports equality. The default implementation", "remove commands from all the entities # in the current location for entity", "item is even equippable try: target = item.target except AttributeError: self.message(f\"{item} cannot be", "provided # this field is used in creating help menus if \"command_label\" not", "return 'False' if [other] is supplied to permit()\"\"\" # check that other is", "_exclude_chars take precedence over the _classes. That is, if a WHITELIST includes the", "to None and any item at that position is unequipped [target]: an EquipTarget\"\"\"", "something menu = self.help_menu() self.message(menu) else: name = args[1] try: self.message(self.cmd_dict[name].help_entry()) except KeyError:", "exist else: self.message(f\"No exit with name '{ex_name}'.\") @Command.with_traits(name=\"equip\") def cmd_equip(self, args): \"\"\"Equip an", "TODO: update to allow players to 'inspect' certain objects self.message(self.location.view()) @Command def say(self,", "'{item_name}'.\") @Command.with_traits(name=\"unequip\") def cmd_unequip(self, args): \"\"\"Unequip an equipped item. Usage: unequip [item]\"\"\" if", "permits it if cmd.filter.permits(self): self.cmd_dict[name] = cmd # because sCommands are not bound", "None: return f\"{type(self).__name__}()\" return f\"{type(self).__name__}(name={self})\" def __str__(self): \"\"\"return the Character's name\"\"\" if self._name:", "this item, cannot equip else: self.message(f\"Cannot equip item {item} to {target}.\") return def", "representing whether a filter includes or excludes the classes that it tracks\"\"\" WHITELIST", "find equipped item '{item_name}'.\") @Command def pickup(self, args): \"\"\"Pick up item from the", "item_name = \" \".join(args[1:]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: item", "# try to clean the docstring, if one was provided try: self.__doc__ =", "if filter is not None: cmd.filter = filter return cmd return decorator class", "isinstance(other, Character): if other in self._include_chars: self._include_chars.remove(other) self._exclude_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" f\"", "a valid name\"\"\" if len(new_name) < 2: self.message(\"Names must have at least 2", "# propagate the name and source new_cmd.name = self.name new_cmd.label = self.label #", "user-focused depiction of Character\"\"\" if self._name is None: return f\"A nameless {type(self)}\" return", "self.message(inv_msg) @Command.with_traits(name=\"use\") def cmd_use(self, args): \"\"\" Use an item. usage: use [item] [options", "Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to use.\") # miscellaneous methods def", "a wrapper that converts methods into commands that can be invoked by characters.", "function additional traits [name] = to invoke this Command, the Character must use", "WHITELIST = True BLACKLIST = False WHITELIST = _FilterMode.WHITELIST BLACKLIST = _FilterMode.BLACKLIST def", "to the old Command, and visa versa new_cmd.filter = self.filter return new_cmd def", "add_item(self, item, amt=1): \"\"\"add [item] to player's inventory\"\"\" # if the item is", "\"\"\"return the Character's name\"\"\" if self._name: return self._name return \"[nameless character]\" def view(self):", "= Command(func) cmd.name = name cmd.label = label if filter is not None:", "of Character\"\"\" if self._name is None: return f\"{type(self).__name__}()\" return f\"{type(self).__name__}(name={self})\" def __str__(self): \"\"\"return", "subclass of functools.partial that supports equality. The default implementation of functools.partial does not", "return f\"{type(self).__name__}(name={self})\" def __str__(self): \"\"\"return the Character's name\"\"\" if self._name: return self._name return", "found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item) item.on_use(self,", "= Filter(Filter.BLACKLIST) def __eq__(self, other): \"\"\"Two commands are equal iff the base functions", "not already provided # this field is used in creating help menus if", "derive a new Command from an existing one by simply adding additional arguments.", "return decorator class CharacterClass(type): \"\"\"metaclass establishing basic Character behaviors CharacterClasses include the following", "message(self, msg): \"\"\"send a message to the controller of this character\"\"\" # place", "= cmd # because sCommands are not bound properly like a normal #", "place a self.msgs.put_nowait(msg) def command(self, msg): \"\"\"issue 'msg' to character. character will parse", "over the _classes. That is, if a WHITELIST includes the class Wizard, but", "reasons: https://bugs.python.org/issue3564 With this class's equality operators, we aren't trying to solve an", "list of CharacterClasses in order for cls in reversed(type(self).__mro__): if isinstance(cls, CharacterClass): sources[cls.command_label]", "\".join(names)) return \"\\n\".join(output) # serialization-related methods @property def symbol(self): \"\"\"return a unique symbol", "\"\"\" Use an item. usage: use [item] [options for item] Options may vary", "just do # util.find(location, ex_name, location.Exit, char=my_char) # I'm only writing this to", "'.specify' to derive a new Command from an existing one by simply adding", "environment\"\"\" if len(args) < 2: self.message(\"Provide an item to drop.\") return item_name =", "__hash__(self): \"\"\"overriding hash\"\"\" return hash((self.func, self.args, self._keys)) def specify(self, *newargs, **new_keywords) -> 'Command':", "spawn_location): \"\"\"Send a greeting to the character and put them into a name-selection", "= self._command_parser def _command_parser(self, line: str): \"\"\"The default parser for a player. Parses\"\"\"", "Manually iterating over our location's list of exits # Note! If writing your", "to you.\") # if the char can't see or interact with the exit,", "player location to spawn_location, but do not MOVE them # thus, player will", "= the type of the command. (Affects help menu.) [filter] = if provided,", "an equipped item. Usage: unequip [item]\"\"\" if len(args) < 2: self.message(\"Provide an item", "# default user-input parsers def _join_parser(self, new_name: str): \"\"\"Parser for a newly joined", "cls._local_commands[str(value)] = value # all commands, with the most recent commands exposed cls._commands", "say(self, args): \"\"\"Send a message to all players in your current location. usage:", "type=Item found_items = util.find(self.location, name=item_name) if len(found_items) == 1: item = found_items[0][0] self.location.inv.remove_item(item)", "vary per item. \"\"\" # TODO: allow players to use accessible items in", "*args, **kwargs): \"\"\"initialize a Command like a functools.partial object\"\"\" super().__init__() # creating an", "methods def help_menu(self) -> str: sources = {} # walk the mro, to", "commands that were implemented for this class cls._local_commands = {} for value in", "cls._commands = {} for base in reversed(cls.__mro__): if not isinstance(base, CharacterClass): continue cls._commands.update(base._local_commands)", "from all the entities # in the current locations for entity in new_location.entities:", "class Filter: \"\"\"Filter for screening out certain CharacterClasses and Characters _classes - set", "because sCommands are not bound properly like a normal # method, we must", "data[\"exclude_chars\"] = list(self._exclude_chars) return data class Command(functools.partial): \"\"\"A subclass of functools.partial that supports", "class will be labeled \"Default Commands\" command_label = \"Default Commands\" # Valid equip", "set of CharacterClasses tracked by the filter _include_chars - set characters to be", "sources[cls.command_label] = [] for name, cmd in self.cmd_dict.items(): try: sources[cmd.label].append(name) except KeyError: sources[cmd.label]", "if a character can see it? old_location.message(f\"{self} left through exit \" f\"'{ex_name}'.\") else:", "False def __hash__(self): \"\"\"overriding hash\"\"\" return hash((self.func, self.args, self._keys)) def specify(self, *newargs, **new_keywords)", "\"whitelist\": self._mode = Filter.WHITELIST elif mode.lower() == \"blacklist\": self._mode = Filter.BLACKLIST else: raise", "for this command\"\"\" if self.label is not None: return f\"{self} [from {self.label}]:\\n{self.__doc__}\" return", "class is in _classes are allowed through the filter. if BLACKLIST is selected,", "other): \"\"\"Set the filter to return 'True' if [other] is supplied to permit()\"\"\"", "found_items[0][0] self.inv.remove_item(item) self.location.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name.", "'msg' using its current parser.\"\"\" if msg: self._parser(msg) def update(self): \"\"\"periodically called method", "unsupported. \"\"\" def __init__(self, *args, **kwargs): \"\"\"initialize a Command like a functools.partial object\"\"\"", "%s\" % type(other)) def exclude(self, other): \"\"\"Set the filter to return 'False' if", "self.cmd_dict: self.message(\"Command \\'%s\\' not recognized.\" % cmd_name) return cmd = self.cmd_dict[cmd_name] cmd(args) def", "locations as necessary and gathering commands from any entities in the location \"\"\"", "does not possess\" f\" equip slot '{target}'.\") return equipped, from_inv = self.equip_dict[target] equipped.on_unequip(self)", "allow players to use accessible items in location? if len(args) < 2: self.message(\"Please", "this function by applying additional arguments. If a provided keyword argument conflicts with", "has items if inv_msg: self.message(inv_msg) @Command.with_traits(name=\"use\") def cmd_use(self, args): \"\"\" Use an item.", "BLACKLIST is selected, only characters whose class is NOT in _classes are allowed", "= found_items[0][0] self.location.inv.remove_item(item) self.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item", "is None: return f\"{type(self).__name__}()\" return f\"{type(self).__name__}(name={self})\" def __str__(self): \"\"\"return the Character's name\"\"\" if", "from all the entities # in the current location for entity in self.location.entities:", "exclude_chars: raise ValueError(\"Cannot have character in both include\" \" and exclude\") for char", "all the entities # in the current location for entity in self.location.entities: entity.on_exit(self)", "the base function self.__name__ = self.func.__name__ self.__doc__ = self.func.__doc__ # try to clean", "with the exit, # we lie to them and pretend like it doesn't", "\"\"\"Show relevant help information for a particular command. usage: help [command] If no", "# the character / ancestors cannot be found in the list return not", "= None, filter: Filter = None): \"\"\"decorator to easily wrap a function additional", "ex_name, location.Exit, char=my_char) # I'm only writing this to avoid a cyclic dependency.", "\"\"\" # TODO: allow players to use accessible items in location? if len(args)", "if a WHITELIST includes the class Wizard, but Bill the Wizard is in", "self.location = None self.set_location(loc) self._parser = self._command_parser def _command_parser(self, line: str): \"\"\"The default", "the char can't see or interact with the exit, # we lie to", "'.join(args[1:]) if msg and self.location is not None: self.location.message(f\"{self.view()}: {msg}\") @Command def go(self,", "doc from the base function self.__name__ = self.func.__name__ self.__doc__ = self.func.__doc__ # try", "def spawn(self, spawn_location): \"\"\"Send a greeting to the character and put them into", "parsers def _join_parser(self, new_name: str): \"\"\"Parser for a newly joined player, used for", "ancestor ancestors = filter(lambda x: isinstance(x, CharacterClass), other.__mro__) for char_class in ancestors: if", "immutable set of keywords for comparisons self._keys = frozenset(self.keywords.items()) # propagate the name", "inventory first. If item is not found in inventory, the command fails. if", "\"\"\"Send a message to all players in your current location. usage: say [msg]", "# because sCommands are not bound properly like a normal # method, we", "# TODO: override getattribute__ to solve the super() issue? if isinstance(getattr(self, cmd.func.__name__), Command):", "char in include_chars: if char in exclude_chars: raise ValueError(\"Cannot have character in both", "but just confirm that two partially-applied functions have the same arguments and underlying", "be excluded \"\"\" self._classes = set(classes) for char in include_chars: if char in", "mode %s\" % repr(mode)) def permits(self, other): \"\"\"returns True if Character/CharacterClass is allowed", "from Commands collected by CharacterClass self.cmd_dict = ShadowDict() for (name, cmd) in self._commands.items():", "def go(self, args): \"\"\"Go to an accessible location. usage: go [exit name] \"\"\"", "find item '{item_name}' to use.\") # miscellaneous methods def help_menu(self) -> str: sources", "None self.msgs = asyncio.Queue() # build dict from Commands collected by CharacterClass self.cmd_dict", "- set characters to be included _exclude_chars - set characters to be excluded", "inv has items if inv_msg: self.message(inv_msg) @Command.with_traits(name=\"use\") def cmd_use(self, args): \"\"\" Use an", "def include(self, other): \"\"\"Set the filter to return 'True' if [other] is supplied", "self.location.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else:", "should be removed from inventory first. If item is not found in inventory,", "Wizard, but Bill the Wizard is in _exclude_chars, Bill will not be permitted", "isinstance(other, Character): if other in self._exclude_chars: self._exclude_chars.remove(other) self._include_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" \"", "[other] is supplied to permit()\"\"\" # check that other is a Character /", "False # the character / ancestors cannot be found in the list return", "functions are equal, the args are equal, and the (initial) keywords are equal\"\"\"", "inv.ItemStack): self.inv.add_item(item.copy(), item.amount) self.inv.add_item(item, amt) def equip(self, item, from_inv=True): \"\"\"place [item] in this", "exclude\") # store characters in a WeakSet, so that the Filter will not", "x: isinstance(x, CharacterClass), other.__mro__) for char_class in ancestors: if char_class in self._classes: return", "character / ancestors cannot be found in the list return not self._mode.value def", "the type of the command. (Affects help menu.) [filter] = if provided, determine", "with name '{ex_name}'.\") return if found_exit.interact.permits(self): old_location = self.location new_location = found_exit.destination new_location.message(f\"{self}", "KeyError: sources[cmd.label] = [name] # unpack the dictionary in reverse order output =", "establishing basic Character behaviors CharacterClasses include the following important attributes: - classname: how", "description of your current location. usage: look \"\"\" # TODO: update to allow", "self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to use.\") #", "found_items = util.find(self.location, name=item_name) if len(found_items) == 1: item = found_items[0][0] self.location.inv.remove_item(item) self.inv.add_item(item)", "menus if \"command_label\" not in namespace: cls.command_label = f\"{cls} Commands\" # commands that", "len(args) < 2: self.message(\"Provide an item to pick up.\") return item_name = \"", "Note that _include_chars / _exclude_chars take precedence over the _classes. That is, if", "item_name = \" \".join(args[1::]).lower() # search through the items in the equip_dict found_items", "lie to them and pretend like it doesn't exist else: self.message(f\"No exit with", "to pick up.\") @Command def drop(self, args): \"\"\"Drop an item into the environment\"\"\"", "#location manipulation methods def set_location(self, new_location): \"\"\"sets location, updating the previous and new", "updating the previous and new locations as necessary and gathering commands from any", "in new_location.entities: entity.on_enter(self) entity.add_cmds(self) #inventory/item related methods def add_item(self, item, amt=1): \"\"\"add [item]", "name cmd.label = label if filter is not None: cmd.filter = filter return", "item, cannot equip else: self.message(f\"Cannot equip item {item} to {target}.\") return def unequip(self,", "NewCommand will change to the old Command, and visa versa new_cmd.filter = self.filter", "item_name = \" \".join(args[1::]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: self.equip(found_items[0][0])", "{item}-\" \"not found in inventory.\") return # check for an already equipped weapon,", "keywords.update(new_keywords) new_cmd = Command(self.func, *args, **keywords) # propagate the name and source new_cmd.name", "if \"command_label\" not in namespace: cls.command_label = f\"{cls} Commands\" # commands that were", "self._FilterMode): self._mode = mode elif isinstance(mode, bool): if mode: self._mode = Filter.WHITELIST else:", "other is not a Command return False def __hash__(self): \"\"\"overriding hash\"\"\" return hash((self.func,", "< 2: # TODO: cache this or something menu = self.help_menu() self.message(menu) else:", "a message to all players in your current location. usage: say [msg] \"\"\"", "fields store player-relevant information that are NOT factored into comparisons. In addition, this", "[command] If no command is supplied, a list of all commands is shown.", "as a new character.\") # string-formatting methods def __repr__(self): \"\"\"return a representation of", "= item, from_inv # class doesn't have an equip target for this item,", "search through the items in the equip_dict found_items = [] for _, equip_data", "hash((self.func, self.args, self._keys)) def specify(self, *newargs, **new_keywords) -> 'Command': \"\"\"Derive a new version", "def say(self, args): \"\"\"Send a message to all players in your current location.", "if len(found_items) == 1: item = found_items[0][0] self.location.inv.remove_item(item) self.inv.add_item(item) elif len(found_items) > 1:", "WeakSet, so that the Filter will not # prevent them from getting garbage", "elif mode.lower() == \"blacklist\": self._mode = Filter.BLACKLIST else: raise ValueError(\"Unrecognized mode %s\" %", "= self.name new_cmd.label = self.label # note that a new filter is not", "is submitted. \"\"\" self.message(f\"Welcome to our SwampyMud! You are a {type(self)}\") self.message(f\"What should", "== Filter.WHITELIST: if other in self._classes: self._classes.remove(other) else: self._classes.add(other) elif isinstance(other, Character): if", "message to all players in your current location. usage: say [msg] \"\"\" msg", "send a message if inv has items if inv_msg: self.message(inv_msg) @Command.with_traits(name=\"use\") def cmd_use(self,", "= \" \".join(args[1:]) # Manually iterating over our location's list of exits #", "it tracks\"\"\" WHITELIST = True BLACKLIST = False WHITELIST = _FilterMode.WHITELIST BLACKLIST =", "usage: say [msg] \"\"\" msg = ' '.join(args[1:]) if msg and self.location is", "weakref.WeakSet(include_chars) self._exclude_chars = weakref.WeakSet(exclude_chars) if isinstance(mode, self._FilterMode): self._mode = mode elif isinstance(mode, bool):", "amt) def equip(self, item, from_inv=True): \"\"\"place [item] in this player's equip dict [item]:", "necessary and gathering commands from any entities in the location \"\"\" try: self.location.characters.remove(self)", "else: self.message(f\"Cannot equip item {item} to {target}.\") return def unequip(self, target): \"\"\"updates this", "player. Parses\"\"\" # command is always the first word args = line.split() cmd_name", "this or something menu = self.help_menu() self.message(menu) else: name = args[1] try: self.message(self.cmd_dict[name].help_entry())", "mode.lower() == \"blacklist\": self._mode = Filter.BLACKLIST else: raise ValueError(\"Unrecognized mode %s\" % repr(mode))", "cmd.filter = filter return cmd return decorator class CharacterClass(type): \"\"\"metaclass establishing basic Character", "super() issue? if isinstance(getattr(self, cmd.func.__name__), Command): setattr(self, cmd.func.__name__, cmd) # set up inventory", "\" and exclude\") # store characters in a WeakSet, so that the Filter", "default command parsing mode self._parser = self._command_parser def message(self, msg): \"\"\"send a message", "= sources.popitem() output.append(f\"---{source}---\") output.append(\" \".join(names)) return \"\\n\".join(output) # serialization-related methods @property def symbol(self):", "items in the equip_dict found_items = [] for _, equip_data in self.equip_dict.items(): if", "Character/CharacterClass,\" \" received %s\" % type(other)) def exclude(self, other): \"\"\"Set the filter to", "name? self._name = new_name # move the player to the actual location they", "in reversed(type(self).__mro__): if isinstance(cls, CharacterClass): sources[cls.command_label] = [] for name, cmd in self.cmd_dict.items():", "if other in self._classes: self._classes.remove(other) elif isinstance(other, Character): if other in self._exclude_chars: self._exclude_chars.remove(other)", "def equip(self, item, from_inv=True): \"\"\"place [item] in this player's equip dict [item]: item", "so that the Filter will not # prevent them from getting garbage collected", "cls.frequency = 1 # add a \"command_label\", if not already provided # this", "is None: equipped.append(f\"{target}: none\") else: equipped.append(f\"{target}: {item[0]}\") equipped.sort() self.message(\"\\n\".join(equipped)) inv_msg = self.inv.readable() #", "name and doc from the base function self.__name__ = self.func.__name__ self.__doc__ = self.func.__doc__", "new players spawn as this class - command_label: how commands from this class", "items self.inv = inv.Inventory() self.equip_dict = inv.EquipTarget.make_dict(*self.equip_slots) # put character in default command", "item was from character's inventory, return it if from_inv: self.inv.add_item(equipped) # default commands", "equipped item '{item_name}'.\") @Command def pickup(self, args): \"\"\"Pick up item from the environment.\"\"\"", "as inv from swampymud import util from swampymud.util.shadowdict import ShadowDict class Filter: \"\"\"Filter", "trying to solve an undecidable problem, but just confirm that two partially-applied functions", "if no name is provided, func.__name__ is used \"\"\" if self.name is None:", "avoids duplication if from_inv: try: self.inv.remove_item(item) # item not found except KeyError: self.message(f\"Cannot", "# TODO: cache this or something menu = self.help_menu() self.message(menu) else: name =", "self.message(\"Provide an item to pick up.\") return item_name = \" \".join(args[1::]).lower() # TODO:", "from_inv=True): \"\"\"place [item] in this player's equip dict [item]: item to Equip [from_inv]:", "have the same arguments and underlying functions. Optional fields, \"name\", \"label\", and \"field\"", "not in namespace: cls.command_label = f\"{cls} Commands\" # commands that were implemented for", "# if the char can't see or interact with the exit, # we", "= None # Commands from this class will be labeled \"Default Commands\" command_label", "defines the 'Filter', used for CharacterClass-based permissions systems, and 'Command', a wrapper that", "from_inv: try: self.inv.remove_item(item) # item not found except KeyError: self.message(f\"Cannot equip {item}-\" \"not", "\"\"\"Enum representing whether a filter includes or excludes the classes that it tracks\"\"\"", "is Filter.WHITELIST: self._classes.add(other) else: if other in self._classes: self._classes.remove(other) elif isinstance(other, Character): if", "a player dies\"\"\" self.message(\"You died.\") if self.location is not None: self.location.message(f\"{self} died.\", exclude={self})", "in inventory, the command fails. if False, [item] is not removed from inventory", "classes that it tracks\"\"\" WHITELIST = True BLACKLIST = False WHITELIST = _FilterMode.WHITELIST", "if isinstance(other, CharacterClass): if self._mode == Filter.WHITELIST: if other in self._classes: self._classes.remove(other) else:", "an item to equip.\") return item_name = \" \".join(args[1::]).lower() found_items = util.find(self.inv, name=item_name)", "namespace.values(): if isinstance(value, Command): value.label = cls.command_label cls._local_commands[str(value)] = value # all commands,", "created, so any changes to the # old NewCommand will change to the", "message if inv has items if inv_msg: self.message(inv_msg) @Command.with_traits(name=\"use\") def cmd_use(self, args): \"\"\"", "[classes] are those classes to be whitelisted/blacklisted [include_chars] are specific characters to be", "is unequipped [target]: an EquipTarget\"\"\" # test if anything is even equipped #", "self.equip_dict[target] is not None: self.unequip(target) item.on_equip(self) item.add_cmds(self) self.equip_dict[item.target] = item, from_inv # class", "mode: self._mode = Filter.WHITELIST else: self._mode = Filter.BLACKLIST else: if mode.lower() == \"whitelist\":", "this Filter\"\"\" data = {\"mode\" : self._mode.value} if self._classes: data[\"classes\"] = list(self._classes) if", "an item.\") return item_name = args[1] found_items = util.find(self.inv, name=item_name) if len(found_items) ==", "in self._include_chars: return True elif other in self._exclude_chars: return False # now try", "self._exclude_chars = weakref.WeakSet(exclude_chars) if isinstance(mode, self._FilterMode): self._mode = mode elif isinstance(mode, bool): if", "permits(self, other): \"\"\"returns True if Character/CharacterClass is allowed in the individual Character is", "\"\"\"decorator to easily wrap a function additional traits [name] = to invoke this", "self._command_parser def message(self, msg): \"\"\"send a message to the controller of this character\"\"\"", "used in creating help menus if \"command_label\" not in namespace: cls.command_label = f\"{cls}", "into the environment\"\"\" if len(args) < 2: self.message(\"Provide an item to drop.\") return", "# replace the item self.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious", "add command only if filter permits it if cmd.filter.permits(self): self.cmd_dict[name] = cmd #", "equal\"\"\" try: return (self.func, self.args, self._keys) == \\ (other.func, other.args, other._keys) except AttributeError:", "util from swampymud.util.shadowdict import ShadowDict class Filter: \"\"\"Filter for screening out certain CharacterClasses", "self._classes: self._classes.remove(other) else: self._classes.add(other) elif isinstance(other, Character): if other in self._include_chars: self._include_chars.remove(other) self._exclude_chars.add(other)", "__eq__(self, other): \"\"\"Two commands are equal iff the base functions are equal, the", "True elif other in self._exclude_chars: return False # now try the Character's class", "self.message(f\"Command '{name}' not recognized.\") @Command def look(self, args): \"\"\"Gives a description of your", "< 2: self.message(\"Provide an item to equip.\") return item_name = \" \".join(args[1::]).lower() found_items", "be alphanumeric.\") return # TODO: perform some kind of check to prevent players", "whose class is in _classes are allowed through the filter. if BLACKLIST is", "# TODO: only show the exit if a character can see it? old_location.message(f\"{self}", "[exit name] \"\"\" ex_name = \" \".join(args[1:]) # Manually iterating over our location's", "unequip(self, target): \"\"\"updates this character's equip_dict such that the [target] is set to", "all the Character's ancestor classes \"\"\" if isinstance(other, Character): if other in self._include_chars:", "None self._parser = self._dead_parser # default user-input parsers def _join_parser(self, new_name: str): \"\"\"Parser", "by default, add a filter that permits all (empty blacklist) self.filter = Filter(Filter.BLACKLIST)", "do not MOVE them # thus, player will not be available to attack", "and exclude\") # store characters in a WeakSet, so that the Filter will", "data): pass def save(self): \"\"\"return a pythonic representation of this Character\"\"\" return {\"_type\":", "[] def __init__(self, name=None): super().__init__() self._name = name self.location = None self.msgs =", "excludes the classes that it tracks\"\"\" WHITELIST = True BLACKLIST = False WHITELIST", "from an existing one by simply adding additional arguments. All other information (base", "item is an ItemStack, unpack it first if isinstance(item, inv.ItemStack): self.inv.add_item(item.copy(), item.amount) self.inv.add_item(item,", "= frozenset(self.keywords.items()) # propagate the name and doc from the base function self.__name__", "keywords are equal\"\"\" try: return (self.func, self.args, self._keys) == \\ (other.func, other.args, other._keys)", "# TODO: find a way to provide type=Item found_items = util.find(self.location, name=item_name) if", "self.equip_dict[target] equipped.on_unequip(self) equipped.remove_cmds(self) self.equip_dict[target] = None # if item was from character's inventory,", "msg and self.location is not None: self.location.message(f\"{self.view()}: {msg}\") @Command def go(self, args): \"\"\"Go", "an already equipped weapon, unequip it if self.equip_dict[target] is not None: self.unequip(target) item.on_equip(self)", "isinstance(cls, CharacterClass): sources[cls.command_label] = [] for name, cmd in self.cmd_dict.items(): try: sources[cmd.label].append(name) except", "the Character's ancestor classes \"\"\" if isinstance(other, Character): if other in self._include_chars: return", "methods def add_item(self, item, amt=1): \"\"\"add [item] to player's inventory\"\"\" # if the", "be returned to inventory upon unequip. \"\"\" # duck test that the item", "- command_label: how commands from this class appear in help menu \"\"\" def", "elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could", "[name] = to invoke this Command, the Character must use [name] instead of", "if not hasattr(self, \"_symbol\"): symbol = \"{}#{}\".format(type(self).__name__, util.to_base(id(self), 62)) setattr(self, \"_symbol\", symbol) return", "functions have the same arguments and underlying functions. Optional fields, \"name\", \"label\", and", "Character\"\"\" if self._name is None: return f\"A nameless {type(self)}\" return f\"{self._name} the {type(self)}\"", "pythonic representation of this Filter\"\"\" data = {\"mode\" : self._mode.value} if self._classes: data[\"classes\"]", "manipulation methods def set_location(self, new_location): \"\"\"sets location, updating the previous and new locations", "ex break else: self.message(f\"No exit with name '{ex_name}'.\") return if found_exit.interact.permits(self): old_location =", "value in namespace.values(): if isinstance(value, Command): value.label = cls.command_label cls._local_commands[str(value)] = value #", "self.equip_dict.items(): if equip_data is None: continue item, _ = equip_data if str(item).lower() ==", "'False' if [other] is supplied to permit()\"\"\" # check that other is a", "so changing keywords after initialization is unsupported. \"\"\" def __init__(self, *args, **kwargs): \"\"\"initialize", "addition, this class has a convenience method, '.specify' to derive a new Command", "\"\"\" if isinstance(other, Character): if other in self._include_chars: return True elif other in", "new_location): \"\"\"sets location, updating the previous and new locations as necessary and gathering", "to avoid a cyclic dependency. for ex in self.location._exit_list: if ex_name in ex.names:", "support equality for mathematically sound reasons: https://bugs.python.org/issue3564 With this class's equality operators, we", "possess\" f\" equip slot '{target}'.\") return equipped, from_inv = self.equip_dict[target] equipped.on_unequip(self) equipped.remove_cmds(self) self.equip_dict[target]", "not created, so any changes to the # old NewCommand will change to", "first. If item is not found in inventory, the command fails. if False,", "def permits(self, other): \"\"\"returns True if Character/CharacterClass is allowed in the individual Character", "2: self.message(\"Names must have at least 2 characters.\") return if not new_name.isalnum(): self.message(\"Names", "== \\ (other.func, other.args, other._keys) except AttributeError: # other is not a Command", "Filter.BLACKLIST else: if mode.lower() == \"whitelist\": self._mode = Filter.WHITELIST elif mode.lower() == \"blacklist\":", "menu \"\"\" def __init__(cls, name, bases, namespace): # add the proper name, if", "2: self.message(\"Provide an item to drop.\") return item_name = \" \".join(args[1:]).lower() found_items =", "CharacterClass if isinstance(other, CharacterClass): if self._mode == Filter.WHITELIST: if other in self._classes: self._classes.remove(other)", "new character.\") # string-formatting methods def __repr__(self): \"\"\"return a representation of Character\"\"\" if", "self.filter = Filter(Filter.BLACKLIST) def __eq__(self, other): \"\"\"Two commands are equal iff the base", "this class appears to players classname = \"Default Character\" # Starting location for", "to the # old NewCommand will change to the old Command, and visa", "or Filter.BLACKLIST if WHITELIST is selected, only characters whose class is in _classes", "a Filter pythonic representation [filter_dict]\"\"\" return Filter(**filter_dict) def to_dict(self): \"\"\"returns a pythonic representation", "= line.split() cmd_name = args[0] if not cmd_name in self.cmd_dict: self.message(\"Command \\'%s\\' not", "class Command(functools.partial): \"\"\"A subclass of functools.partial that supports equality. The default implementation of", "for entity in self.location.entities: entity.on_exit(self) entity.remove_cmds(self) except AttributeError: # location was none pass", "self.message(\"Names must be alphanumeric.\") return # TODO: perform some kind of check to", "that other is a Character / CharacterClass if isinstance(other, CharacterClass): if self._mode ==", "self.message(f\"Could not find equipped item '{item_name}'.\") @Command def pickup(self, args): \"\"\"Pick up item", "an item into the environment\"\"\" if len(args) < 2: self.message(\"Provide an item to", "Character always has a symbol # even if someone forgets to set self._symbol", "other in self._exclude_chars: self._exclude_chars.remove(other) self._include_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" \" received %s\" %", "help information for a particular command. usage: help [command] If no command is", "{item[0]}\") equipped.sort() self.message(\"\\n\".join(equipped)) inv_msg = self.inv.readable() # only send a message if inv", "perform some kind of check to prevent players # from having the same", "a way to provide type=Item found_items = util.find(self.location, name=item_name) if len(found_items) == 1:", "see it? old_location.message(f\"{self} left through exit \" f\"'{ex_name}'.\") else: if found_exit.perceive.permits(self): self.message(f\"Exit '{ex_name}'", "= 1 # add a \"command_label\", if not already provided # this field", "provided. These fields store player-relevant information that are NOT factored into comparisons. In", "classname\"\"\" return cls.classname class Character(metaclass=CharacterClass): \"\"\"Base class for all other CharacterClasses\"\"\" # How", "symbol = \"{}#{}\".format(type(self).__name__, util.to_base(id(self), 62)) setattr(self, \"_symbol\", symbol) return self._symbol @classmethod def load(cls,", "miscellaneous methods def help_menu(self) -> str: sources = {} # walk the mro,", "players # from having the same name? self._name = new_name # move the", "# Manually iterating over our location's list of exits # Note! If writing", "[from {self.label}]:\\n{self.__doc__}\" return f\"{self}:\\n{self.__doc__}\" @staticmethod def with_traits(name: str = None, label: str =", "Command(func) cmd.name = name cmd.label = label if filter is not None: cmd.filter", "ShadowDict() for (name, cmd) in self._commands.items(): cmd = cmd.specify(self) # add command only", "AttributeError: pass # initialize satellite data self.name = None self.label = None #", "self.message(f\"{type(self)} does not possess\" f\" equip slot '{target}'.\") return equipped, from_inv = self.equip_dict[target]", "to be whitelisted/blacklisted [include_chars] are specific characters to be included [exclude_chars] are specific", "__str__(self): \"\"\"return the Character's name\"\"\" if self._name: return self._name return \"[nameless character]\" def", "_exclude_chars, Bill will not be permitted through the filter. \"\"\" class _FilterMode(enum.Enum): \"\"\"Enum", "that supports equality. The default implementation of functools.partial does not normally support equality", "confirm that two partially-applied functions have the same arguments and underlying functions. Optional", "entity.on_exit(self) entity.remove_cmds(self) except AttributeError: # location was none pass self.location = new_location self.location.add_char(self)", "from this class appear in help menu \"\"\" def __init__(cls, name, bases, namespace):", "cmd.filter.permits(self): self.cmd_dict[name] = cmd # because sCommands are not bound properly like a", "line: str): \"\"\"Parser used when a character has died\"\"\" self.message(\"You have died. Reconnect", "[from_inv]: if True, [item] should be removed from inventory first. If item is", "the item self.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name.", "garbage collected self._include_chars = weakref.WeakSet(include_chars) self._exclude_chars = weakref.WeakSet(exclude_chars) if isinstance(mode, self._FilterMode): self._mode =", "args): \"\"\"Show relevant help information for a particular command. usage: help [command] If", "\"\"\"Module defining the CharacterClass metaclass and Character class, which serves as the basis", "self.message(f\"Could not find item '{item_name}'.\") @Command.with_traits(name=\"unequip\") def cmd_unequip(self, args): \"\"\"Unequip an equipped item.", "additional arguments. All other information (base function, names, etc.) will be propagated. While", "\" \".join(args[1:]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: item = found_items[0][0]", "commands is shown. \"\"\" if len(args) < 2: # TODO: cache this or", "# Valid equip slots for characters of this class equip_slots = [] def", "name is provided, func.__name__ is used \"\"\" if self.name is None: return self.func.__name__", "as a whitelist if [mode] is False, the Filter will act as a", "self._name = name self.location = None self.msgs = asyncio.Queue() # build dict from", "joined player, used for selecting a valid name\"\"\" if len(new_name) < 2: self.message(\"Names", "the individual Character is evaluated first, then the Character's class, then all the", "if self._classes: data[\"classes\"] = list(self._classes) if self._include_chars: data[\"include_chars\"] = list(self._include_chars) if self._exclude_chars: data[\"exclude_chars\"]", "Filter: \"\"\"Filter for screening out certain CharacterClasses and Characters _classes - set of", "in self.cmd_dict: self.message(\"Command \\'%s\\' not recognized.\" % cmd_name) return cmd = self.cmd_dict[cmd_name] cmd(args)", "@Command def say(self, args): \"\"\"Send a message to all players in your current", "the INITIAL keywords, so changing keywords after initialization is unsupported. \"\"\" def __init__(self,", "version of this function by applying additional arguments. If a provided keyword argument", "to ensure that Character always has a symbol # even if someone forgets", "self.equip_dict[target] is None: self.message(f\"No item equipped on target {target}.\") return except KeyError: self.message(f\"{type(self)}", "factored into comparisons. In addition, this class has a convenience method, '.specify' to", "equip slot '{target}'.\") return equipped, from_inv = self.equip_dict[target] equipped.on_unequip(self) equipped.remove_cmds(self) self.equip_dict[target] = None", "usage: use [item] [options for item] Options may vary per item. \"\"\" #", "item_name: found_items.append(item) if len(found_items) == 1: self.unequip(found_items[0].target) elif len(found_items) > 1: #TODO handle", "avoid doing so. All comparisons are based on the INITIAL keywords, so changing", "the Filter will act as a blacklist [classes] are those classes to be", "None return cls(name) def post_load(self, data): pass def save(self): \"\"\"return a pythonic representation", "@Command def drop(self, args): \"\"\"Drop an item into the environment\"\"\" if len(args) <", "override getattribute__ to solve the super() issue? if isinstance(getattr(self, cmd.func.__name__), Command): setattr(self, cmd.func.__name__,", "entity in self.location.entities: entity.on_exit(self) entity.remove_cmds(self) except AttributeError: # location was none pass self.location", "include\" \" and exclude\") for char in exclude_chars: if char in include_chars: raise", "information for a particular command. usage: help [command] If no command is supplied,", "[item] in this player's equip dict [item]: item to Equip [from_inv]: if True,", "drop(self, args): \"\"\"Drop an item into the environment\"\"\" if len(args) < 2: self.message(\"Provide", "the character should spawn after a name is submitted. \"\"\" self.message(f\"Welcome to our", "is neither a CharClass nor Character else: return False # the character /", "1: self.equip(found_items[0][0]) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\")", "= inv.EquipTarget.make_dict(*self.equip_slots) # put character in default command parsing mode self._parser = self._command_parser", "inventory. usage: inv\"\"\" # create a string representation of the equipped items equipped", "TODO: perform some kind of check to prevent players # from having the", "len(found_items) == 1: self.unequip(found_items[0].target) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item", "namespace: cls.classname = util.camel_to_space(name) # add a frequency field, if not already provided", "# string-formatting methods def __repr__(self): \"\"\"return a representation of Character\"\"\" if self._name is", "self.set_location(new_location) # TODO: only show the exit if a character can see it?", "find a way to provide type=Item found_items = util.find(self.location, name=item_name) if len(found_items) ==", "raise ValueError(\"Cannot have character in both include\" \" and exclude\") # store characters", "arguments and underlying functions. Optional fields, \"name\", \"label\", and \"field\" are also provided.", "new_cmd def __str__(self): \"\"\"returns the name of this command if no name is", "if true, remove item from inventory # this avoids duplication if from_inv: try:", "defining the CharacterClass metaclass and Character class, which serves as the basis for", "AttributeError: # location was none pass self.location = new_location self.location.add_char(self) # add commands", "-> str: sources = {} # walk the mro, to get the list", "pass def save(self): \"\"\"return a pythonic representation of this Character\"\"\" return {\"_type\": type(self),", "isinstance(x, CharacterClass), other.__mro__) for char_class in ancestors: if char_class in self._classes: return self._mode.value", "len(found_items) == 1: self.equip(found_items[0][0]) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item", "class has a convenience method, '.specify' to derive a new Command from an", "the exit, # we lie to them and pretend like it doesn't exist", "whether a filter includes or excludes the classes that it tracks\"\"\" WHITELIST =", "util.find(self.inv, name=item_name) if len(found_items) == 1: self.equip(found_items[0][0]) elif len(found_items) > 1: #TODO handle", "if isinstance(other, Character): if other in self._include_chars: return True elif other in self._exclude_chars:", "command_label: how commands from this class appear in help menu \"\"\" def __init__(cls,", "_mode - Filter.WHITELIST or Filter.BLACKLIST if WHITELIST is selected, only characters whose class", "isinstance(value, Command): value.label = cls.command_label cls._local_commands[str(value)] = value # all commands, with the", "def __str__(self): \"\"\"return the Character's name\"\"\" if self._name: return self._name return \"[nameless character]\"", "ItemStack, unpack it first if isinstance(item, inv.ItemStack): self.inv.add_item(item.copy(), item.amount) self.inv.add_item(item, amt) def equip(self,", "not new_name.isalnum(): self.message(\"Names must be alphanumeric.\") return # TODO: perform some kind of", "return equipped, from_inv = self.equip_dict[target] equipped.on_unequip(self) equipped.remove_cmds(self) self.equip_dict[target] = None # if item", "be in loc = self.location self.location = None self.set_location(loc) self._parser = self._command_parser def", "commands that can be invoked by characters. \"\"\" import enum import functools import", "the command. (Affects help menu.) [filter] = if provided, determine which Characters /", "return if target in self.equip_dict: # check remove_inv, if true, remove item from", "self.keywords.copy() keywords.update(new_keywords) new_cmd = Command(self.func, *args, **keywords) # propagate the name and source", "{item} to {target}.\") return def unequip(self, target): \"\"\"updates this character's equip_dict such that", "\"\"\"returns a Filter pythonic representation [filter_dict]\"\"\" return Filter(**filter_dict) def to_dict(self): \"\"\"returns a pythonic", "= None, label: str = None, filter: Filter = None): \"\"\"decorator to easily", "pass self.location = new_location self.location.add_char(self) # add commands from all the entities #", "\".join(args[1:]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item)", "weakref.WeakSet(exclude_chars) if isinstance(mode, self._FilterMode): self._mode = mode elif isinstance(mode, bool): if mode: self._mode", "if char_class in self._classes: return self._mode.value # \"other\" is neither a CharClass nor", "we call you?\") # set player location to spawn_location, but do not MOVE", "and gathering commands from any entities in the location \"\"\" try: self.location.characters.remove(self) #", "help message for this command\"\"\" if self.label is not None: return f\"{self} [from", "available to attack self.location = spawn_location self._parser = self._join_parser def despawn(self): \"\"\"method executed", "mathematically sound reasons: https://bugs.python.org/issue3564 With this class's equality operators, we aren't trying to", "equip item {item} to {target}.\") return def unequip(self, target): \"\"\"updates this character's equip_dict", "pass self.location = None self._parser = self._dead_parser # default user-input parsers def _join_parser(self,", "new_location self.location.add_char(self) # add commands from all the entities # in the current", "to character. character will parse 'msg' using its current parser.\"\"\" if msg: self._parser(msg)", "item.on_use(self, args[2:]) # replace the item self.inv.add_item(item) elif len(found_items) > 1: #TODO handle", "\"[nameless character]\" def view(self): \"\"\"return a longer, user-focused depiction of Character\"\"\" if self._name", "the filter to return 'False' if [other] is supplied to permit()\"\"\" # check", "propagated. While you can update Command.keywords, avoid doing so. All comparisons are based", "output = [] while sources: source, names = sources.popitem() output.append(f\"---{source}---\") output.append(\" \".join(names)) return", "returned to inventory upon unequip. \"\"\" # duck test that the item is", "equipped on target {target}.\") return except KeyError: self.message(f\"{type(self)} does not possess\" f\" equip", "None: return f\"{self} [from {self.label}]:\\n{self.__doc__}\" return f\"{self}:\\n{self.__doc__}\" @staticmethod def with_traits(name: str = None,", "item, amt=1): \"\"\"add [item] to player's inventory\"\"\" # if the item is an", "of this Filter\"\"\" data = {\"mode\" : self._mode.value} if self._classes: data[\"classes\"] = list(self._classes)", "_classes are allowed through the filter. Note that _include_chars / _exclude_chars take precedence", "# if item was from character's inventory, return it if from_inv: self.inv.add_item(equipped) #", "old_location.message(f\"{self} left through exit \" f\"'{ex_name}'.\") else: if found_exit.perceive.permits(self): self.message(f\"Exit '{ex_name}' is inaccessible", "super().__init__() # creating an immutable set of keywords for comparisons self._keys = frozenset(self.keywords.items())", "a Command like a functools.partial object\"\"\" super().__init__() # creating an immutable set of", "if equip_data is None: continue item, _ = equip_data if str(item).lower() == item_name:", "recognized.\" % cmd_name) return cmd = self.cmd_dict[cmd_name] cmd(args) def _dead_parser(self, line: str): \"\"\"Parser", "CharacterClass if isinstance(other, CharacterClass): if self._mode is Filter.WHITELIST: self._classes.add(other) else: if other in", "return False def __hash__(self): \"\"\"overriding hash\"\"\" return hash((self.func, self.args, self._keys)) def specify(self, *newargs,", "class _FilterMode(enum.Enum): \"\"\"Enum representing whether a filter includes or excludes the classes that", "return except KeyError: self.message(f\"{type(self)} does not possess\" f\" equip slot '{target}'.\") return equipped,", "class appear in help menu \"\"\" def __init__(cls, name, bases, namespace): # add", "\"\"\"overriding repr()\"\"\" return \"Filter({!r}, {!r}, {!r}, {!r})\".format( self._mode.value, set(self._classes), set(self._include_chars), set(self._exclude_chars) ) @staticmethod", "store characters in a WeakSet, so that the Filter will not # prevent", "__init__(self, mode, classes=(), include_chars=(), exclude_chars=()): \"\"\"initialize a Filter with [mode] if [mode] is", "found_items[0][0] self.inv.remove_item(item) item.on_use(self, args[2:]) # replace the item self.inv.add_item(item) elif len(found_items) > 1:", "other): \"\"\"Set the filter to return 'False' if [other] is supplied to permit()\"\"\"", "[] while sources: source, names = sources.popitem() output.append(f\"---{source}---\") output.append(\" \".join(names)) return \"\\n\".join(output) #", "a convenience method, '.specify' to derive a new Command from an existing one", "if len(args) < 2: self.message(\"Provide an item to pick up.\") return item_name =", "from the environment.\"\"\" if len(args) < 2: self.message(\"Provide an item to pick up.\")", "set(classes) for char in include_chars: if char in exclude_chars: raise ValueError(\"Cannot have character", "blacklist [classes] are those classes to be whitelisted/blacklisted [include_chars] are specific characters to", "__str__(self): \"\"\"returns the name of this command if no name is provided, func.__name__", "name of this command if no name is provided, func.__name__ is used \"\"\"", "= to invoke this Command, the Character must use [name] instead of the", "return self._symbol @classmethod def load(cls, data): name = data[\"name\"] if \"name\" in data", "cmd in self.cmd_dict.items(): try: sources[cmd.label].append(name) except KeyError: sources[cmd.label] = [name] # unpack the", "not isinstance(base, CharacterClass): continue cls._commands.update(base._local_commands) cls._commands.update(cls._local_commands) # calling the super init super().__init__(name, bases,", "removed from inventory and will not be returned to inventory upon unequip. \"\"\"", "\"\"\" msg = ' '.join(args[1:]) if msg and self.location is not None: self.location.message(f\"{self.view()}:", "argument conflicts with a prior argument, the prior argument will be overriden. \"\"\"", "class equip_slots = [] def __init__(self, name=None): super().__init__() self._name = name self.location =", "self.label # note that a new filter is not created, so any changes", "return self.name def help_entry(self) -> str: \"\"\"return a help message for this command\"\"\"", "position is unequipped [target]: an EquipTarget\"\"\" # test if anything is even equipped", "this command. \"\"\" def decorator(func): cmd = Command(func) cmd.name = name cmd.label =", "classes=(), include_chars=(), exclude_chars=()): \"\"\"initialize a Filter with [mode] if [mode] is True, the", "find item '{item_name}' to pick up.\") @Command def drop(self, args): \"\"\"Drop an item", "the filter. if BLACKLIST is selected, only characters whose class is NOT in", "in namespace: cls.frequency = 1 # add a \"command_label\", if not already provided", "= item.target except AttributeError: self.message(f\"{item} cannot be equipped.\") return if target in self.equip_dict:", "calling the super init super().__init__(name, bases, namespace) def __str__(cls): \"\"\"overriding str to return", "for all other CharacterClasses\"\"\" # How this class appears to players classname =", "class Character(metaclass=CharacterClass): \"\"\"Base class for all other CharacterClasses\"\"\" # How this class appears", "self.message(f\"Welcome to our SwampyMud! You are a {type(self)}\") self.message(f\"What should we call you?\")", "\"\"\" try: self.location.characters.remove(self) # remove commands from all the entities # in the", "out certain CharacterClasses and Characters _classes - set of CharacterClasses tracked by the", "= self.func.__doc__ # try to clean the docstring, if one was provided try:", "for ex in self.location._exit_list: if ex_name in ex.names: found_exit = ex break else:", "KeyError: self.message(f\"{type(self)} does not possess\" f\" equip slot '{target}'.\") return equipped, from_inv =", "inventory # this avoids duplication if from_inv: try: self.inv.remove_item(item) # item not found", "always the first word args = line.split() cmd_name = args[0] if not cmd_name", "from inventory first. If item is not found in inventory, the command fails.", "= if provided, determine which Characters / Classes are permitted to use this", "start\" \" as a new character.\") # string-formatting methods def __repr__(self): \"\"\"return a", "for char in include_chars: if char in exclude_chars: raise ValueError(\"Cannot have character in", "return False # the character / ancestors cannot be found in the list", "\"name\" in data else None return cls(name) def post_load(self, data): pass def save(self):", "character in default command parsing mode self._parser = self._command_parser def message(self, msg): \"\"\"send", "a list of all commands is shown. \"\"\" if len(args) < 2: #", "The default implementation of functools.partial does not normally support equality for mathematically sound", "@property def symbol(self): \"\"\"return a unique symbol for this Character\"\"\" # failsafe to", "equality for mathematically sound reasons: https://bugs.python.org/issue3564 With this class's equality operators, we aren't", "in both include\" \" and exclude\") # store characters in a WeakSet, so", "item = found_items[0][0] self.inv.remove_item(item) self.location.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious", "class other = type(other) if isinstance(other, CharacterClass): # cycle through each ancestor ancestors", "player, used for selecting a valid name\"\"\" if len(new_name) < 2: self.message(\"Names must", "self.message(f\"Cannot equip {item}-\" \"not found in inventory.\") return # check for an already", "equip else: self.message(f\"Cannot equip item {item} to {target}.\") return def unequip(self, target): \"\"\"updates", "All other information (base function, names, etc.) will be propagated. While you can", "not find equipped item '{item_name}'.\") @Command def pickup(self, args): \"\"\"Pick up item from", "is not a Command return False def __hash__(self): \"\"\"overriding hash\"\"\" return hash((self.func, self.args,", "characters. \"\"\" import enum import functools import inspect import weakref import asyncio import", "command fails. if False, [item] is not removed from inventory and will not", "= True BLACKLIST = False WHITELIST = _FilterMode.WHITELIST BLACKLIST = _FilterMode.BLACKLIST def __init__(self,", "return Filter(**filter_dict) def to_dict(self): \"\"\"returns a pythonic representation of this Filter\"\"\" data =", "if len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item) item.on_use(self, args[2:]) # replace the", "to be included [exclude_chars] are specific characters to be excluded \"\"\" self._classes =", "the entities # in the current locations for entity in new_location.entities: entity.on_enter(self) entity.add_cmds(self)", "usage: inv\"\"\" # create a string representation of the equipped items equipped =", "over our location's list of exits # Note! If writing your own method,", "if self._name: return self._name return \"[nameless character]\" def view(self): \"\"\"return a longer, user-focused", "self.location.entities: entity.on_exit(self) entity.remove_cmds(self) except AttributeError: # location was none pass self.location = new_location", "command parsing mode self._parser = self._command_parser def message(self, msg): \"\"\"send a message to", "selecting a valid name\"\"\" if len(new_name) < 2: self.message(\"Names must have at least", "unequip it if self.equip_dict[target] is not None: self.unequip(target) item.on_equip(self) item.add_cmds(self) self.equip_dict[item.target] = item,", "inventory, return it if from_inv: self.inv.add_item(equipped) # default commands @Command def help(self, args):", "return not self._mode.value def include(self, other): \"\"\"Set the filter to return 'True' if", "classes \"\"\" if isinstance(other, Character): if other in self._include_chars: return True elif other", "data[\"name\"] if \"name\" in data else None return cls(name) def post_load(self, data): pass", "in _exclude_chars, Bill will not be permitted through the filter. \"\"\" class _FilterMode(enum.Enum):", "# TODO: perform some kind of check to prevent players # from having", "be labeled \"Default Commands\" command_label = \"Default Commands\" # Valid equip slots for", "other in self._include_chars: return True elif other in self._exclude_chars: return False # now", "first word args = line.split() cmd_name = args[0] if not cmd_name in self.cmd_dict:", "at that position is unequipped [target]: an EquipTarget\"\"\" # test if anything is", "data): name = data[\"name\"] if \"name\" in data else None return cls(name) def", "Filter will act as a whitelist if [mode] is False, the Filter will", "# class doesn't have an equip target for this item, cannot equip else:", "found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: self.equip(found_items[0][0]) elif len(found_items) > 1:", "inv from swampymud import util from swampymud.util.shadowdict import ShadowDict class Filter: \"\"\"Filter for", "exclude_chars: if char in include_chars: raise ValueError(\"Cannot have character in both include\" \"", "allowed in the individual Character is evaluated first, then the Character's class, then", "= \" \".join(args[1::]).lower() # TODO: find a way to provide type=Item found_items =", "return f\"{type(self).__name__}()\" return f\"{type(self).__name__}(name={self})\" def __str__(self): \"\"\"return the Character's name\"\"\" if self._name: return", "try: self.message(self.cmd_dict[name].help_entry()) except KeyError: self.message(f\"Command '{name}' not recognized.\") @Command def look(self, args): \"\"\"Gives", "item to equip.\") return item_name = \" \".join(args[1::]).lower() found_items = util.find(self.inv, name=item_name) if", "the CharacterClass metaclass and Character class, which serves as the basis for all", "characters. This module also defines the 'Filter', used for CharacterClass-based permissions systems, and", "for comparisons self._keys = frozenset(self.keywords.items()) # propagate the name and doc from the", "= util.camel_to_space(name) # add a frequency field, if not already provided if \"frequency\"", "decorator(func): cmd = Command(func) cmd.name = name cmd.label = label if filter is", "# location was none pass self.location = new_location self.location.add_char(self) # add commands from", "use.\") # miscellaneous methods def help_menu(self) -> str: sources = {} # walk", "is provided, func.__name__ is used \"\"\" if self.name is None: return self.func.__name__ return", "to use.\") # miscellaneous methods def help_menu(self) -> str: sources = {} #", "namespace: cls.command_label = f\"{cls} Commands\" # commands that were implemented for this class", "have died. Reconnect to this server to start\" \" as a new character.\")", "character's equip_dict such that the [target] is set to None and any item", "# TODO: allow players to use accessible items in location? if len(args) <", "% type(other)) def exclude(self, other): \"\"\"Set the filter to return 'False' if [other]", "Character must use [name] instead of the function's name [label] = the type", "is False, the Filter will act as a blacklist [classes] are those classes", "characters to be included [exclude_chars] are specific characters to be excluded \"\"\" self._classes", "[mode] is False, the Filter will act as a blacklist [classes] are those", "if the char can't see or interact with the exit, # we lie", "following important attributes: - classname: how the class appears to the players -", "equipped.on_unequip(self) equipped.remove_cmds(self) self.equip_dict[target] = None # if item was from character's inventory, return", "left through exit \" f\"'{ex_name}'.\") else: if found_exit.perceive.permits(self): self.message(f\"Exit '{ex_name}' is inaccessible to", "char can't see or interact with the exit, # we lie to them", "handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find equipped item '{item_name}'.\")", "of this command if no name is provided, func.__name__ is used \"\"\" if", "character and put them into a name-selection mode. [spawn_location]: where the character should", "None: equipped.append(f\"{target}: none\") else: equipped.append(f\"{target}: {item[0]}\") equipped.sort() self.message(\"\\n\".join(equipped)) inv_msg = self.inv.readable() # only", "Classes are permitted to use this command. \"\"\" def decorator(func): cmd = Command(func)", "= Command(self.func, *args, **keywords) # propagate the name and source new_cmd.name = self.name", "put them into a name-selection mode. [spawn_location]: where the character should spawn after", "initialize satellite data self.name = None self.label = None # by default, add", "if isinstance(getattr(self, cmd.func.__name__), Command): setattr(self, cmd.func.__name__, cmd) # set up inventory and equipping", "reverse order output = [] while sources: source, names = sources.popitem() output.append(f\"---{source}---\") output.append(\"", "are allowed through the filter. Note that _include_chars / _exclude_chars take precedence over", "to spawn_location, but do not MOVE them # thus, player will not be", "the class appears to the players - frequency: how often will new players", "1: item = found_items[0][0] self.inv.remove_item(item) item.on_use(self, args[2:]) # replace the item self.inv.add_item(item) elif", "[exclude_chars] are specific characters to be excluded \"\"\" self._classes = set(classes) for char", "_classes - set of CharacterClasses tracked by the filter _include_chars - set characters", "CharacterClass): # cycle through each ancestor ancestors = filter(lambda x: isinstance(x, CharacterClass), other.__mro__)", "All comparisons are based on the INITIAL keywords, so changing keywords after initialization", "in exclude_chars: raise ValueError(\"Cannot have character in both include\" \" and exclude\") for", "self.cmd_dict.items(): try: sources[cmd.label].append(name) except KeyError: sources[cmd.label] = [name] # unpack the dictionary in", "are also provided. These fields store player-relevant information that are NOT factored into", "test if anything is even equipped # also duck test to see if", "item. Usage: unequip [item]\"\"\" if len(args) < 2: self.message(\"Provide an item to equip.\")", "you?\") # set player location to spawn_location, but do not MOVE them #", "if self.equip_dict[target] is not None: self.unequip(target) item.on_equip(self) item.add_cmds(self) self.equip_dict[item.target] = item, from_inv #", "from character's inventory, return it if from_inv: self.inv.add_item(equipped) # default commands @Command def", "\"\"\" if len(args) < 2: # TODO: cache this or something menu =", "such that the [target] is set to None and any item at that", "reversed(cls.__mro__): if not isinstance(base, CharacterClass): continue cls._commands.update(base._local_commands) cls._commands.update(cls._local_commands) # calling the super init", "item '{item_name}'.\") @Command def pickup(self, args): \"\"\"Pick up item from the environment.\"\"\" if", "specific characters to be included [exclude_chars] are specific characters to be excluded \"\"\"", "pythonic representation [filter_dict]\"\"\" return Filter(**filter_dict) def to_dict(self): \"\"\"returns a pythonic representation of this", "try: if self.equip_dict[target] is None: self.message(f\"No item equipped on target {target}.\") return except", "wrap a function additional traits [name] = to invoke this Command, the Character", "return self.func.__name__ return self.name def help_entry(self) -> str: \"\"\"return a help message for", "usage: go [exit name] \"\"\" ex_name = \" \".join(args[1:]) # Manually iterating over", "equip.\") return item_name = \" \".join(args[1::]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items) ==", "cyclic dependency. for ex in self.location._exit_list: if ex_name in ex.names: found_exit = ex", "current location. usage: say [msg] \"\"\" msg = ' '.join(args[1:]) if msg and", "= util.find(self.inv, name=item_name) if len(found_items) == 1: self.equip(found_items[0][0]) elif len(found_items) > 1: #TODO", "if from_inv: self.inv.add_item(equipped) # default commands @Command def help(self, args): \"\"\"Show relevant help", "help menus if \"command_label\" not in namespace: cls.command_label = f\"{cls} Commands\" # commands", "the character / ancestors cannot be found in the list return not self._mode.value", "if \"classname\" not in namespace: cls.classname = util.camel_to_space(name) # add a frequency field,", "else: self.message(f\"No exit with name '{ex_name}'.\") return if found_exit.interact.permits(self): old_location = self.location new_location", "not None: self.location.message(f\"{self.view()}: {msg}\") @Command def go(self, args): \"\"\"Go to an accessible location.", "self.equip_dict[item.target] = item, from_inv # class doesn't have an equip target for this", "= weakref.WeakSet(exclude_chars) if isinstance(mode, self._FilterMode): self._mode = mode elif isinstance(mode, bool): if mode:", "problem, but just confirm that two partially-applied functions have the same arguments and", "implemented for this class cls._local_commands = {} for value in namespace.values(): if isinstance(value,", "class, which serves as the basis for all in-game characters. This module also", "#TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}'.\")", "most recent commands exposed cls._commands = {} for base in reversed(cls.__mro__): if not", "is selected, only characters whose class is NOT in _classes are allowed through", "self.message(f\"{item} cannot be equipped.\") return if target in self.equip_dict: # check remove_inv, if", "an item to drop.\") return item_name = \" \".join(args[1:]).lower() found_items = util.find(self.inv, name=item_name)", "'Command', a wrapper that converts methods into commands that can be invoked by", "player to the actual location they should be in loc = self.location self.location", "from the base function self.__name__ = self.func.__name__ self.__doc__ = self.func.__doc__ # try to", "important attributes: - classname: how the class appears to the players - frequency:", "filter to return 'True' if [other] is supplied to permit()\"\"\" # check that", "fields, \"name\", \"label\", and \"field\" are also provided. These fields store player-relevant information", "was from character's inventory, return it if from_inv: self.inv.add_item(equipped) # default commands @Command", "method, we must manually bind the methods # TODO: override getattribute__ to solve", "cmd.name = name cmd.label = label if filter is not None: cmd.filter =", "provide type=Item found_items = util.find(self.location, name=item_name) if len(found_items) == 1: item = found_items[0][0]", "or excludes the classes that it tracks\"\"\" WHITELIST = True BLACKLIST = False", "else: equipped.append(f\"{target}: {item[0]}\") equipped.sort() self.message(\"\\n\".join(equipped)) inv_msg = self.inv.readable() # only send a message", "up item from the environment.\"\"\" if len(args) < 2: self.message(\"Provide an item to", "frozenset(self.keywords.items()) # propagate the name and doc from the base function self.__name__ =", "if \"frequency\" not in namespace: cls.frequency = 1 # add a \"command_label\", if", "raise ValueError(\"Cannot have character in both include\" \" and exclude\") for char in", "item to drop.\") return item_name = \" \".join(args[1:]).lower() found_items = util.find(self.inv, name=item_name) if", "# command is always the first word args = line.split() cmd_name = args[0]", "item, _ = equip_data if str(item).lower() == item_name: found_items.append(item) if len(found_items) == 1:", "Character(metaclass=CharacterClass): \"\"\"Base class for all other CharacterClasses\"\"\" # How this class appears to", "item. \"\"\" # TODO: allow players to use accessible items in location? if", "{type(other)}\") def __repr__(self): \"\"\"overriding repr()\"\"\" return \"Filter({!r}, {!r}, {!r}, {!r})\".format( self._mode.value, set(self._classes), set(self._include_chars),", "Character\" # Starting location for this class starting_location = None # Commands from", "f\"{type(self).__name__}()\" return f\"{type(self).__name__}(name={self})\" def __str__(self): \"\"\"return the Character's name\"\"\" if self._name: return self._name", "menu = self.help_menu() self.message(menu) else: name = args[1] try: self.message(self.cmd_dict[name].help_entry()) except KeyError: self.message(f\"Command", "propagate the name and doc from the base function self.__name__ = self.func.__name__ self.__doc__", "@Command def go(self, args): \"\"\"Go to an accessible location. usage: go [exit name]", "class - command_label: how commands from this class appear in help menu \"\"\"", "argument will be overriden. \"\"\" args = self.args + tuple(newargs) keywords = self.keywords.copy()", "self.equip_dict = inv.EquipTarget.make_dict(*self.equip_slots) # put character in default command parsing mode self._parser =", "If a provided keyword argument conflicts with a prior argument, the prior argument", "_command_parser(self, line: str): \"\"\"The default parser for a player. Parses\"\"\" # command is", "= {} for base in reversed(cls.__mro__): if not isinstance(base, CharacterClass): continue cls._commands.update(base._local_commands) cls._commands.update(cls._local_commands)", "\"\"\"returns a pythonic representation of this Filter\"\"\" data = {\"mode\" : self._mode.value} if", "\"\"\"A subclass of functools.partial that supports equality. The default implementation of functools.partial does", "of the function's name [label] = the type of the command. (Affects help", "as this class - command_label: how commands from this class appear in help", "set up inventory and equipping items self.inv = inv.Inventory() self.equip_dict = inv.EquipTarget.make_dict(*self.equip_slots) #", "f\"{type(self).__name__}(name={self})\" def __str__(self): \"\"\"return the Character's name\"\"\" if self._name: return self._name return \"[nameless", "_join_parser(self, new_name: str): \"\"\"Parser for a newly joined player, used for selecting a", "but do not MOVE them # thus, player will not be available to", "None # if item was from character's inventory, return it if from_inv: self.inv.add_item(equipped)", "You are a {type(self)}\") self.message(f\"What should we call you?\") # set player location", "\"\"\"overriding str to return classname\"\"\" return cls.classname class Character(metaclass=CharacterClass): \"\"\"Base class for all", "also defines the 'Filter', used for CharacterClass-based permissions systems, and 'Command', a wrapper", "mode.lower() == \"whitelist\": self._mode = Filter.WHITELIST elif mode.lower() == \"blacklist\": self._mode = Filter.BLACKLIST", "# Commands from this class will be labeled \"Default Commands\" command_label = \"Default", "actual location they should be in loc = self.location self.location = None self.set_location(loc)", "has a symbol # even if someone forgets to set self._symbol in the", "not None: cmd.filter = filter return cmd return decorator class CharacterClass(type): \"\"\"metaclass establishing", "False # now try the Character's class other = type(other) if isinstance(other, CharacterClass):", "entities # in the current locations for entity in new_location.entities: entity.on_enter(self) entity.add_cmds(self) #inventory/item", "self.message(\"\\n\".join(equipped)) inv_msg = self.inv.readable() # only send a message if inv has items", "self.message(f\"Could not find item '{item_name}' to pick up.\") @Command def drop(self, args): \"\"\"Drop", "character. character will parse 'msg' using its current parser.\"\"\" if msg: self._parser(msg) def", "data self.name = None self.label = None # by default, add a filter", "into a name-selection mode. [spawn_location]: where the character should spawn after a name", "= value # all commands, with the most recent commands exposed cls._commands =", "with_traits(name: str = None, label: str = None, filter: Filter = None): \"\"\"decorator", "collected by CharacterClass self.cmd_dict = ShadowDict() for (name, cmd) in self._commands.items(): cmd =", "# check remove_inv, if true, remove item from inventory # this avoids duplication", "help(self, args): \"\"\"Show relevant help information for a particular command. usage: help [command]", "your inventory.\"\"\" if len(args) < 2: self.message(\"Provide an item to equip.\") return item_name", "check for an already equipped weapon, unequip it if self.equip_dict[target] is not None:", "[] for target, item in self.equip_dict.items(): if item is None: equipped.append(f\"{target}: none\") else:", "def __init__(cls, name, bases, namespace): # add the proper name, if not already", "self.message(\"Provide an item to equip.\") return item_name = \" \".join(args[1::]).lower() # search through", "Character's class, then all the Character's ancestor classes \"\"\" if isinstance(other, Character): if", "comparisons are based on the INITIAL keywords, so changing keywords after initialization is", "find item '{item_name}' to drop.\") @Command.with_traits(name=\"inv\") def cmd_inv(self, args): \"\"\"Show your inventory. usage:", "act as a blacklist [classes] are those classes to be whitelisted/blacklisted [include_chars] are", "# unpack the dictionary in reverse order output = [] while sources: source,", "name self.location = None self.msgs = asyncio.Queue() # build dict from Commands collected", "replace the item self.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item", "self.message(f\"No exit with name '{ex_name}'.\") @Command.with_traits(name=\"equip\") def cmd_equip(self, args): \"\"\"Equip an equippable item", "a filter includes or excludes the classes that it tracks\"\"\" WHITELIST = True", "if isinstance(other, CharacterClass): # cycle through each ancestor ancestors = filter(lambda x: isinstance(x,", "location.Exit, char=my_char) # I'm only writing this to avoid a cyclic dependency. for", "proper name, if not already provided if \"classname\" not in namespace: cls.classname =", "entity.remove_cmds(self) except AttributeError: # location was none pass self.location = new_location self.location.add_char(self) #", "in the current locations for entity in new_location.entities: entity.on_enter(self) entity.add_cmds(self) #inventory/item related methods", "location. usage: say [msg] \"\"\" msg = ' '.join(args[1:]) if msg and self.location", "While you can update Command.keywords, avoid doing so. All comparisons are based on", "only writing this to avoid a cyclic dependency. for ex in self.location._exit_list: if", "namespace: cls.frequency = 1 # add a \"command_label\", if not already provided #", "function's name [label] = the type of the command. (Affects help menu.) [filter]", "writing this to avoid a cyclic dependency. for ex in self.location._exit_list: if ex_name", "= cls.command_label cls._local_commands[str(value)] = value # all commands, with the most recent commands", "not # prevent them from getting garbage collected self._include_chars = weakref.WeakSet(include_chars) self._exclude_chars =", "- set characters to be excluded _mode - Filter.WHITELIST or Filter.BLACKLIST if WHITELIST", "commands exposed cls._commands = {} for base in reversed(cls.__mro__): if not isinstance(base, CharacterClass):", "the item is even equippable try: target = item.target except AttributeError: self.message(f\"{item} cannot", "the list return not self._mode.value def include(self, other): \"\"\"Set the filter to return", "= \"Default Character\" # Starting location for this class starting_location = None #", "thus, player will not be available to attack self.location = spawn_location self._parser =", "= util.find(self.inv, name=item_name) if len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item) self.location.inv.add_item(item) elif", "allowed through the filter. Note that _include_chars / _exclude_chars take precedence over the", "is supplied to permit()\"\"\" # check that other is a Character / CharacterClass", "= list(self._include_chars) if self._exclude_chars: data[\"exclude_chars\"] = list(self._exclude_chars) return data class Command(functools.partial): \"\"\"A subclass", "/ ancestors cannot be found in the list return not self._mode.value def include(self,", "default user-input parsers def _join_parser(self, new_name: str): \"\"\"Parser for a newly joined player,", "line.split() cmd_name = args[0] if not cmd_name in self.cmd_dict: self.message(\"Command \\'%s\\' not recognized.\"", "parser for a player. Parses\"\"\" # command is always the first word args", "= None # by default, add a filter that permits all (empty blacklist)", "commands @Command def help(self, args): \"\"\"Show relevant help information for a particular command.", "self.msgs = asyncio.Queue() # build dict from Commands collected by CharacterClass self.cmd_dict =", "name=item_name) if len(found_items) == 1: item = found_items[0][0] self.inv.remove_item(item) self.location.inv.add_item(item) elif len(found_items) >", "elif isinstance(other, Character): if other in self._exclude_chars: self._exclude_chars.remove(other) self._include_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\"", "item_name = \" \".join(args[1::]).lower() # TODO: find a way to provide type=Item found_items", "unequipped [target]: an EquipTarget\"\"\" # test if anything is even equipped # also", "if isinstance(item, inv.ItemStack): self.inv.add_item(item.copy(), item.amount) self.inv.add_item(item, amt) def equip(self, item, from_inv=True): \"\"\"place [item]", "self._classes.add(other) elif isinstance(other, Character): if other in self._include_chars: self._include_chars.remove(other) self._exclude_chars.add(other) else: raise ValueError(\"Expected", "== item_name: found_items.append(item) if len(found_items) == 1: self.unequip(found_items[0].target) elif len(found_items) > 1: #TODO", "propagate the name and source new_cmd.name = self.name new_cmd.label = self.label # note", "type of the command. (Affects help menu.) [filter] = if provided, determine which", "args): \"\"\"Send a message to all players in your current location. usage: say", "all commands is shown. \"\"\" if len(args) < 2: # TODO: cache this", "_exclude_chars - set characters to be excluded _mode - Filter.WHITELIST or Filter.BLACKLIST if", "to_dict(self): \"\"\"returns a pythonic representation of this Filter\"\"\" data = {\"mode\" : self._mode.value}", "item from your inventory.\"\"\" if len(args) < 2: self.message(\"Provide an item to equip.\")", "WHITELIST = _FilterMode.WHITELIST BLACKLIST = _FilterMode.BLACKLIST def __init__(self, mode, classes=(), include_chars=(), exclude_chars=()): \"\"\"initialize", "found in inventory, the command fails. if False, [item] is not removed from", "cmd_use(self, args): \"\"\" Use an item. usage: use [item] [options for item] Options", "from getting garbage collected self._include_chars = weakref.WeakSet(include_chars) self._exclude_chars = weakref.WeakSet(exclude_chars) if isinstance(mode, self._FilterMode):", "list return not self._mode.value def include(self, other): \"\"\"Set the filter to return 'True'", "CharacterClass self.cmd_dict = ShadowDict() for (name, cmd) in self._commands.items(): cmd = cmd.specify(self) #", "self.message(f\"No exit with name '{ex_name}'.\") return if found_exit.interact.permits(self): old_location = self.location new_location =", "the name and doc from the base function self.__name__ = self.func.__name__ self.__doc__ =", "when a player dies\"\"\" self.message(\"You died.\") if self.location is not None: self.location.message(f\"{self} died.\",", "item.add_cmds(self) self.equip_dict[item.target] = item, from_inv # class doesn't have an equip target for", "is set to None and any item at that position is unequipped [target]:", "found_items[0][0] self.location.inv.remove_item(item) self.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name.", "# thus, player will not be available to attack self.location = spawn_location self._parser", "are those classes to be whitelisted/blacklisted [include_chars] are specific characters to be included", "except KeyError: self.message(f\"{type(self)} does not possess\" f\" equip slot '{target}'.\") return equipped, from_inv", "to {target}.\") return def unequip(self, target): \"\"\"updates this character's equip_dict such that the", "hasattr(self, \"_symbol\"): symbol = \"{}#{}\".format(type(self).__name__, util.to_base(id(self), 62)) setattr(self, \"_symbol\", symbol) return self._symbol @classmethod", "using its current parser.\"\"\" if msg: self._parser(msg) def update(self): \"\"\"periodically called method that", "and equipping items self.inv = inv.Inventory() self.equip_dict = inv.EquipTarget.make_dict(*self.equip_slots) # put character in", "writing your own method, just do # util.find(location, ex_name, location.Exit, char=my_char) # I'm", "This module also defines the 'Filter', used for CharacterClass-based permissions systems, and 'Command',", "char in exclude_chars: if char in include_chars: raise ValueError(\"Cannot have character in both", "to permit()\"\"\" # check that other is a Character / CharacterClass if isinstance(other,", "\"label\", and \"field\" are also provided. These fields store player-relevant information that are", "will be propagated. While you can update Command.keywords, avoid doing so. All comparisons", "len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not", "was provided try: self.__doc__ = inspect.cleandoc(self.__doc__) except AttributeError: pass # initialize satellite data", "self._parser = self._command_parser def message(self, msg): \"\"\"send a message to the controller of", "for a player. Parses\"\"\" # command is always the first word args =", "equip target for this item, cannot equip else: self.message(f\"Cannot equip item {item} to", "now try the Character's class other = type(other) if isinstance(other, CharacterClass): # cycle", "help [command] If no command is supplied, a list of all commands is", "found_exit.destination new_location.message(f\"{self} entered.\") self.set_location(new_location) # TODO: only show the exit if a character", "default implementation of functools.partial does not normally support equality for mathematically sound reasons:", "= None self.label = None # by default, add a filter that permits", "filter that permits all (empty blacklist) self.filter = Filter(Filter.BLACKLIST) def __eq__(self, other): \"\"\"Two", "def view(self): \"\"\"return a longer, user-focused depiction of Character\"\"\" if self._name is None:", "util.to_base(id(self), 62)) setattr(self, \"_symbol\", symbol) return self._symbol @classmethod def load(cls, data): name =", "\"\"\"Equip an equippable item from your inventory.\"\"\" if len(args) < 2: self.message(\"Provide an", "import inspect import weakref import asyncio import swampymud.inventory as inv from swampymud import", "players - frequency: how often will new players spawn as this class -", "WHITELIST includes the class Wizard, but Bill the Wizard is in _exclude_chars, Bill", "\"\"\" def __init__(self, *args, **kwargs): \"\"\"initialize a Command like a functools.partial object\"\"\" super().__init__()", "# add the proper name, if not already provided if \"classname\" not in", "add a frequency field, if not already provided if \"frequency\" not in namespace:", "go [exit name] \"\"\" ex_name = \" \".join(args[1:]) # Manually iterating over our", "'Filter', used for CharacterClass-based permissions systems, and 'Command', a wrapper that converts methods", "class, then all the Character's ancestor classes \"\"\" if isinstance(other, Character): if other", "item to Equip [from_inv]: if True, [item] should be removed from inventory first.", "# only send a message if inv has items if inv_msg: self.message(inv_msg) @Command.with_traits(name=\"use\")", "return f\"A nameless {type(self)}\" return f\"{self._name} the {type(self)}\" #location manipulation methods def set_location(self,", "convenience method, '.specify' to derive a new Command from an existing one by", "__init__(self, name=None): super().__init__() self._name = name self.location = None self.msgs = asyncio.Queue() #", "entities # in the current location for entity in self.location.entities: entity.on_exit(self) entity.remove_cmds(self) except", "the mro, to get the list of CharacterClasses in order for cls in", "Commands from this class will be labeled \"Default Commands\" command_label = \"Default Commands\"", "/ CharacterClass if isinstance(other, CharacterClass): if self._mode is Filter.WHITELIST: self._classes.add(other) else: if other", "filter permits it if cmd.filter.permits(self): self.cmd_dict[name] = cmd # because sCommands are not", "character in both include\" \" and exclude\") # store characters in a WeakSet,", "# remove commands from all the entities # in the current location for", "a CharClass nor Character else: return False # the character / ancestors cannot", "class appears to players classname = \"Default Character\" # Starting location for this", "'{item_name}' to pick up.\") @Command def drop(self, args): \"\"\"Drop an item into the", "\"\"\"return a representation of Character\"\"\" if self._name is None: return f\"{type(self).__name__}()\" return f\"{type(self).__name__}(name={self})\"", "already provided # this field is used in creating help menus if \"command_label\"", "are allowed through the filter. if BLACKLIST is selected, only characters whose class", "\" \".join(args[1::]).lower() # search through the items in the equip_dict found_items = []", "you can update Command.keywords, avoid doing so. All comparisons are based on the", "except ValueError: pass self.location = None self._parser = self._dead_parser # default user-input parsers", "self.func.__name__ return self.name def help_entry(self) -> str: \"\"\"return a help message for this", "if len(found_items) == 1: self.equip(found_items[0][0]) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious", "\"command_label\" not in namespace: cls.command_label = f\"{cls} Commands\" # commands that were implemented", "'{target}'.\") return equipped, from_inv = self.equip_dict[target] equipped.on_unequip(self) equipped.remove_cmds(self) self.equip_dict[target] = None # if", "Character\"\"\" if self._name is None: return f\"{type(self).__name__}()\" return f\"{type(self).__name__}(name={self})\" def __str__(self): \"\"\"return the", "item from the environment.\"\"\" if len(args) < 2: self.message(\"Provide an item to pick", "{} # walk the mro, to get the list of CharacterClasses in order", "name = data[\"name\"] if \"name\" in data else None return cls(name) def post_load(self,", "string representation of the equipped items equipped = [] for target, item in", "of CharacterClasses in order for cls in reversed(type(self).__mro__): if isinstance(cls, CharacterClass): sources[cls.command_label] =", "other in self._include_chars: self._include_chars.remove(other) self._exclude_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" f\" received {type(other)}\") def", "= weakref.WeakSet(include_chars) self._exclude_chars = weakref.WeakSet(exclude_chars) if isinstance(mode, self._FilterMode): self._mode = mode elif isinstance(mode,", "in self._classes: self._classes.remove(other) elif isinstance(other, Character): if other in self._exclude_chars: self._exclude_chars.remove(other) self._include_chars.add(other) else:", "through the filter. \"\"\" class _FilterMode(enum.Enum): \"\"\"Enum representing whether a filter includes or", "Command return False def __hash__(self): \"\"\"overriding hash\"\"\" return hash((self.func, self.args, self._keys)) def specify(self,", "are equal, and the (initial) keywords are equal\"\"\" try: return (self.func, self.args, self._keys)", "@Command.with_traits(name=\"inv\") def cmd_inv(self, args): \"\"\"Show your inventory. usage: inv\"\"\" # create a string", "for this class cls._local_commands = {} for value in namespace.values(): if isinstance(value, Command):", "location, updating the previous and new locations as necessary and gathering commands from", "repr(mode)) def permits(self, other): \"\"\"returns True if Character/CharacterClass is allowed in the individual", "\"Filter({!r}, {!r}, {!r}, {!r})\".format( self._mode.value, set(self._classes), set(self._include_chars), set(self._exclude_chars) ) @staticmethod def from_dict(filter_dict): \"\"\"returns", "based on the INITIAL keywords, so changing keywords after initialization is unsupported. \"\"\"", "dictionary in reverse order output = [] while sources: source, names = sources.popitem()", "into comparisons. In addition, this class has a convenience method, '.specify' to derive", "already equipped weapon, unequip it if self.equip_dict[target] is not None: self.unequip(target) item.on_equip(self) item.add_cmds(self)", "name '{ex_name}'.\") return if found_exit.interact.permits(self): old_location = self.location new_location = found_exit.destination new_location.message(f\"{self} entered.\")", "True if Character/CharacterClass is allowed in the individual Character is evaluated first, then", "TODO: find a way to provide type=Item found_items = util.find(self.location, name=item_name) if len(found_items)", "equality operators, we aren't trying to solve an undecidable problem, but just confirm", "set(self._classes), set(self._include_chars), set(self._exclude_chars) ) @staticmethod def from_dict(filter_dict): \"\"\"returns a Filter pythonic representation [filter_dict]\"\"\"", "an item. usage: use [item] [options for item] Options may vary per item.", "character.\") # string-formatting methods def __repr__(self): \"\"\"return a representation of Character\"\"\" if self._name", "target for this item, cannot equip else: self.message(f\"Cannot equip item {item} to {target}.\")", "location? if len(args) < 2: self.message(\"Please specify an item.\") return item_name = args[1]", "self._keys = frozenset(self.keywords.items()) # propagate the name and doc from the base function", "'True' if [other] is supplied to permit()\"\"\" # check that other is a", "= list(self._classes) if self._include_chars: data[\"include_chars\"] = list(self._include_chars) if self._exclude_chars: data[\"exclude_chars\"] = list(self._exclude_chars) return", "permitted through the filter. \"\"\" class _FilterMode(enum.Enum): \"\"\"Enum representing whether a filter includes", "for (name, cmd) in self._commands.items(): cmd = cmd.specify(self) # add command only if", "None self.set_location(loc) self._parser = self._command_parser def _command_parser(self, line: str): \"\"\"The default parser for", "should we call you?\") # set player location to spawn_location, but do not", "def to_dict(self): \"\"\"returns a pythonic representation of this Filter\"\"\" data = {\"mode\" :", "equipped.append(f\"{target}: {item[0]}\") equipped.sort() self.message(\"\\n\".join(equipped)) inv_msg = self.inv.readable() # only send a message if", "supplied, a list of all commands is shown. \"\"\" if len(args) < 2:", "self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find equipped item '{item_name}'.\") @Command def", "by applying additional arguments. If a provided keyword argument conflicts with a prior", "to return 'True' if [other] is supplied to permit()\"\"\" # check that other", "self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to pick up.\")", "if not new_name.isalnum(): self.message(\"Names must be alphanumeric.\") return # TODO: perform some kind", "True, [item] should be removed from inventory first. If item is not found", "'inspect' certain objects self.message(self.location.view()) @Command def say(self, args): \"\"\"Send a message to all", "Character else: return False # the character / ancestors cannot be found in", "Filter(Filter.BLACKLIST) def __eq__(self, other): \"\"\"Two commands are equal iff the base functions are", "return if not new_name.isalnum(): self.message(\"Names must be alphanumeric.\") return # TODO: perform some", "\" \".join(args[1::]).lower() # TODO: find a way to provide type=Item found_items = util.find(self.location,", "location for this class starting_location = None # Commands from this class will", "TODO: cache this or something menu = self.help_menu() self.message(menu) else: name = args[1]", "and 'Command', a wrapper that converts methods into commands that can be invoked", "self.message(f\"No item equipped on target {target}.\") return except KeyError: self.message(f\"{type(self)} does not possess\"", "Character): if other in self._include_chars: self._include_chars.remove(other) self._exclude_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" f\" received", "CharacterClass-based permissions systems, and 'Command', a wrapper that converts methods into commands that", "having the same name? self._name = new_name # move the player to the", "False, [item] is not removed from inventory and will not be returned to", "controller of this character\"\"\" # place a self.msgs.put_nowait(msg) def command(self, msg): \"\"\"issue 'msg'", "'{ex_name}'.\") return if found_exit.interact.permits(self): old_location = self.location new_location = found_exit.destination new_location.message(f\"{self} entered.\") self.set_location(new_location)", "are based on the INITIAL keywords, so changing keywords after initialization is unsupported.", "characters to be included _exclude_chars - set characters to be excluded _mode -", "self._name = new_name # move the player to the actual location they should", "that are NOT factored into comparisons. In addition, this class has a convenience", "Command, the Character must use [name] instead of the function's name [label] =", "self._name is None: return f\"{type(self).__name__}()\" return f\"{type(self).__name__}(name={self})\" def __str__(self): \"\"\"return the Character's name\"\"\"", "self._exclude_chars: self._exclude_chars.remove(other) self._include_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" \" received %s\" % type(other)) def", "\"\"\" # duck test that the item is even equippable try: target =", "bases, namespace): # add the proper name, if not already provided if \"classname\"", "commands from any entities in the location \"\"\" try: self.location.characters.remove(self) # remove commands", "player's equip dict [item]: item to Equip [from_inv]: if True, [item] should be", "true, remove item from inventory # this avoids duplication if from_inv: try: self.inv.remove_item(item)", "AttributeError: self.message(f\"{item} cannot be equipped.\") return if target in self.equip_dict: # check remove_inv,", "Character's ancestor classes \"\"\" if isinstance(other, Character): if other in self._include_chars: return True", "you.\") # if the char can't see or interact with the exit, #", "= ex break else: self.message(f\"No exit with name '{ex_name}'.\") return if found_exit.interact.permits(self): old_location", "is used in creating help menus if \"command_label\" not in namespace: cls.command_label =", "as a blacklist [classes] are those classes to be whitelisted/blacklisted [include_chars] are specific", "the command fails. if False, [item] is not removed from inventory and will", "the character and put them into a name-selection mode. [spawn_location]: where the character", "import ShadowDict class Filter: \"\"\"Filter for screening out certain CharacterClasses and Characters _classes", "like a functools.partial object\"\"\" super().__init__() # creating an immutable set of keywords for", "classname = \"Default Character\" # Starting location for this class starting_location = None", "self._keys) == \\ (other.func, other.args, other._keys) except AttributeError: # other is not a", "if str(item).lower() == item_name: found_items.append(item) if len(found_items) == 1: self.unequip(found_items[0].target) elif len(found_items) >", "our SwampyMud! You are a {type(self)}\") self.message(f\"What should we call you?\") # set", "other): \"\"\"Two commands are equal iff the base functions are equal, the args", "died\"\"\" self.message(\"You have died. Reconnect to this server to start\" \" as a", "_classes. That is, if a WHITELIST includes the class Wizard, but Bill the", "may vary per item. \"\"\" # TODO: allow players to use accessible items", "mode, classes=(), include_chars=(), exclude_chars=()): \"\"\"initialize a Filter with [mode] if [mode] is True,", "decorator class CharacterClass(type): \"\"\"metaclass establishing basic Character behaviors CharacterClasses include the following important", "to invoke this Command, the Character must use [name] instead of the function's", "return f\"{self}:\\n{self.__doc__}\" @staticmethod def with_traits(name: str = None, label: str = None, filter:", "location. usage: go [exit name] \"\"\" ex_name = \" \".join(args[1:]) # Manually iterating", "# put character in default command parsing mode self._parser = self._command_parser def message(self,", "order for cls in reversed(type(self).__mro__): if isinstance(cls, CharacterClass): sources[cls.command_label] = [] for name,", "only characters whose class is in _classes are allowed through the filter. if", "a self.msgs.put_nowait(msg) def command(self, msg): \"\"\"issue 'msg' to character. character will parse 'msg'", "this server to start\" \" as a new character.\") # string-formatting methods def", "equip_data is None: continue item, _ = equip_data if str(item).lower() == item_name: found_items.append(item)", "specify an item.\") return item_name = args[1] found_items = util.find(self.inv, name=item_name) if len(found_items)", "command. usage: help [command] If no command is supplied, a list of all", "in _classes are allowed through the filter. if BLACKLIST is selected, only characters", "= None self.msgs = asyncio.Queue() # build dict from Commands collected by CharacterClass", "already provided if \"frequency\" not in namespace: cls.frequency = 1 # add a", "if self._name is None: return f\"A nameless {type(self)}\" return f\"{self._name} the {type(self)}\" #location", "= filter(lambda x: isinstance(x, CharacterClass), other.__mro__) for char_class in ancestors: if char_class in", "in a WeakSet, so that the Filter will not # prevent them from", "them # thus, player will not be available to attack self.location = spawn_location", "appears to the players - frequency: how often will new players spawn as", "for item] Options may vary per item. \"\"\" # TODO: allow players to", "except AttributeError: self.message(f\"{item} cannot be equipped.\") return if target in self.equip_dict: # check", "\\'%s\\' not recognized.\" % cmd_name) return cmd = self.cmd_dict[cmd_name] cmd(args) def _dead_parser(self, line:", "the following important attributes: - classname: how the class appears to the players", "not find item '{item_name}' to pick up.\") @Command def drop(self, args): \"\"\"Drop an", "[target] # in its equip slots try: if self.equip_dict[target] is None: self.message(f\"No item", "when a character has died\"\"\" self.message(\"You have died. Reconnect to this server to", "none pass self.location = new_location self.location.add_char(self) # add commands from all the entities", "cache this or something menu = self.help_menu() self.message(menu) else: name = args[1] try:", "unequip. \"\"\" # duck test that the item is even equippable try: target", "= found_items[0][0] self.inv.remove_item(item) item.on_use(self, args[2:]) # replace the item self.inv.add_item(item) elif len(found_items) >", "to provide type=Item found_items = util.find(self.location, name=item_name) if len(found_items) == 1: item =", "the class Wizard, but Bill the Wizard is in _exclude_chars, Bill will not", "sCommands are not bound properly like a normal # method, we must manually", "def command(self, msg): \"\"\"issue 'msg' to character. character will parse 'msg' using its", "isinstance(item, inv.ItemStack): self.inv.add_item(item.copy(), item.amount) self.inv.add_item(item, amt) def equip(self, item, from_inv=True): \"\"\"place [item] in", "else: self.message(f\"Could not find item '{item_name}' to drop.\") @Command.with_traits(name=\"inv\") def cmd_inv(self, args): \"\"\"Show", "inv_msg = self.inv.readable() # only send a message if inv has items if", "return data class Command(functools.partial): \"\"\"A subclass of functools.partial that supports equality. The default", "look \"\"\" # TODO: update to allow players to 'inspect' certain objects self.message(self.location.view())", "tracks\"\"\" WHITELIST = True BLACKLIST = False WHITELIST = _FilterMode.WHITELIST BLACKLIST = _FilterMode.BLACKLIST", "includes the class Wizard, but Bill the Wizard is in _exclude_chars, Bill will", "use accessible items in location? if len(args) < 2: self.message(\"Please specify an item.\")", "the super init super().__init__(name, bases, namespace) def __str__(cls): \"\"\"overriding str to return classname\"\"\"", "add commands from all the entities # in the current locations for entity", "\"\"\"sets location, updating the previous and new locations as necessary and gathering commands", "the location \"\"\" try: self.location.characters.remove(self) # remove commands from all the entities #", "= self.keywords.copy() keywords.update(new_keywords) new_cmd = Command(self.func, *args, **keywords) # propagate the name and", "def message(self, msg): \"\"\"send a message to the controller of this character\"\"\" #", "if someone forgets to set self._symbol in the __init__ if not hasattr(self, \"_symbol\"):", "self._parser = self._join_parser def despawn(self): \"\"\"method executed when a player dies\"\"\" self.message(\"You died.\")", "< 2: self.message(\"Provide an item to drop.\") return item_name = \" \".join(args[1:]).lower() found_items", "the function's name [label] = the type of the command. (Affects help menu.)", "set(self._exclude_chars) ) @staticmethod def from_dict(filter_dict): \"\"\"returns a Filter pythonic representation [filter_dict]\"\"\" return Filter(**filter_dict)", "CharacterClass): if self._mode == Filter.WHITELIST: if other in self._classes: self._classes.remove(other) else: self._classes.add(other) elif", "functools.partial object\"\"\" super().__init__() # creating an immutable set of keywords for comparisons self._keys", "that the [target] is set to None and any item at that position", "and pretend like it doesn't exist else: self.message(f\"No exit with name '{ex_name}'.\") @Command.with_traits(name=\"equip\")", "CharacterClass): sources[cls.command_label] = [] for name, cmd in self.cmd_dict.items(): try: sources[cmd.label].append(name) except KeyError:", "@Command def help(self, args): \"\"\"Show relevant help information for a particular command. usage:", "self._parser = self._dead_parser # default user-input parsers def _join_parser(self, new_name: str): \"\"\"Parser for", "through the items in the equip_dict found_items = [] for _, equip_data in", "pythonic representation of this Character\"\"\" return {\"_type\": type(self), \"name\": self._name} def children(self): \"\"\"pass\"\"\"", "filter. Note that _include_chars / _exclude_chars take precedence over the _classes. That is,", "self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}'.\") @Command.with_traits(name=\"unequip\") def cmd_unequip(self,", "used for selecting a valid name\"\"\" if len(new_name) < 2: self.message(\"Names must have", "a character can see it? old_location.message(f\"{self} left through exit \" f\"'{ex_name}'.\") else: if", "ValueError(\"Unrecognized mode %s\" % repr(mode)) def permits(self, other): \"\"\"returns True if Character/CharacterClass is", "ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to use.\")", "cannot be equipped.\") return if target in self.equip_dict: # check remove_inv, if true,", "drop.\") @Command.with_traits(name=\"inv\") def cmd_inv(self, args): \"\"\"Show your inventory. usage: inv\"\"\" # create a", "the environment.\"\"\" if len(args) < 2: self.message(\"Provide an item to pick up.\") return", "equipped.append(f\"{target}: none\") else: equipped.append(f\"{target}: {item[0]}\") equipped.sort() self.message(\"\\n\".join(equipped)) inv_msg = self.inv.readable() # only send", "it if from_inv: self.inv.add_item(equipped) # default commands @Command def help(self, args): \"\"\"Show relevant", "from_inv # class doesn't have an equip target for this item, cannot equip", "cmd_inv(self, args): \"\"\"Show your inventory. usage: inv\"\"\" # create a string representation of", "cmd # because sCommands are not bound properly like a normal # method,", "\"\"\"method executed when a player dies\"\"\" self.message(\"You died.\") if self.location is not None:", "f\"'{ex_name}'.\") else: if found_exit.perceive.permits(self): self.message(f\"Exit '{ex_name}' is inaccessible to you.\") # if the", "command is always the first word args = line.split() cmd_name = args[0] if", "# add command only if filter permits it if cmd.filter.permits(self): self.cmd_dict[name] = cmd", "With this class's equality operators, we aren't trying to solve an undecidable problem,", "the filter to return 'True' if [other] is supplied to permit()\"\"\" # check", "__init__ if not hasattr(self, \"_symbol\"): symbol = \"{}#{}\".format(type(self).__name__, util.to_base(id(self), 62)) setattr(self, \"_symbol\", symbol)", "easily wrap a function additional traits [name] = to invoke this Command, the", "the player to the actual location they should be in loc = self.location", "other is a Character / CharacterClass if isinstance(other, CharacterClass): if self._mode == Filter.WHITELIST:", "self._parser = self._command_parser def _command_parser(self, line: str): \"\"\"The default parser for a player.", "NOT factored into comparisons. In addition, this class has a convenience method, '.specify'", "a player. Parses\"\"\" # command is always the first word args = line.split()", "def with_traits(name: str = None, label: str = None, filter: Filter = None):", "def __hash__(self): \"\"\"overriding hash\"\"\" return hash((self.func, self.args, self._keys)) def specify(self, *newargs, **new_keywords) ->", "is in _classes are allowed through the filter. if BLACKLIST is selected, only", "name-selection mode. [spawn_location]: where the character should spawn after a name is submitted.", "entities in the location \"\"\" try: self.location.characters.remove(self) # remove commands from all the", "in your current location. usage: say [msg] \"\"\" msg = ' '.join(args[1:]) if", "to use this command. \"\"\" def decorator(func): cmd = Command(func) cmd.name = name", "anything is even equipped # also duck test to see if this character", "is a Character / CharacterClass if isinstance(other, CharacterClass): if self._mode == Filter.WHITELIST: if", "of Character\"\"\" if self._name is None: return f\"A nameless {type(self)}\" return f\"{self._name} the", "{msg}\") @Command def go(self, args): \"\"\"Go to an accessible location. usage: go [exit", "command only if filter permits it if cmd.filter.permits(self): self.cmd_dict[name] = cmd # because", "None): \"\"\"decorator to easily wrap a function additional traits [name] = to invoke", "_FilterMode(enum.Enum): \"\"\"Enum representing whether a filter includes or excludes the classes that it", "if self._exclude_chars: data[\"exclude_chars\"] = list(self._exclude_chars) return data class Command(functools.partial): \"\"\"A subclass of functools.partial", "which serves as the basis for all in-game characters. This module also defines", "self.location.add_char(self) # add commands from all the entities # in the current locations", "classname: how the class appears to the players - frequency: how often will", "Bill will not be permitted through the filter. \"\"\" class _FilterMode(enum.Enum): \"\"\"Enum representing", "include_chars: if char in exclude_chars: raise ValueError(\"Cannot have character in both include\" \"", "must be alphanumeric.\") return # TODO: perform some kind of check to prevent", "in self._include_chars: self._include_chars.remove(other) self._exclude_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" f\" received {type(other)}\") def __repr__(self):", "\"Default Commands\" # Valid equip slots for characters of this class equip_slots =", "# How this class appears to players classname = \"Default Character\" # Starting", "name and source new_cmd.name = self.name new_cmd.label = self.label # note that a", "self._classes = set(classes) for char in include_chars: if char in exclude_chars: raise ValueError(\"Cannot", "\".join(args[1::]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: self.equip(found_items[0][0]) elif len(found_items) >", "= self.args + tuple(newargs) keywords = self.keywords.copy() keywords.update(new_keywords) new_cmd = Command(self.func, *args, **keywords)", "item into the environment\"\"\" if len(args) < 2: self.message(\"Provide an item to drop.\")", "else: return False # the character / ancestors cannot be found in the", "in self._commands.items(): cmd = cmd.specify(self) # add command only if filter permits it", "and the (initial) keywords are equal\"\"\" try: return (self.func, self.args, self._keys) == \\", "KeyError: self.message(f\"Cannot equip {item}-\" \"not found in inventory.\") return # check for an", "item.\") return item_name = args[1] found_items = util.find(self.inv, name=item_name) if len(found_items) == 1:", "found_exit.perceive.permits(self): self.message(f\"Exit '{ex_name}' is inaccessible to you.\") # if the char can't see", "can't see or interact with the exit, # we lie to them and", "doesn't exist else: self.message(f\"No exit with name '{ex_name}'.\") @Command.with_traits(name=\"equip\") def cmd_equip(self, args): \"\"\"Equip", "to be excluded _mode - Filter.WHITELIST or Filter.BLACKLIST if WHITELIST is selected, only", "% cmd_name) return cmd = self.cmd_dict[cmd_name] cmd(args) def _dead_parser(self, line: str): \"\"\"Parser used", "\"\"\"Set the filter to return 'True' if [other] is supplied to permit()\"\"\" #", "self.__doc__ = inspect.cleandoc(self.__doc__) except AttributeError: pass # initialize satellite data self.name = None", "_include_chars / _exclude_chars take precedence over the _classes. That is, if a WHITELIST", "name\"\"\" if self._name: return self._name return \"[nameless character]\" def view(self): \"\"\"return a longer,", "def despawn(self): \"\"\"method executed when a player dies\"\"\" self.message(\"You died.\") if self.location is", "/ Classes are permitted to use this command. \"\"\" def decorator(func): cmd =", "# walk the mro, to get the list of CharacterClasses in order for", "is even equippable try: target = item.target except AttributeError: self.message(f\"{item} cannot be equipped.\")", "for mathematically sound reasons: https://bugs.python.org/issue3564 With this class's equality operators, we aren't trying", "try: self.__doc__ = inspect.cleandoc(self.__doc__) except AttributeError: pass # initialize satellite data self.name =", "repr()\"\"\" return \"Filter({!r}, {!r}, {!r}, {!r})\".format( self._mode.value, set(self._classes), set(self._include_chars), set(self._exclude_chars) ) @staticmethod def", "msg): \"\"\"issue 'msg' to character. character will parse 'msg' using its current parser.\"\"\"", "filter includes or excludes the classes that it tracks\"\"\" WHITELIST = True BLACKLIST", "be equipped.\") return if target in self.equip_dict: # check remove_inv, if true, remove", "self.message(\"Command \\'%s\\' not recognized.\" % cmd_name) return cmd = self.cmd_dict[cmd_name] cmd(args) def _dead_parser(self,", "equipped.\") return if target in self.equip_dict: # check remove_inv, if true, remove item", "'{name}' not recognized.\") @Command def look(self, args): \"\"\"Gives a description of your current", "equippable try: target = item.target except AttributeError: self.message(f\"{item} cannot be equipped.\") return if", "Filter.WHITELIST: if other in self._classes: self._classes.remove(other) else: self._classes.add(other) elif isinstance(other, Character): if other", "to an accessible location. usage: go [exit name] \"\"\" ex_name = \" \".join(args[1:])", "mode self._parser = self._command_parser def message(self, msg): \"\"\"send a message to the controller", "equipped, from_inv = self.equip_dict[target] equipped.on_unequip(self) equipped.remove_cmds(self) self.equip_dict[target] = None # if item was", "ValueError(\"Cannot have character in both include\" \" and exclude\") # store characters in", "# \"other\" is neither a CharClass nor Character else: return False # the", "mode elif isinstance(mode, bool): if mode: self._mode = Filter.WHITELIST else: self._mode = Filter.BLACKLIST", "else: if found_exit.perceive.permits(self): self.message(f\"Exit '{ex_name}' is inaccessible to you.\") # if the char", "usage: help [command] If no command is supplied, a list of all commands", "the classes that it tracks\"\"\" WHITELIST = True BLACKLIST = False WHITELIST =", "prevent players # from having the same name? self._name = new_name # move", "a message to the controller of this character\"\"\" # place a self.msgs.put_nowait(msg) def", "slots try: if self.equip_dict[target] is None: self.message(f\"No item equipped on target {target}.\") return", "str): \"\"\"Parser for a newly joined player, used for selecting a valid name\"\"\"", "other): \"\"\"returns True if Character/CharacterClass is allowed in the individual Character is evaluated", "current location for entity in self.location.entities: entity.on_exit(self) entity.remove_cmds(self) except AttributeError: # location was", "new Command from an existing one by simply adding additional arguments. All other", "@Command def pickup(self, args): \"\"\"Pick up item from the environment.\"\"\" if len(args) <", "def drop(self, args): \"\"\"Drop an item into the environment\"\"\" if len(args) < 2:", "Filter.WHITELIST else: self._mode = Filter.BLACKLIST else: if mode.lower() == \"whitelist\": self._mode = Filter.WHITELIST", "message to the controller of this character\"\"\" # place a self.msgs.put_nowait(msg) def command(self,", "Bill the Wizard is in _exclude_chars, Bill will not be permitted through the", "Characters / Classes are permitted to use this command. \"\"\" def decorator(func): cmd", "provided try: self.__doc__ = inspect.cleandoc(self.__doc__) except AttributeError: pass # initialize satellite data self.name", "the item is an ItemStack, unpack it first if isinstance(item, inv.ItemStack): self.inv.add_item(item.copy(), item.amount)", "the filter. Note that _include_chars / _exclude_chars take precedence over the _classes. That", "@classmethod def load(cls, data): name = data[\"name\"] if \"name\" in data else None", "in loc = self.location self.location = None self.set_location(loc) self._parser = self._command_parser def _command_parser(self,", "(name, cmd) in self._commands.items(): cmd = cmd.specify(self) # add command only if filter", "players to use accessible items in location? if len(args) < 2: self.message(\"Please specify", "found in the list return not self._mode.value def include(self, other): \"\"\"Set the filter", "str to return classname\"\"\" return cls.classname class Character(metaclass=CharacterClass): \"\"\"Base class for all other", "command is supplied, a list of all commands is shown. \"\"\" if len(args)", "\"\"\"Drop an item into the environment\"\"\" if len(args) < 2: self.message(\"Provide an item", "to return 'False' if [other] is supplied to permit()\"\"\" # check that other", "a new character.\") # string-formatting methods def __repr__(self): \"\"\"return a representation of Character\"\"\"", "Character / CharacterClass if isinstance(other, CharacterClass): if self._mode is Filter.WHITELIST: self._classes.add(other) else: if", "inventory.\"\"\" if len(args) < 2: self.message(\"Provide an item to equip.\") return item_name =", "item in self.equip_dict.items(): if item is None: equipped.append(f\"{target}: none\") else: equipped.append(f\"{target}: {item[0]}\") equipped.sort()", "# cycle through each ancestor ancestors = filter(lambda x: isinstance(x, CharacterClass), other.__mro__) for", "else: raise ValueError(\"Expected Character/CharacterClass,\" \" received %s\" % type(other)) def exclude(self, other): \"\"\"Set", "name '{ex_name}'.\") @Command.with_traits(name=\"equip\") def cmd_equip(self, args): \"\"\"Equip an equippable item from your inventory.\"\"\"", "self._mode = Filter.BLACKLIST else: raise ValueError(\"Unrecognized mode %s\" % repr(mode)) def permits(self, other):", "return # check for an already equipped weapon, unequip it if self.equip_dict[target] is", "return \"[nameless character]\" def view(self): \"\"\"return a longer, user-focused depiction of Character\"\"\" if", "not removed from inventory and will not be returned to inventory upon unequip.", "it if self.equip_dict[target] is not None: self.unequip(target) item.on_equip(self) item.add_cmds(self) self.equip_dict[item.target] = item, from_inv", "return item_name = \" \".join(args[1:]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items) == 1:", "the actual location they should be in loc = self.location self.location = None", "same arguments and underlying functions. Optional fields, \"name\", \"label\", and \"field\" are also", "be invoked by characters. \"\"\" import enum import functools import inspect import weakref", "\"\"\"Show your inventory. usage: inv\"\"\" # create a string representation of the equipped", "selected, only characters whose class is NOT in _classes are allowed through the", "items in location? if len(args) < 2: self.message(\"Please specify an item.\") return item_name", "basis for all in-game characters. This module also defines the 'Filter', used for", "[options for item] Options may vary per item. \"\"\" # TODO: allow players", "etc.) will be propagated. While you can update Command.keywords, avoid doing so. All", "to our SwampyMud! You are a {type(self)}\") self.message(f\"What should we call you?\") #", "**new_keywords) -> 'Command': \"\"\"Derive a new version of this function by applying additional", "a Character / CharacterClass if isinstance(other, CharacterClass): if self._mode is Filter.WHITELIST: self._classes.add(other) else:", "str(item).lower() == item_name: found_items.append(item) if len(found_items) == 1: self.unequip(found_items[0].target) elif len(found_items) > 1:", "entity.add_cmds(self) #inventory/item related methods def add_item(self, item, amt=1): \"\"\"add [item] to player's inventory\"\"\"", "spawn as this class - command_label: how commands from this class appear in", "swampymud.inventory as inv from swampymud import util from swampymud.util.shadowdict import ShadowDict class Filter:", "list(self._classes) if self._include_chars: data[\"include_chars\"] = list(self._include_chars) if self._exclude_chars: data[\"exclude_chars\"] = list(self._exclude_chars) return data", "in ex.names: found_exit = ex break else: self.message(f\"No exit with name '{ex_name}'.\") return", "command_label = \"Default Commands\" # Valid equip slots for characters of this class", "self._commands.items(): cmd = cmd.specify(self) # add command only if filter permits it if", "if len(args) < 2: self.message(\"Provide an item to drop.\") return item_name = \"", "for this Character\"\"\" # failsafe to ensure that Character always has a symbol", "elif isinstance(mode, bool): if mode: self._mode = Filter.WHITELIST else: self._mode = Filter.BLACKLIST else:", "= type(other) if isinstance(other, CharacterClass): # cycle through each ancestor ancestors = filter(lambda", "class for all other CharacterClasses\"\"\" # How this class appears to players classname", "source, names = sources.popitem() output.append(f\"---{source}---\") output.append(\" \".join(names)) return \"\\n\".join(output) # serialization-related methods @property", "be permitted through the filter. \"\"\" class _FilterMode(enum.Enum): \"\"\"Enum representing whether a filter", "relevant help information for a particular command. usage: help [command] If no command", "drop.\") return item_name = \" \".join(args[1:]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items) ==", "else: self.message(f\"No exit with name '{ex_name}'.\") @Command.with_traits(name=\"equip\") def cmd_equip(self, args): \"\"\"Equip an equippable", "includes or excludes the classes that it tracks\"\"\" WHITELIST = True BLACKLIST =", "that Character always has a symbol # even if someone forgets to set", "Filter will act as a blacklist [classes] are those classes to be whitelisted/blacklisted", "return item_name = \" \".join(args[1::]).lower() # search through the items in the equip_dict", "see or interact with the exit, # we lie to them and pretend", "any changes to the # old NewCommand will change to the old Command,", "2: # TODO: cache this or something menu = self.help_menu() self.message(menu) else: name", "self._mode.value def include(self, other): \"\"\"Set the filter to return 'True' if [other] is", "the # old NewCommand will change to the old Command, and visa versa", "def cmd_inv(self, args): \"\"\"Show your inventory. usage: inv\"\"\" # create a string representation", "Note! If writing your own method, just do # util.find(location, ex_name, location.Exit, char=my_char)", "behaviors CharacterClasses include the following important attributes: - classname: how the class appears", "location to spawn_location, but do not MOVE them # thus, player will not", "players classname = \"Default Character\" # Starting location for this class starting_location =", "also provided. These fields store player-relevant information that are NOT factored into comparisons.", "self.inv.remove_item(item) self.location.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\")", "self._keys)) def specify(self, *newargs, **new_keywords) -> 'Command': \"\"\"Derive a new version of this", "to attack self.location = spawn_location self._parser = self._join_parser def despawn(self): \"\"\"method executed when", "the {type(self)}\" #location manipulation methods def set_location(self, new_location): \"\"\"sets location, updating the previous", "attributes: - classname: how the class appears to the players - frequency: how", "commands are equal iff the base functions are equal, the args are equal,", "self.message(\"You died.\") if self.location is not None: self.location.message(f\"{self} died.\", exclude={self}) try: self.location.characters.remove(self) except", "item to pick up.\") return item_name = \" \".join(args[1::]).lower() # TODO: find a", "# all commands, with the most recent commands exposed cls._commands = {} for", "a particular command. usage: help [command] If no command is supplied, a list", "None: self.unequip(target) item.on_equip(self) item.add_cmds(self) self.equip_dict[item.target] = item, from_inv # class doesn't have an", "name] \"\"\" ex_name = \" \".join(args[1:]) # Manually iterating over our location's list", "self._name: return self._name return \"[nameless character]\" def view(self): \"\"\"return a longer, user-focused depiction", "\"command_label\", if not already provided # this field is used in creating help", "a help message for this command\"\"\" if self.label is not None: return f\"{self}", "cannot equip else: self.message(f\"Cannot equip item {item} to {target}.\") return def unequip(self, target):", "are equal iff the base functions are equal, the args are equal, and", "alphanumeric.\") return # TODO: perform some kind of check to prevent players #", "permits all (empty blacklist) self.filter = Filter(Filter.BLACKLIST) def __eq__(self, other): \"\"\"Two commands are", "nor Character else: return False # the character / ancestors cannot be found", "found in inventory.\") return # check for an already equipped weapon, unequip it", "from swampymud import util from swampymud.util.shadowdict import ShadowDict class Filter: \"\"\"Filter for screening", "the [target] is set to None and any item at that position is", "if msg and self.location is not None: self.location.message(f\"{self.view()}: {msg}\") @Command def go(self, args):", "to 'inspect' certain objects self.message(self.location.view()) @Command def say(self, args): \"\"\"Send a message to", "an undecidable problem, but just confirm that two partially-applied functions have the same", "build dict from Commands collected by CharacterClass self.cmd_dict = ShadowDict() for (name, cmd)", "environment.\"\"\" if len(args) < 2: self.message(\"Provide an item to pick up.\") return item_name", "[filter_dict]\"\"\" return Filter(**filter_dict) def to_dict(self): \"\"\"returns a pythonic representation of this Filter\"\"\" data", "names = sources.popitem() output.append(f\"---{source}---\") output.append(\" \".join(names)) return \"\\n\".join(output) # serialization-related methods @property def", "Results={found_items}\") else: self.message(f\"Could not find item '{item_name}'.\") @Command.with_traits(name=\"unequip\") def cmd_unequip(self, args): \"\"\"Unequip an", "@staticmethod def with_traits(name: str = None, label: str = None, filter: Filter =", "self.inv.add_item(item, amt) def equip(self, item, from_inv=True): \"\"\"place [item] in this player's equip dict", "# old NewCommand will change to the old Command, and visa versa new_cmd.filter", "not find item '{item_name}' to use.\") # miscellaneous methods def help_menu(self) -> str:", "swampymud import util from swampymud.util.shadowdict import ShadowDict class Filter: \"\"\"Filter for screening out", "them into a name-selection mode. [spawn_location]: where the character should spawn after a", "def help(self, args): \"\"\"Show relevant help information for a particular command. usage: help", "< 2: self.message(\"Please specify an item.\") return item_name = args[1] found_items = util.find(self.inv,", "if mode: self._mode = Filter.WHITELIST else: self._mode = Filter.BLACKLIST else: if mode.lower() ==", "self.location new_location = found_exit.destination new_location.message(f\"{self} entered.\") self.set_location(new_location) # TODO: only show the exit", "= Filter.WHITELIST elif mode.lower() == \"blacklist\": self._mode = Filter.BLACKLIST else: raise ValueError(\"Unrecognized mode", "adding additional arguments. All other information (base function, names, etc.) will be propagated.", "= new_location self.location.add_char(self) # add commands from all the entities # in the", "to return classname\"\"\" return cls.classname class Character(metaclass=CharacterClass): \"\"\"Base class for all other CharacterClasses\"\"\"", "a character has died\"\"\" self.message(\"You have died. Reconnect to this server to start\"", "if other in self._exclude_chars: self._exclude_chars.remove(other) self._include_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" \" received %s\"", "[item]: item to Equip [from_inv]: if True, [item] should be removed from inventory", "# default commands @Command def help(self, args): \"\"\"Show relevant help information for a", "Character/CharacterClass,\" f\" received {type(other)}\") def __repr__(self): \"\"\"overriding repr()\"\"\" return \"Filter({!r}, {!r}, {!r}, {!r})\".format(", "msg: self._parser(msg) def update(self): \"\"\"periodically called method that updates character state\"\"\" print(f\"[{self}] received", "return 'True' if [other] is supplied to permit()\"\"\" # check that other is", "def update(self): \"\"\"periodically called method that updates character state\"\"\" print(f\"[{self}] received update\") def", "of this Character\"\"\" return {\"_type\": type(self), \"name\": self._name} def children(self): \"\"\"pass\"\"\" return []", "not hasattr(self, \"_symbol\"): symbol = \"{}#{}\".format(type(self).__name__, util.to_base(id(self), 62)) setattr(self, \"_symbol\", symbol) return self._symbol", "inventory\"\"\" # if the item is an ItemStack, unpack it first if isinstance(item,", "equip_dict such that the [target] is set to None and any item at", "the dictionary in reverse order output = [] while sources: source, names =", "self._exclude_chars.remove(other) self._include_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" \" received %s\" % type(other)) def exclude(self,", "cmd) in self._commands.items(): cmd = cmd.specify(self) # add command only if filter permits", "supports equality. The default implementation of functools.partial does not normally support equality for", "\"\"\"return a help message for this command\"\"\" if self.label is not None: return", "= self.cmd_dict[cmd_name] cmd(args) def _dead_parser(self, line: str): \"\"\"Parser used when a character has", ": self._mode.value} if self._classes: data[\"classes\"] = list(self._classes) if self._include_chars: data[\"include_chars\"] = list(self._include_chars) if", "or something menu = self.help_menu() self.message(menu) else: name = args[1] try: self.message(self.cmd_dict[name].help_entry()) except", "isinstance(mode, bool): if mode: self._mode = Filter.WHITELIST else: self._mode = Filter.BLACKLIST else: if", "return # TODO: perform some kind of check to prevent players # from", "Results={found_items}\") else: self.message(f\"Could not find equipped item '{item_name}'.\") @Command def pickup(self, args): \"\"\"Pick", "def __str__(cls): \"\"\"overriding str to return classname\"\"\" return cls.classname class Character(metaclass=CharacterClass): \"\"\"Base class", "labeled \"Default Commands\" command_label = \"Default Commands\" # Valid equip slots for characters", "# Starting location for this class starting_location = None # Commands from this", "died.\", exclude={self}) try: self.location.characters.remove(self) except ValueError: pass self.location = None self._parser = self._dead_parser", "and new locations as necessary and gathering commands from any entities in the", "else: if other in self._classes: self._classes.remove(other) elif isinstance(other, Character): if other in self._exclude_chars:", "% repr(mode)) def permits(self, other): \"\"\"returns True if Character/CharacterClass is allowed in the", "cmd_name) return cmd = self.cmd_dict[cmd_name] cmd(args) def _dead_parser(self, line: str): \"\"\"Parser used when", "equality. The default implementation of functools.partial does not normally support equality for mathematically", "[target]: an EquipTarget\"\"\" # test if anything is even equipped # also duck", "add a filter that permits all (empty blacklist) self.filter = Filter(Filter.BLACKLIST) def __eq__(self,", "import swampymud.inventory as inv from swampymud import util from swampymud.util.shadowdict import ShadowDict class", "handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}'.\") @Command.with_traits(name=\"unequip\")", "that two partially-applied functions have the same arguments and underlying functions. Optional fields,", "CharClass nor Character else: return False # the character / ancestors cannot be", "- classname: how the class appears to the players - frequency: how often", "if not already provided # this field is used in creating help menus", "the old Command, and visa versa new_cmd.filter = self.filter return new_cmd def __str__(self):", "ensure that Character always has a symbol # even if someone forgets to", "__repr__(self): \"\"\"return a representation of Character\"\"\" if self._name is None: return f\"{type(self).__name__}()\" return", "other in self._exclude_chars: return False # now try the Character's class other =", "characters to be excluded \"\"\" self._classes = set(classes) for char in include_chars: if", "isinstance(mode, self._FilterMode): self._mode = mode elif isinstance(mode, bool): if mode: self._mode = Filter.WHITELIST", "return item_name = args[1] found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: item", "both include\" \" and exclude\") for char in exclude_chars: if char in include_chars:", "self.inv.readable() # only send a message if inv has items if inv_msg: self.message(inv_msg)", "an equippable item from your inventory.\"\"\" if len(args) < 2: self.message(\"Provide an item", "Usage: unequip [item]\"\"\" if len(args) < 2: self.message(\"Provide an item to equip.\") return", "asyncio import swampymud.inventory as inv from swampymud import util from swampymud.util.shadowdict import ShadowDict", "always has a symbol # even if someone forgets to set self._symbol in", "# in its equip slots try: if self.equip_dict[target] is None: self.message(f\"No item equipped", "(other.func, other.args, other._keys) except AttributeError: # other is not a Command return False", "if provided, determine which Characters / Classes are permitted to use this command.", "depiction of Character\"\"\" if self._name is None: return f\"A nameless {type(self)}\" return f\"{self._name}", "'{ex_name}'.\") @Command.with_traits(name=\"equip\") def cmd_equip(self, args): \"\"\"Equip an equippable item from your inventory.\"\"\" if", "default, add a filter that permits all (empty blacklist) self.filter = Filter(Filter.BLACKLIST) def", "while sources: source, names = sources.popitem() output.append(f\"---{source}---\") output.append(\" \".join(names)) return \"\\n\".join(output) # serialization-related", "Commands\" command_label = \"Default Commands\" # Valid equip slots for characters of this", "else: self.message(f\"Could not find equipped item '{item_name}'.\") @Command def pickup(self, args): \"\"\"Pick up", "equal, the args are equal, and the (initial) keywords are equal\"\"\" try: return", "else: self._mode = Filter.BLACKLIST else: if mode.lower() == \"whitelist\": self._mode = Filter.WHITELIST elif", "to derive a new Command from an existing one by simply adding additional", "the methods # TODO: override getattribute__ to solve the super() issue? if isinstance(getattr(self,", "is not found in inventory, the command fails. if False, [item] is not", "_, equip_data in self.equip_dict.items(): if equip_data is None: continue item, _ = equip_data", "classes to be whitelisted/blacklisted [include_chars] are specific characters to be included [exclude_chars] are", "> 1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find", "\"\"\"Gives a description of your current location. usage: look \"\"\" # TODO: update", "to drop.\") @Command.with_traits(name=\"inv\") def cmd_inv(self, args): \"\"\"Show your inventory. usage: inv\"\"\" # create", "How this class appears to players classname = \"Default Character\" # Starting location", "in reverse order output = [] while sources: source, names = sources.popitem() output.append(f\"---{source}---\")", "char in include_chars: raise ValueError(\"Cannot have character in both include\" \" and exclude\")", "in self.cmd_dict.items(): try: sources[cmd.label].append(name) except KeyError: sources[cmd.label] = [name] # unpack the dictionary", "command. (Affects help menu.) [filter] = if provided, determine which Characters / Classes", "args): \"\"\"Equip an equippable item from your inventory.\"\"\" if len(args) < 2: self.message(\"Provide", "information (base function, names, etc.) will be propagated. While you can update Command.keywords,", "TODO: override getattribute__ to solve the super() issue? if isinstance(getattr(self, cmd.func.__name__), Command): setattr(self,", "location \"\"\" try: self.location.characters.remove(self) # remove commands from all the entities # in", "module also defines the 'Filter', used for CharacterClass-based permissions systems, and 'Command', a", "remove item from inventory # this avoids duplication if from_inv: try: self.inv.remove_item(item) #", "self.message(f\"What should we call you?\") # set player location to spawn_location, but do", "to easily wrap a function additional traits [name] = to invoke this Command,", "\"classname\" not in namespace: cls.classname = util.camel_to_space(name) # add a frequency field, if", "cls.classname class Character(metaclass=CharacterClass): \"\"\"Base class for all other CharacterClasses\"\"\" # How this class", "self.msgs.put_nowait(msg) def command(self, msg): \"\"\"issue 'msg' to character. character will parse 'msg' using", "\"\"\" class _FilterMode(enum.Enum): \"\"\"Enum representing whether a filter includes or excludes the classes", "= None # if item was from character's inventory, return it if from_inv:", "prevent them from getting garbage collected self._include_chars = weakref.WeakSet(include_chars) self._exclude_chars = weakref.WeakSet(exclude_chars) if", "died.\") if self.location is not None: self.location.message(f\"{self} died.\", exclude={self}) try: self.location.characters.remove(self) except ValueError:", "# I'm only writing this to avoid a cyclic dependency. for ex in", "value.label = cls.command_label cls._local_commands[str(value)] = value # all commands, with the most recent", "\"\"\"add [item] to player's inventory\"\"\" # if the item is an ItemStack, unpack", "def decorator(func): cmd = Command(func) cmd.name = name cmd.label = label if filter", "self._exclude_chars: return False # now try the Character's class other = type(other) if", "ancestor classes \"\"\" if isinstance(other, Character): if other in self._include_chars: return True elif", "equipped item. Usage: unequip [item]\"\"\" if len(args) < 2: self.message(\"Provide an item to", "\"\"\"initialize a Command like a functools.partial object\"\"\" super().__init__() # creating an immutable set", "= None self._parser = self._dead_parser # default user-input parsers def _join_parser(self, new_name: str):", "Command from an existing one by simply adding additional arguments. All other information", "whose class is NOT in _classes are allowed through the filter. Note that", "that the item is even equippable try: target = item.target except AttributeError: self.message(f\"{item}", "is shown. \"\"\" if len(args) < 2: # TODO: cache this or something", "provided keyword argument conflicts with a prior argument, the prior argument will be", "to use accessible items in location? if len(args) < 2: self.message(\"Please specify an", "character should spawn after a name is submitted. \"\"\" self.message(f\"Welcome to our SwampyMud!", "reversed(type(self).__mro__): if isinstance(cls, CharacterClass): sources[cls.command_label] = [] for name, cmd in self.cmd_dict.items(): try:", "and doc from the base function self.__name__ = self.func.__name__ self.__doc__ = self.func.__doc__ #", "name=None): super().__init__() self._name = name self.location = None self.msgs = asyncio.Queue() # build", "all players in your current location. usage: say [msg] \"\"\" msg = '", "init super().__init__(name, bases, namespace) def __str__(cls): \"\"\"overriding str to return classname\"\"\" return cls.classname", "through the filter. Note that _include_chars / _exclude_chars take precedence over the _classes.", "in self.equip_dict.items(): if item is None: equipped.append(f\"{target}: none\") else: equipped.append(f\"{target}: {item[0]}\") equipped.sort() self.message(\"\\n\".join(equipped))", "return f\"{self._name} the {type(self)}\" #location manipulation methods def set_location(self, new_location): \"\"\"sets location, updating", "this character's equip_dict such that the [target] is set to None and any", "pick up.\") @Command def drop(self, args): \"\"\"Drop an item into the environment\"\"\" if", "%s\" % repr(mode)) def permits(self, other): \"\"\"returns True if Character/CharacterClass is allowed in", "output.append(f\"---{source}---\") output.append(\" \".join(names)) return \"\\n\".join(output) # serialization-related methods @property def symbol(self): \"\"\"return a", "self.location.message(f\"{self.view()}: {msg}\") @Command def go(self, args): \"\"\"Go to an accessible location. usage: go", "equippable item from your inventory.\"\"\" if len(args) < 2: self.message(\"Provide an item to", "class cls._local_commands = {} for value in namespace.values(): if isinstance(value, Command): value.label =", "specify(self, *newargs, **new_keywords) -> 'Command': \"\"\"Derive a new version of this function by", "{} for base in reversed(cls.__mro__): if not isinstance(base, CharacterClass): continue cls._commands.update(base._local_commands) cls._commands.update(cls._local_commands) #", "target {target}.\") return except KeyError: self.message(f\"{type(self)} does not possess\" f\" equip slot '{target}'.\")", "if len(found_items) == 1: self.unequip(found_items[0].target) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious", "_FilterMode.BLACKLIST def __init__(self, mode, classes=(), include_chars=(), exclude_chars=()): \"\"\"initialize a Filter with [mode] if", "include the following important attributes: - classname: how the class appears to the", "by CharacterClass self.cmd_dict = ShadowDict() for (name, cmd) in self._commands.items(): cmd = cmd.specify(self)", "current location. usage: look \"\"\" # TODO: update to allow players to 'inspect'", "len(args) < 2: # TODO: cache this or something menu = self.help_menu() self.message(menu)", "is allowed in the individual Character is evaluated first, then the Character's class,", "mro, to get the list of CharacterClasses in order for cls in reversed(type(self).__mro__):", "return self._mode.value # \"other\" is neither a CharClass nor Character else: return False", "particular command. usage: help [command] If no command is supplied, a list of", "excluded \"\"\" self._classes = set(classes) for char in include_chars: if char in exclude_chars:", "62)) setattr(self, \"_symbol\", symbol) return self._symbol @classmethod def load(cls, data): name = data[\"name\"]", "not normally support equality for mathematically sound reasons: https://bugs.python.org/issue3564 With this class's equality", "# move the player to the actual location they should be in loc", "after initialization is unsupported. \"\"\" def __init__(self, *args, **kwargs): \"\"\"initialize a Command like", "provided if \"classname\" not in namespace: cls.classname = util.camel_to_space(name) # add a frequency", "# check that other is a Character / CharacterClass if isinstance(other, CharacterClass): if", "appears to players classname = \"Default Character\" # Starting location for this class", "normally support equality for mathematically sound reasons: https://bugs.python.org/issue3564 With this class's equality operators,", "location for entity in self.location.entities: entity.on_exit(self) entity.remove_cmds(self) except AttributeError: # location was none", "prior argument will be overriden. \"\"\" args = self.args + tuple(newargs) keywords =", "the filter. \"\"\" class _FilterMode(enum.Enum): \"\"\"Enum representing whether a filter includes or excludes", "equip dict [item]: item to Equip [from_inv]: if True, [item] should be removed", "name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to pick up.\") @Command def", "= util.find(self.location, name=item_name) if len(found_items) == 1: item = found_items[0][0] self.location.inv.remove_item(item) self.inv.add_item(item) elif", "to Equip [from_inv]: if True, [item] should be removed from inventory first. If", "ValueError(\"Expected Character/CharacterClass,\" \" received %s\" % type(other)) def exclude(self, other): \"\"\"Set the filter", "item '{item_name}'.\") @Command.with_traits(name=\"unequip\") def cmd_unequip(self, args): \"\"\"Unequip an equipped item. Usage: unequip [item]\"\"\"", "and exclude\") for char in exclude_chars: if char in include_chars: raise ValueError(\"Cannot have", "\"\"\"place [item] in this player's equip dict [item]: item to Equip [from_inv]: if", "ValueError(\"Cannot have character in both include\" \" and exclude\") for char in exclude_chars:", "through each ancestor ancestors = filter(lambda x: isinstance(x, CharacterClass), other.__mro__) for char_class in", "= \" \".join(args[1::]).lower() found_items = util.find(self.inv, name=item_name) if len(found_items) == 1: self.equip(found_items[0][0]) elif", "\"\"\" import enum import functools import inspect import weakref import asyncio import swampymud.inventory", "a WHITELIST includes the class Wizard, but Bill the Wizard is in _exclude_chars,", "kind of check to prevent players # from having the same name? self._name", "self.unequip(found_items[0].target) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else:", "item is None: equipped.append(f\"{target}: none\") else: equipped.append(f\"{target}: {item[0]}\") equipped.sort() self.message(\"\\n\".join(equipped)) inv_msg = self.inv.readable()", "len(args) < 2: self.message(\"Please specify an item.\") return item_name = args[1] found_items =", "self.message(\"Names must have at least 2 characters.\") return if not new_name.isalnum(): self.message(\"Names must", "# serialization-related methods @property def symbol(self): \"\"\"return a unique symbol for this Character\"\"\"", "CharacterClasses\"\"\" # How this class appears to players classname = \"Default Character\" #", "equip_data if str(item).lower() == item_name: found_items.append(item) if len(found_items) == 1: self.unequip(found_items[0].target) elif len(found_items)", "in order for cls in reversed(type(self).__mro__): if isinstance(cls, CharacterClass): sources[cls.command_label] = [] for", "= name self.location = None self.msgs = asyncio.Queue() # build dict from Commands", "additional arguments. If a provided keyword argument conflicts with a prior argument, the", "print(f\"[{self}] received update\") def spawn(self, spawn_location): \"\"\"Send a greeting to the character and", "in ancestors: if char_class in self._classes: return self._mode.value # \"other\" is neither a", "item '{item_name}' to drop.\") @Command.with_traits(name=\"inv\") def cmd_inv(self, args): \"\"\"Show your inventory. usage: inv\"\"\"", "char in exclude_chars: raise ValueError(\"Cannot have character in both include\" \" and exclude\")", "its equip slots try: if self.equip_dict[target] is None: self.message(f\"No item equipped on target", "self.message(\"Provide an item to drop.\") return item_name = \" \".join(args[1:]).lower() found_items = util.find(self.inv,", "self.label is not None: return f\"{self} [from {self.label}]:\\n{self.__doc__}\" return f\"{self}:\\n{self.__doc__}\" @staticmethod def with_traits(name:", "first, then the Character's class, then all the Character's ancestor classes \"\"\" if", "inventory and will not be returned to inventory upon unequip. \"\"\" # duck", "weapon, unequip it if self.equip_dict[target] is not None: self.unequip(target) item.on_equip(self) item.add_cmds(self) self.equip_dict[item.target] =", "\" f\"'{ex_name}'.\") else: if found_exit.perceive.permits(self): self.message(f\"Exit '{ex_name}' is inaccessible to you.\") # if", "self.cmd_dict = ShadowDict() for (name, cmd) in self._commands.items(): cmd = cmd.specify(self) # add", "def help_entry(self) -> str: \"\"\"return a help message for this command\"\"\" if self.label", "arguments. All other information (base function, names, etc.) will be propagated. While you", "KeyError: self.message(f\"Command '{name}' not recognized.\") @Command def look(self, args): \"\"\"Gives a description of", "equip_data in self.equip_dict.items(): if equip_data is None: continue item, _ = equip_data if", "must have at least 2 characters.\") return if not new_name.isalnum(): self.message(\"Names must be", "updates character state\"\"\" print(f\"[{self}] received update\") def spawn(self, spawn_location): \"\"\"Send a greeting to", "util.camel_to_space(name) # add a frequency field, if not already provided if \"frequency\" not", "from_dict(filter_dict): \"\"\"returns a Filter pythonic representation [filter_dict]\"\"\" return Filter(**filter_dict) def to_dict(self): \"\"\"returns a", "name=item_name) if len(found_items) == 1: item = found_items[0][0] self.location.inv.remove_item(item) self.inv.add_item(item) elif len(found_items) >", "in exclude_chars: if char in include_chars: raise ValueError(\"Cannot have character in both include\"", "solve an undecidable problem, but just confirm that two partially-applied functions have the", "overriden. \"\"\" args = self.args + tuple(newargs) keywords = self.keywords.copy() keywords.update(new_keywords) new_cmd =", "add the proper name, if not already provided if \"classname\" not in namespace:", "= None): \"\"\"decorator to easily wrap a function additional traits [name] = to", "the same name? self._name = new_name # move the player to the actual", "amt=1): \"\"\"add [item] to player's inventory\"\"\" # if the item is an ItemStack,", "line: str): \"\"\"The default parser for a player. Parses\"\"\" # command is always", "the name and source new_cmd.name = self.name new_cmd.label = self.label # note that", "changing keywords after initialization is unsupported. \"\"\" def __init__(self, *args, **kwargs): \"\"\"initialize a", "help menu \"\"\" def __init__(cls, name, bases, namespace): # add the proper name,", "Filter\"\"\" data = {\"mode\" : self._mode.value} if self._classes: data[\"classes\"] = list(self._classes) if self._include_chars:", "included _exclude_chars - set characters to be excluded _mode - Filter.WHITELIST or Filter.BLACKLIST", "be whitelisted/blacklisted [include_chars] are specific characters to be included [exclude_chars] are specific characters", "doesn't have an equip target for this item, cannot equip else: self.message(f\"Cannot equip", "if self.label is not None: return f\"{self} [from {self.label}]:\\n{self.__doc__}\" return f\"{self}:\\n{self.__doc__}\" @staticmethod def", "be available to attack self.location = spawn_location self._parser = self._join_parser def despawn(self): \"\"\"method", "where the character should spawn after a name is submitted. \"\"\" self.message(f\"Welcome to", "used \"\"\" if self.name is None: return self.func.__name__ return self.name def help_entry(self) ->", "cmd.func.__name__), Command): setattr(self, cmd.func.__name__, cmd) # set up inventory and equipping items self.inv", "is NOT in _classes are allowed through the filter. Note that _include_chars /", "in _classes are allowed through the filter. Note that _include_chars / _exclude_chars take", "in reversed(cls.__mro__): if not isinstance(base, CharacterClass): continue cls._commands.update(base._local_commands) cls._commands.update(cls._local_commands) # calling the super", "args): \"\"\"Pick up item from the environment.\"\"\" if len(args) < 2: self.message(\"Provide an", "the previous and new locations as necessary and gathering commands from any entities", "item.on_equip(self) item.add_cmds(self) self.equip_dict[item.target] = item, from_inv # class doesn't have an equip target", "None: self.location.message(f\"{self.view()}: {msg}\") @Command def go(self, args): \"\"\"Go to an accessible location. usage:", "# in the current locations for entity in new_location.entities: entity.on_enter(self) entity.add_cmds(self) #inventory/item related", "partially-applied functions have the same arguments and underlying functions. Optional fields, \"name\", \"label\",", "target in self.equip_dict: # check remove_inv, if true, remove item from inventory #", "just confirm that two partially-applied functions have the same arguments and underlying functions.", "to prevent players # from having the same name? self._name = new_name #", "our location's list of exits # Note! If writing your own method, just", "super().__init__(name, bases, namespace) def __str__(cls): \"\"\"overriding str to return classname\"\"\" return cls.classname class", "is True, the Filter will act as a whitelist if [mode] is False,", "all commands, with the most recent commands exposed cls._commands = {} for base", "def look(self, args): \"\"\"Gives a description of your current location. usage: look \"\"\"", "not be returned to inventory upon unequip. \"\"\" # duck test that the", "will not be permitted through the filter. \"\"\" class _FilterMode(enum.Enum): \"\"\"Enum representing whether", "command(self, msg): \"\"\"issue 'msg' to character. character will parse 'msg' using its current", "found except KeyError: self.message(f\"Cannot equip {item}-\" \"not found in inventory.\") return # check", "self.cmd_dict[cmd_name] cmd(args) def _dead_parser(self, line: str): \"\"\"Parser used when a character has died\"\"\"", "self._mode = Filter.WHITELIST elif mode.lower() == \"blacklist\": self._mode = Filter.BLACKLIST else: raise ValueError(\"Unrecognized", "way to provide type=Item found_items = util.find(self.location, name=item_name) if len(found_items) == 1: item", "in self.location._exit_list: if ex_name in ex.names: found_exit = ex break else: self.message(f\"No exit", "self._exclude_chars.add(other) else: raise ValueError(\"Expected Character/CharacterClass,\" f\" received {type(other)}\") def __repr__(self): \"\"\"overriding repr()\"\"\" return", "player's inventory\"\"\" # if the item is an ItemStack, unpack it first if", "found_items = [] for _, equip_data in self.equip_dict.items(): if equip_data is None: continue", "on the INITIAL keywords, so changing keywords after initialization is unsupported. \"\"\" def", "msg = ' '.join(args[1:]) if msg and self.location is not None: self.location.message(f\"{self.view()}: {msg}\")", "if not already provided if \"frequency\" not in namespace: cls.frequency = 1 #", "if self.equip_dict[target] is None: self.message(f\"No item equipped on target {target}.\") return except KeyError:", "entity in new_location.entities: entity.on_enter(self) entity.add_cmds(self) #inventory/item related methods def add_item(self, item, amt=1): \"\"\"add", "# creating an immutable set of keywords for comparisons self._keys = frozenset(self.keywords.items()) #", "by characters. \"\"\" import enum import functools import inspect import weakref import asyncio", "\"field\" are also provided. These fields store player-relevant information that are NOT factored", "if [mode] is False, the Filter will act as a blacklist [classes] are", "str = None, filter: Filter = None): \"\"\"decorator to easily wrap a function", "#TODO handle ambiguity self.message(f\"Ambigious item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}'", "so any changes to the # old NewCommand will change to the old", "item. usage: use [item] [options for item] Options may vary per item. \"\"\"", "def post_load(self, data): pass def save(self): \"\"\"return a pythonic representation of this Character\"\"\"", "to pick up.\") return item_name = \" \".join(args[1::]).lower() # TODO: find a way", "method, just do # util.find(location, ex_name, location.Exit, char=my_char) # I'm only writing this", "help_entry(self) -> str: \"\"\"return a help message for this command\"\"\" if self.label is", "a \"command_label\", if not already provided # this field is used in creating", "it doesn't exist else: self.message(f\"No exit with name '{ex_name}'.\") @Command.with_traits(name=\"equip\") def cmd_equip(self, args):", "to the controller of this character\"\"\" # place a self.msgs.put_nowait(msg) def command(self, msg):", "determine which Characters / Classes are permitted to use this command. \"\"\" def", "in both include\" \" and exclude\") for char in exclude_chars: if char in", "Commands\" # Valid equip slots for characters of this class equip_slots = []", "item name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}'.\") @Command.with_traits(name=\"unequip\") def cmd_unequip(self, args):", "not None: self.unequip(target) item.on_equip(self) item.add_cmds(self) self.equip_dict[item.target] = item, from_inv # class doesn't have", "[item] should be removed from inventory first. If item is not found in", "Commands\" # commands that were implemented for this class cls._local_commands = {} for", "if not already provided if \"classname\" not in namespace: cls.classname = util.camel_to_space(name) #", "class starting_location = None # Commands from this class will be labeled \"Default", "isinstance(base, CharacterClass): continue cls._commands.update(base._local_commands) cls._commands.update(cls._local_commands) # calling the super init super().__init__(name, bases, namespace)", "item equipped on target {target}.\") return except KeyError: self.message(f\"{type(self)} does not possess\" f\"", "character\"\"\" # place a self.msgs.put_nowait(msg) def command(self, msg): \"\"\"issue 'msg' to character. character", "- frequency: how often will new players spawn as this class - command_label:", "characters whose class is in _classes are allowed through the filter. if BLACKLIST", "exposed cls._commands = {} for base in reversed(cls.__mro__): if not isinstance(base, CharacterClass): continue", "self.equip_dict.items(): if item is None: equipped.append(f\"{target}: none\") else: equipped.append(f\"{target}: {item[0]}\") equipped.sort() self.message(\"\\n\".join(equipped)) inv_msg", "elif other in self._exclude_chars: return False # now try the Character's class other", "to the actual location they should be in loc = self.location self.location =", "equip slots for characters of this class equip_slots = [] def __init__(self, name=None):", "= [] for name, cmd in self.cmd_dict.items(): try: sources[cmd.label].append(name) except KeyError: sources[cmd.label] =", "this Character\"\"\" return {\"_type\": type(self), \"name\": self._name} def children(self): \"\"\"pass\"\"\" return [] #TODO:", "are NOT factored into comparisons. In addition, this class has a convenience method,", "commands from all the entities # in the current locations for entity in", "def from_dict(filter_dict): \"\"\"returns a Filter pythonic representation [filter_dict]\"\"\" return Filter(**filter_dict) def to_dict(self): \"\"\"returns", "those classes to be whitelisted/blacklisted [include_chars] are specific characters to be included [exclude_chars]", "is not None: self.location.message(f\"{self} died.\", exclude={self}) try: self.location.characters.remove(self) except ValueError: pass self.location =", "Results={found_items}\") else: self.message(f\"Could not find item '{item_name}' to pick up.\") @Command def drop(self,", "f\"{self} [from {self.label}]:\\n{self.__doc__}\" return f\"{self}:\\n{self.__doc__}\" @staticmethod def with_traits(name: str = None, label: str", "by the filter _include_chars - set characters to be included _exclude_chars - set", "type(other) if isinstance(other, CharacterClass): # cycle through each ancestor ancestors = filter(lambda x:", "namespace) def __str__(cls): \"\"\"overriding str to return classname\"\"\" return cls.classname class Character(metaclass=CharacterClass): \"\"\"Base", "issue? if isinstance(getattr(self, cmd.func.__name__), Command): setattr(self, cmd.func.__name__, cmd) # set up inventory and", "in self.equip_dict.items(): if equip_data is None: continue item, _ = equip_data if str(item).lower()", "include_chars=(), exclude_chars=()): \"\"\"initialize a Filter with [mode] if [mode] is True, the Filter", "in the individual Character is evaluated first, then the Character's class, then all", "in location? if len(args) < 2: self.message(\"Please specify an item.\") return item_name =", "import enum import functools import inspect import weakref import asyncio import swampymud.inventory as", "{\"mode\" : self._mode.value} if self._classes: data[\"classes\"] = list(self._classes) if self._include_chars: data[\"include_chars\"] = list(self._include_chars)", "a prior argument, the prior argument will be overriden. \"\"\" args = self.args", "== \"whitelist\": self._mode = Filter.WHITELIST elif mode.lower() == \"blacklist\": self._mode = Filter.BLACKLIST else:", "representation of this Filter\"\"\" data = {\"mode\" : self._mode.value} if self._classes: data[\"classes\"] =", "symbol) return self._symbol @classmethod def load(cls, data): name = data[\"name\"] if \"name\" in", "name\"\"\" if len(new_name) < 2: self.message(\"Names must have at least 2 characters.\") return", "self.name new_cmd.label = self.label # note that a new filter is not created,", "then all the Character's ancestor classes \"\"\" if isinstance(other, Character): if other in", "cls.command_label cls._local_commands[str(value)] = value # all commands, with the most recent commands exposed", "the args are equal, and the (initial) keywords are equal\"\"\" try: return (self.func,", "dict from Commands collected by CharacterClass self.cmd_dict = ShadowDict() for (name, cmd) in", "if found_exit.perceive.permits(self): self.message(f\"Exit '{ex_name}' is inaccessible to you.\") # if the char can't", "old Command, and visa versa new_cmd.filter = self.filter return new_cmd def __str__(self): \"\"\"returns", "_include_chars - set characters to be included _exclude_chars - set characters to be", "one by simply adding additional arguments. All other information (base function, names, etc.)", "self.message(\"Provide an item to equip.\") return item_name = \" \".join(args[1::]).lower() found_items = util.find(self.inv,", "name. Results={found_items}\") else: self.message(f\"Could not find item '{item_name}'.\") @Command.with_traits(name=\"unequip\") def cmd_unequip(self, args): \"\"\"Unequip", "Character behaviors CharacterClasses include the following important attributes: - classname: how the class", "= spawn_location self._parser = self._join_parser def despawn(self): \"\"\"method executed when a player dies\"\"\"", "self.inv = inv.Inventory() self.equip_dict = inv.EquipTarget.make_dict(*self.equip_slots) # put character in default command parsing", "unique symbol for this Character\"\"\" # failsafe to ensure that Character always has", "else: raise ValueError(\"Expected Character/CharacterClass,\" f\" received {type(other)}\") def __repr__(self): \"\"\"overriding repr()\"\"\" return \"Filter({!r},", "self.location = None self._parser = self._dead_parser # default user-input parsers def _join_parser(self, new_name:", "ancestors cannot be found in the list return not self._mode.value def include(self, other):", "to be excluded \"\"\" self._classes = set(classes) for char in include_chars: if char", "of this function by applying additional arguments. If a provided keyword argument conflicts", "recent commands exposed cls._commands = {} for base in reversed(cls.__mro__): if not isinstance(base,", "of exits # Note! If writing your own method, just do # util.find(location,", "the __init__ if not hasattr(self, \"_symbol\"): symbol = \"{}#{}\".format(type(self).__name__, util.to_base(id(self), 62)) setattr(self, \"_symbol\",", "self.equip_dict: # check remove_inv, if true, remove item from inventory # this avoids", "that position is unequipped [target]: an EquipTarget\"\"\" # test if anything is even", "from_inv = self.equip_dict[target] equipped.on_unequip(self) equipped.remove_cmds(self) self.equip_dict[target] = None # if item was from", "dependency. for ex in self.location._exit_list: if ex_name in ex.names: found_exit = ex break", "set to None and any item at that position is unequipped [target]: an", "args[0] if not cmd_name in self.cmd_dict: self.message(\"Command \\'%s\\' not recognized.\" % cmd_name) return", "user-input parsers def _join_parser(self, new_name: str): \"\"\"Parser for a newly joined player, used", "Character class, which serves as the basis for all in-game characters. This module", "not already provided if \"classname\" not in namespace: cls.classname = util.camel_to_space(name) # add", "other CharacterClasses\"\"\" # How this class appears to players classname = \"Default Character\"", "this character\"\"\" # place a self.msgs.put_nowait(msg) def command(self, msg): \"\"\"issue 'msg' to character.", "how commands from this class appear in help menu \"\"\" def __init__(cls, name,", "name [label] = the type of the command. (Affects help menu.) [filter] =", "old NewCommand will change to the old Command, and visa versa new_cmd.filter =", "implementation of functools.partial does not normally support equality for mathematically sound reasons: https://bugs.python.org/issue3564", "the equip_dict found_items = [] for _, equip_data in self.equip_dict.items(): if equip_data is", "else: raise ValueError(\"Unrecognized mode %s\" % repr(mode)) def permits(self, other): \"\"\"returns True if", "some kind of check to prevent players # from having the same name?", "Character\"\"\" return {\"_type\": type(self), \"name\": self._name} def children(self): \"\"\"pass\"\"\" return [] #TODO: handle", "command\"\"\" if self.label is not None: return f\"{self} [from {self.label}]:\\n{self.__doc__}\" return f\"{self}:\\n{self.__doc__}\" @staticmethod", "is not removed from inventory and will not be returned to inventory upon", "in namespace.values(): if isinstance(value, Command): value.label = cls.command_label cls._local_commands[str(value)] = value # all", "valid name\"\"\" if len(new_name) < 2: self.message(\"Names must have at least 2 characters.\")", "set player location to spawn_location, but do not MOVE them # thus, player", "a WeakSet, so that the Filter will not # prevent them from getting", "information that are NOT factored into comparisons. In addition, this class has a", "of your current location. usage: look \"\"\" # TODO: update to allow players", "filter _include_chars - set characters to be included _exclude_chars - set characters to", "duck test to see if this character even has [target] # in its", "@Command.with_traits(name=\"use\") def cmd_use(self, args): \"\"\" Use an item. usage: use [item] [options for", "is None: return f\"A nameless {type(self)}\" return f\"{self._name} the {type(self)}\" #location manipulation methods", "slots for characters of this class equip_slots = [] def __init__(self, name=None): super().__init__()", "getting garbage collected self._include_chars = weakref.WeakSet(include_chars) self._exclude_chars = weakref.WeakSet(exclude_chars) if isinstance(mode, self._FilterMode): self._mode", "return \"Filter({!r}, {!r}, {!r}, {!r})\".format( self._mode.value, set(self._classes), set(self._include_chars), set(self._exclude_chars) ) @staticmethod def from_dict(filter_dict):", "self.message(self.cmd_dict[name].help_entry()) except KeyError: self.message(f\"Command '{name}' not recognized.\") @Command def look(self, args): \"\"\"Gives a", "this command\"\"\" if self.label is not None: return f\"{self} [from {self.label}]:\\n{self.__doc__}\" return f\"{self}:\\n{self.__doc__}\"", "functools.partial does not normally support equality for mathematically sound reasons: https://bugs.python.org/issue3564 With this", "if len(args) < 2: # TODO: cache this or something menu = self.help_menu()", "related methods def add_item(self, item, amt=1): \"\"\"add [item] to player's inventory\"\"\" # if", "self.message(f\"Could not find item '{item_name}' to drop.\") @Command.with_traits(name=\"inv\") def cmd_inv(self, args): \"\"\"Show your", "to them and pretend like it doesn't exist else: self.message(f\"No exit with name", "args): \"\"\"Unequip an equipped item. Usage: unequip [item]\"\"\" if len(args) < 2: self.message(\"Provide", "comparisons self._keys = frozenset(self.keywords.items()) # propagate the name and doc from the base", "docstring, if one was provided try: self.__doc__ = inspect.cleandoc(self.__doc__) except AttributeError: pass #", "store player-relevant information that are NOT factored into comparisons. In addition, this class", "if \"name\" in data else None return cls(name) def post_load(self, data): pass def", "else: name = args[1] try: self.message(self.cmd_dict[name].help_entry()) except KeyError: self.message(f\"Command '{name}' not recognized.\") @Command", "try: target = item.target except AttributeError: self.message(f\"{item} cannot be equipped.\") return if target", "name. Results={found_items}\") else: self.message(f\"Could not find equipped item '{item_name}'.\") @Command def pickup(self, args):", "a normal # method, we must manually bind the methods # TODO: override", "data = {\"mode\" : self._mode.value} if self._classes: data[\"classes\"] = list(self._classes) if self._include_chars: data[\"include_chars\"]", "spawn(self, spawn_location): \"\"\"Send a greeting to the character and put them into a", "\".join(args[1::]).lower() # search through the items in the equip_dict found_items = [] for", "item.amount) self.inv.add_item(item, amt) def equip(self, item, from_inv=True): \"\"\"place [item] in this player's equip", "INITIAL keywords, so changing keywords after initialization is unsupported. \"\"\" def __init__(self, *args,", "is not created, so any changes to the # old NewCommand will change", "\"frequency\" not in namespace: cls.frequency = 1 # add a \"command_label\", if not", "function, names, etc.) will be propagated. While you can update Command.keywords, avoid doing", "setattr(self, \"_symbol\", symbol) return self._symbol @classmethod def load(cls, data): name = data[\"name\"] if", "to set self._symbol in the __init__ if not hasattr(self, \"_symbol\"): symbol = \"{}#{}\".format(type(self).__name__,", "characters.\") return if not new_name.isalnum(): self.message(\"Names must be alphanumeric.\") return # TODO: perform", "no name is provided, func.__name__ is used \"\"\" if self.name is None: return", "satellite data self.name = None self.label = None # by default, add a", "item, from_inv=True): \"\"\"place [item] in this player's equip dict [item]: item to Equip", "# we lie to them and pretend like it doesn't exist else: self.message(f\"No", "self.name is None: return self.func.__name__ return self.name def help_entry(self) -> str: \"\"\"return a", "CharacterClass(type): \"\"\"metaclass establishing basic Character behaviors CharacterClasses include the following important attributes: -", "args = self.args + tuple(newargs) keywords = self.keywords.copy() keywords.update(new_keywords) new_cmd = Command(self.func, *args,", "like it doesn't exist else: self.message(f\"No exit with name '{ex_name}'.\") @Command.with_traits(name=\"equip\") def cmd_equip(self,", "None, filter: Filter = None): \"\"\"decorator to easily wrap a function additional traits", "removed from inventory first. If item is not found in inventory, the command", "if item is None: equipped.append(f\"{target}: none\") else: equipped.append(f\"{target}: {item[0]}\") equipped.sort() self.message(\"\\n\".join(equipped)) inv_msg =", "data else None return cls(name) def post_load(self, data): pass def save(self): \"\"\"return a", "# test if anything is even equipped # also duck test to see", "return new_cmd def __str__(self): \"\"\"returns the name of this command if no name", "in default command parsing mode self._parser = self._command_parser def message(self, msg): \"\"\"send a", "update to allow players to 'inspect' certain objects self.message(self.location.view()) @Command def say(self, args):", "= \"{}#{}\".format(type(self).__name__, util.to_base(id(self), 62)) setattr(self, \"_symbol\", symbol) return self._symbol @classmethod def load(cls, data):", "\"\"\"returns the name of this command if no name is provided, func.__name__ is", "I'm only writing this to avoid a cyclic dependency. for ex in self.location._exit_list:", "'msg' to character. character will parse 'msg' using its current parser.\"\"\" if msg:", "and self.location is not None: self.location.message(f\"{self.view()}: {msg}\") @Command def go(self, args): \"\"\"Go to", "the players - frequency: how often will new players spawn as this class", "this class will be labeled \"Default Commands\" command_label = \"Default Commands\" # Valid", "spawn after a name is submitted. \"\"\" self.message(f\"Welcome to our SwampyMud! You are", "not found except KeyError: self.message(f\"Cannot equip {item}-\" \"not found in inventory.\") return #", "a new Command from an existing one by simply adding additional arguments. All", "2 characters.\") return if not new_name.isalnum(): self.message(\"Names must be alphanumeric.\") return # TODO:", "that can be invoked by characters. \"\"\" import enum import functools import inspect", "operators, we aren't trying to solve an undecidable problem, but just confirm that", "https://bugs.python.org/issue3564 With this class's equality operators, we aren't trying to solve an undecidable", "from this class will be labeled \"Default Commands\" command_label = \"Default Commands\" #", "aren't trying to solve an undecidable problem, but just confirm that two partially-applied", "char_class in self._classes: return self._mode.value # \"other\" is neither a CharClass nor Character", "\"\"\"Unequip an equipped item. Usage: unequip [item]\"\"\" if len(args) < 2: self.message(\"Provide an", "self.args + tuple(newargs) keywords = self.keywords.copy() keywords.update(new_keywords) new_cmd = Command(self.func, *args, **keywords) #", "to the players - frequency: how often will new players spawn as this", "filter is not created, so any changes to the # old NewCommand will", "an immutable set of keywords for comparisons self._keys = frozenset(self.keywords.items()) # propagate the", "the basis for all in-game characters. This module also defines the 'Filter', used", "{} for value in namespace.values(): if isinstance(value, Command): value.label = cls.command_label cls._local_commands[str(value)] =", "has a convenience method, '.specify' to derive a new Command from an existing", "executed when a player dies\"\"\" self.message(\"You died.\") if self.location is not None: self.location.message(f\"{self}", "avoid a cyclic dependency. for ex in self.location._exit_list: if ex_name in ex.names: found_exit", "# calling the super init super().__init__(name, bases, namespace) def __str__(cls): \"\"\"overriding str to", "representation of Character\"\"\" if self._name is None: return f\"{type(self).__name__}()\" return f\"{type(self).__name__}(name={self})\" def __str__(self):", "through the filter. if BLACKLIST is selected, only characters whose class is NOT", "the _classes. That is, if a WHITELIST includes the class Wizard, but Bill", "= [] def __init__(self, name=None): super().__init__() self._name = name self.location = None self.msgs", "current locations for entity in new_location.entities: entity.on_enter(self) entity.add_cmds(self) #inventory/item related methods def add_item(self,", "default commands @Command def help(self, args): \"\"\"Show relevant help information for a particular", "== 1: item = found_items[0][0] self.location.inv.remove_item(item) self.inv.add_item(item) elif len(found_items) > 1: #TODO handle", "inaccessible to you.\") # if the char can't see or interact with the", "menu.) [filter] = if provided, determine which Characters / Classes are permitted to", "a Command return False def __hash__(self): \"\"\"overriding hash\"\"\" return hash((self.func, self.args, self._keys)) def", "item = found_items[0][0] self.location.inv.remove_item(item) self.inv.add_item(item) elif len(found_items) > 1: #TODO handle ambiguity self.message(f\"Ambigious", "= asyncio.Queue() # build dict from Commands collected by CharacterClass self.cmd_dict = ShadowDict()", "newly joined player, used for selecting a valid name\"\"\" if len(new_name) < 2:", "to solve the super() issue? if isinstance(getattr(self, cmd.func.__name__), Command): setattr(self, cmd.func.__name__, cmd) #", "hash\"\"\" return hash((self.func, self.args, self._keys)) def specify(self, *newargs, **new_keywords) -> 'Command': \"\"\"Derive a", "methods @property def symbol(self): \"\"\"return a unique symbol for this Character\"\"\" # failsafe", "self.name def help_entry(self) -> str: \"\"\"return a help message for this command\"\"\" if", "this Character\"\"\" # failsafe to ensure that Character always has a symbol #", "_classes are allowed through the filter. if BLACKLIST is selected, only characters whose", "ex_name in ex.names: found_exit = ex break else: self.message(f\"No exit with name '{ex_name}'.\")", "ValueError: pass self.location = None self._parser = self._dead_parser # default user-input parsers def", "char_class in ancestors: if char_class in self._classes: return self._mode.value # \"other\" is neither", "Equip [from_inv]: if True, [item] should be removed from inventory first. If item", "Filter.WHITELIST or Filter.BLACKLIST if WHITELIST is selected, only characters whose class is in", "= self.equip_dict[target] equipped.on_unequip(self) equipped.remove_cmds(self) self.equip_dict[target] = None # if item was from character's", "the 'Filter', used for CharacterClass-based permissions systems, and 'Command', a wrapper that converts", "simply adding additional arguments. All other information (base function, names, etc.) will be", "equip(self, item, from_inv=True): \"\"\"place [item] in this player's equip dict [item]: item to", "= Filter.BLACKLIST else: raise ValueError(\"Unrecognized mode %s\" % repr(mode)) def permits(self, other): \"\"\"returns", "= self.location self.location = None self.set_location(loc) self._parser = self._command_parser def _command_parser(self, line: str):", "# set up inventory and equipping items self.inv = inv.Inventory() self.equip_dict = inv.EquipTarget.make_dict(*self.equip_slots)", "self._mode == Filter.WHITELIST: if other in self._classes: self._classes.remove(other) else: self._classes.add(other) elif isinstance(other, Character):", "Filter.WHITELIST elif mode.lower() == \"blacklist\": self._mode = Filter.BLACKLIST else: raise ValueError(\"Unrecognized mode %s\"", "Character / CharacterClass if isinstance(other, CharacterClass): if self._mode == Filter.WHITELIST: if other in", "not already provided if \"frequency\" not in namespace: cls.frequency = 1 # add", "we aren't trying to solve an undecidable problem, but just confirm that two", "self.func.__name__ self.__doc__ = self.func.__doc__ # try to clean the docstring, if one was", "comparisons. In addition, this class has a convenience method, '.specify' to derive a", "be propagated. While you can update Command.keywords, avoid doing so. All comparisons are", "the most recent commands exposed cls._commands = {} for base in reversed(cls.__mro__): if", "cmd.specify(self) # add command only if filter permits it if cmd.filter.permits(self): self.cmd_dict[name] =", "the items in the equip_dict found_items = [] for _, equip_data in self.equip_dict.items():", "that it tracks\"\"\" WHITELIST = True BLACKLIST = False WHITELIST = _FilterMode.WHITELIST BLACKLIST" ]
[ "ast import literal_eval from flask import jsonify, request from back.mongo.data.collect.indicators.mongo import find_indicators def", "literal_eval(request.args.get(\"limit\")) if \"limit\" in request.args else 100 filter[\"_id\"] = 0 data = find_indicators(query,", "query = literal_eval(request.args.get(\"query\")) if \"query\" in request.args else {\"countries\": {\"$exists\": True, \"$ne\": []},", "0}} filter = literal_eval(request.args.get(\"filter\")) if \"filter\" in request.args else {\"countries\": 0} sort =", "= literal_eval(request.args.get(\"query\")) if \"query\" in request.args else {\"countries\": {\"$exists\": True, \"$ne\": []}, \"completeness\":", "= literal_eval(request.args.get(\"filter\")) if \"filter\" in request.args else {\"countries\": 0} sort = literal_eval(request.args.get(\"sort\")) if", "flask import jsonify, request from back.mongo.data.collect.indicators.mongo import find_indicators def register_api_indicators_route(app): @app.route(\"/api/indicators\") def api_indicators():", "in request.args else {\"countries\": 0} sort = literal_eval(request.args.get(\"sort\")) if \"sort\" in request.args else", "import jsonify, request from back.mongo.data.collect.indicators.mongo import find_indicators def register_api_indicators_route(app): @app.route(\"/api/indicators\") def api_indicators(): query", "api_indicators(): query = literal_eval(request.args.get(\"query\")) if \"query\" in request.args else {\"countries\": {\"$exists\": True, \"$ne\":", "sort = literal_eval(request.args.get(\"sort\")) if \"sort\" in request.args else [(\"completeness\", -1), (\"name\", 1)] limit", "register_api_indicators_route(app): @app.route(\"/api/indicators\") def api_indicators(): query = literal_eval(request.args.get(\"query\")) if \"query\" in request.args else {\"countries\":", "@app.route(\"/api/indicators\") def api_indicators(): query = literal_eval(request.args.get(\"query\")) if \"query\" in request.args else {\"countries\": {\"$exists\":", "in request.args else 100 filter[\"_id\"] = 0 data = find_indicators(query, filter, sort, limit)", "[]}, \"completeness\": {\"$gt\": 0}} filter = literal_eval(request.args.get(\"filter\")) if \"filter\" in request.args else {\"countries\":", "back.mongo.data.collect.indicators.mongo import find_indicators def register_api_indicators_route(app): @app.route(\"/api/indicators\") def api_indicators(): query = literal_eval(request.args.get(\"query\")) if \"query\"", "import literal_eval from flask import jsonify, request from back.mongo.data.collect.indicators.mongo import find_indicators def register_api_indicators_route(app):", "request.args else {\"countries\": 0} sort = literal_eval(request.args.get(\"sort\")) if \"sort\" in request.args else [(\"completeness\",", "in request.args else {\"countries\": {\"$exists\": True, \"$ne\": []}, \"completeness\": {\"$gt\": 0}} filter =", "-1), (\"name\", 1)] limit = literal_eval(request.args.get(\"limit\")) if \"limit\" in request.args else 100 filter[\"_id\"]", "jsonify, request from back.mongo.data.collect.indicators.mongo import find_indicators def register_api_indicators_route(app): @app.route(\"/api/indicators\") def api_indicators(): query =", "in request.args else [(\"completeness\", -1), (\"name\", 1)] limit = literal_eval(request.args.get(\"limit\")) if \"limit\" in", "1)] limit = literal_eval(request.args.get(\"limit\")) if \"limit\" in request.args else 100 filter[\"_id\"] = 0", "<filename>app/front/tree/home/api/indicators/route.py from ast import literal_eval from flask import jsonify, request from back.mongo.data.collect.indicators.mongo import", "\"query\" in request.args else {\"countries\": {\"$exists\": True, \"$ne\": []}, \"completeness\": {\"$gt\": 0}} filter", "import find_indicators def register_api_indicators_route(app): @app.route(\"/api/indicators\") def api_indicators(): query = literal_eval(request.args.get(\"query\")) if \"query\" in", "literal_eval from flask import jsonify, request from back.mongo.data.collect.indicators.mongo import find_indicators def register_api_indicators_route(app): @app.route(\"/api/indicators\")", "if \"query\" in request.args else {\"countries\": {\"$exists\": True, \"$ne\": []}, \"completeness\": {\"$gt\": 0}}", "0} sort = literal_eval(request.args.get(\"sort\")) if \"sort\" in request.args else [(\"completeness\", -1), (\"name\", 1)]", "limit = literal_eval(request.args.get(\"limit\")) if \"limit\" in request.args else 100 filter[\"_id\"] = 0 data", "\"$ne\": []}, \"completeness\": {\"$gt\": 0}} filter = literal_eval(request.args.get(\"filter\")) if \"filter\" in request.args else", "{\"$exists\": True, \"$ne\": []}, \"completeness\": {\"$gt\": 0}} filter = literal_eval(request.args.get(\"filter\")) if \"filter\" in", "else 100 filter[\"_id\"] = 0 data = find_indicators(query, filter, sort, limit) return jsonify(data)", "literal_eval(request.args.get(\"filter\")) if \"filter\" in request.args else {\"countries\": 0} sort = literal_eval(request.args.get(\"sort\")) if \"sort\"", "\"completeness\": {\"$gt\": 0}} filter = literal_eval(request.args.get(\"filter\")) if \"filter\" in request.args else {\"countries\": 0}", "filter = literal_eval(request.args.get(\"filter\")) if \"filter\" in request.args else {\"countries\": 0} sort = literal_eval(request.args.get(\"sort\"))", "from back.mongo.data.collect.indicators.mongo import find_indicators def register_api_indicators_route(app): @app.route(\"/api/indicators\") def api_indicators(): query = literal_eval(request.args.get(\"query\")) if", "literal_eval(request.args.get(\"query\")) if \"query\" in request.args else {\"countries\": {\"$exists\": True, \"$ne\": []}, \"completeness\": {\"$gt\":", "else {\"countries\": {\"$exists\": True, \"$ne\": []}, \"completeness\": {\"$gt\": 0}} filter = literal_eval(request.args.get(\"filter\")) if", "True, \"$ne\": []}, \"completeness\": {\"$gt\": 0}} filter = literal_eval(request.args.get(\"filter\")) if \"filter\" in request.args", "def api_indicators(): query = literal_eval(request.args.get(\"query\")) if \"query\" in request.args else {\"countries\": {\"$exists\": True,", "\"filter\" in request.args else {\"countries\": 0} sort = literal_eval(request.args.get(\"sort\")) if \"sort\" in request.args", "literal_eval(request.args.get(\"sort\")) if \"sort\" in request.args else [(\"completeness\", -1), (\"name\", 1)] limit = literal_eval(request.args.get(\"limit\"))", "= literal_eval(request.args.get(\"sort\")) if \"sort\" in request.args else [(\"completeness\", -1), (\"name\", 1)] limit =", "\"sort\" in request.args else [(\"completeness\", -1), (\"name\", 1)] limit = literal_eval(request.args.get(\"limit\")) if \"limit\"", "else [(\"completeness\", -1), (\"name\", 1)] limit = literal_eval(request.args.get(\"limit\")) if \"limit\" in request.args else", "from flask import jsonify, request from back.mongo.data.collect.indicators.mongo import find_indicators def register_api_indicators_route(app): @app.route(\"/api/indicators\") def", "else {\"countries\": 0} sort = literal_eval(request.args.get(\"sort\")) if \"sort\" in request.args else [(\"completeness\", -1),", "(\"name\", 1)] limit = literal_eval(request.args.get(\"limit\")) if \"limit\" in request.args else 100 filter[\"_id\"] =", "= literal_eval(request.args.get(\"limit\")) if \"limit\" in request.args else 100 filter[\"_id\"] = 0 data =", "if \"filter\" in request.args else {\"countries\": 0} sort = literal_eval(request.args.get(\"sort\")) if \"sort\" in", "request from back.mongo.data.collect.indicators.mongo import find_indicators def register_api_indicators_route(app): @app.route(\"/api/indicators\") def api_indicators(): query = literal_eval(request.args.get(\"query\"))", "request.args else {\"countries\": {\"$exists\": True, \"$ne\": []}, \"completeness\": {\"$gt\": 0}} filter = literal_eval(request.args.get(\"filter\"))", "{\"countries\": 0} sort = literal_eval(request.args.get(\"sort\")) if \"sort\" in request.args else [(\"completeness\", -1), (\"name\",", "request.args else 100 filter[\"_id\"] = 0 data = find_indicators(query, filter, sort, limit) return", "if \"limit\" in request.args else 100 filter[\"_id\"] = 0 data = find_indicators(query, filter,", "{\"$gt\": 0}} filter = literal_eval(request.args.get(\"filter\")) if \"filter\" in request.args else {\"countries\": 0} sort", "if \"sort\" in request.args else [(\"completeness\", -1), (\"name\", 1)] limit = literal_eval(request.args.get(\"limit\")) if", "request.args else [(\"completeness\", -1), (\"name\", 1)] limit = literal_eval(request.args.get(\"limit\")) if \"limit\" in request.args", "from ast import literal_eval from flask import jsonify, request from back.mongo.data.collect.indicators.mongo import find_indicators", "\"limit\" in request.args else 100 filter[\"_id\"] = 0 data = find_indicators(query, filter, sort,", "def register_api_indicators_route(app): @app.route(\"/api/indicators\") def api_indicators(): query = literal_eval(request.args.get(\"query\")) if \"query\" in request.args else", "[(\"completeness\", -1), (\"name\", 1)] limit = literal_eval(request.args.get(\"limit\")) if \"limit\" in request.args else 100", "{\"countries\": {\"$exists\": True, \"$ne\": []}, \"completeness\": {\"$gt\": 0}} filter = literal_eval(request.args.get(\"filter\")) if \"filter\"", "find_indicators def register_api_indicators_route(app): @app.route(\"/api/indicators\") def api_indicators(): query = literal_eval(request.args.get(\"query\")) if \"query\" in request.args" ]
[ "\" parameter no longer has any effect and may not be allowed\" \\", "\"mpunet 0.1.3 or higher requires integer targets\" \\ \" as opposed to one-hot", "targets\" \\ \" as opposed to one-hot encoded targets. Setting the 'sparse'\" \\", "as opposed to one-hot encoded targets. Setting the 'sparse'\" \\ \" parameter no", "requires integer targets\" \\ \" as opposed to one-hot encoded targets. Setting the", "any effect and may not be allowed\" \\ \" in future versions.\" logger.warn(sparse_err)", "has any effect and may not be allowed\" \\ \" in future versions.\"", "\\ \" as opposed to one-hot encoded targets. Setting the 'sparse'\" \\ \"", "warn_sparse_param(logger): logger = logger or ScreenLogger sparse_err = \"mpunet 0.1.3 or higher requires", "parameter no longer has any effect and may not be allowed\" \\ \"", "longer has any effect and may not be allowed\" \\ \" in future", "or higher requires integer targets\" \\ \" as opposed to one-hot encoded targets.", "one-hot encoded targets. Setting the 'sparse'\" \\ \" parameter no longer has any", "higher requires integer targets\" \\ \" as opposed to one-hot encoded targets. Setting", "to one-hot encoded targets. Setting the 'sparse'\" \\ \" parameter no longer has", "logger or ScreenLogger sparse_err = \"mpunet 0.1.3 or higher requires integer targets\" \\", "targets. Setting the 'sparse'\" \\ \" parameter no longer has any effect and", "no longer has any effect and may not be allowed\" \\ \" in", "encoded targets. Setting the 'sparse'\" \\ \" parameter no longer has any effect", "= logger or ScreenLogger sparse_err = \"mpunet 0.1.3 or higher requires integer targets\"", "mpunet.logging import ScreenLogger def warn_sparse_param(logger): logger = logger or ScreenLogger sparse_err = \"mpunet", "ScreenLogger sparse_err = \"mpunet 0.1.3 or higher requires integer targets\" \\ \" as", "\\ \" parameter no longer has any effect and may not be allowed\"", "= \"mpunet 0.1.3 or higher requires integer targets\" \\ \" as opposed to", "ScreenLogger def warn_sparse_param(logger): logger = logger or ScreenLogger sparse_err = \"mpunet 0.1.3 or", "from mpunet.logging import ScreenLogger def warn_sparse_param(logger): logger = logger or ScreenLogger sparse_err =", "'sparse'\" \\ \" parameter no longer has any effect and may not be", "def warn_sparse_param(logger): logger = logger or ScreenLogger sparse_err = \"mpunet 0.1.3 or higher", "or ScreenLogger sparse_err = \"mpunet 0.1.3 or higher requires integer targets\" \\ \"", "logger = logger or ScreenLogger sparse_err = \"mpunet 0.1.3 or higher requires integer", "sparse_err = \"mpunet 0.1.3 or higher requires integer targets\" \\ \" as opposed", "0.1.3 or higher requires integer targets\" \\ \" as opposed to one-hot encoded", "the 'sparse'\" \\ \" parameter no longer has any effect and may not", "opposed to one-hot encoded targets. Setting the 'sparse'\" \\ \" parameter no longer", "Setting the 'sparse'\" \\ \" parameter no longer has any effect and may", "\" as opposed to one-hot encoded targets. Setting the 'sparse'\" \\ \" parameter", "import ScreenLogger def warn_sparse_param(logger): logger = logger or ScreenLogger sparse_err = \"mpunet 0.1.3", "integer targets\" \\ \" as opposed to one-hot encoded targets. Setting the 'sparse'\"" ]
[ "current_vlans.list = {} obj = HANDLE.GetManagedObject(None, FabricVlan.ClassId()) if obj != None: for mo", "'n']: print '' print '*** Error: Please enter either \"yes\" or \"no\". ***'", "for org in current_orgs.list: if org in mo.getattr(prop): organization = org else: organization", "or 'n']: current_orgs() add_vlan_to_vnic() print (\"The \" + '\"' + add_vlans.vlan_name + '\"'", "< (2, 6): from functools import partial import ssl ssl.wrap_socket = partial( ssl.wrap_socket,", "\"Descr\": descr = mo.getattr(prop) if str(prop) == \"PolicyOwner\": policy_owner = mo.getattr(prop) if str(prop)", "{\"IdentPoolName\": \"{}\".format(ident_pool_name), \"Dn\": \"{}\".format(dn), \"QosPolicyName\": \"{}\".format(qos_policy_name), \"Descr\": \"{}\".format(descr), \"PolicyOwner\": \"{}\".format(policy_owner), \"NwCtrlPolicyName\": \"{}\".format(nw_ctrl_policy_name), \"TemplType\":", "print '' obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId(), { VnicLanConnTempl.RN: \"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)}) if obj != None:", "if str(prop) == \"PinToGroupName\": pin_to_group_name = mo.getattr(prop) if str(prop) == \"SwitchId\": switch_id =", "== \"Descr\": descr = mo.getattr(prop) if str(prop) == \"PolicyOwner\": policy_owner = mo.getattr(prop) if", "= HANDLE.GetManagedObject(None, None, {\"Dn\": \"fabric/lan\"}) HANDLE.AddManagedObject(obj, \"fabricVlan\", {\"DefaultNet\": \"no\", \"PubNwName\": \"\", \"Dn\": \"fabric/lan/net-{}\".format(add_vlans.vlan_name),", "6): from functools import partial import ssl ssl.wrap_socket = partial( ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) if", "raw_input( 'Would you like to add a new VLAN? (yes/no): ') if add_vlans.confirm_new_vlan", "current_vlans.list.items(): if add_vlans.vlan_name in str(key): print '' print 'The following VLAN has been", "if str(prop) == \"Mtu\": mtu = mo.getattr(prop) if str(prop) == \"PinToGroupName\": pin_to_group_name =", "\"Id\": \"{}\".format(vlan_id)}) current_vlans() for key, value in current_vlans.list.items(): if add_vlans.vlan_name in str(key): print", "UCSM domain - View and Add VLANs - Add a VLAN to a", "def add_vlans(): \"\"\" Create new VLANs on UCS. \"\"\" print '' add_vlans.confirm_new_vlan =", "{\"DefaultNet\": \"no\", \"PubNwName\": \"\", \"Dn\": \"fabric/lan/net-{}\".format(add_vlans.vlan_name), \"PolicyOwner\": \"local\", \"CompressionType\": \"included\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Sharing\":", "prevents proper UCS domain login when using Python 2.7 or higher. Credit to", "[Warning]: AddManagedObject [Description]:Expected Naming Property Name for ClassId VnicLanConnTempl not found warnings.warn(string) '''", "\") while confirm_add_vlan not in ['yes', 'y', 'no', 'n']: print '' print '***", "\"{}\".format(mtu), \"PinToGroupName\": \"{}\".format(pin_to_group_name), \"SwitchId\": \"{}\".format(switch_id)}, True) mo_1 = HANDLE.AddManagedObject(mo, \"vnicEtherIf\", { \"DefaultNet\": \"no\",", "from UcsSdk.MoMeta.OrgOrg import OrgOrg import sys import warnings ''' Supress the following warning", "CLI interface that utilizes the Cisco UCS SDK to: - Connect to a", "'\"' + \" VLAN has been added to \" '\"' + add_vlan_to_vnic.vnic_name +", "'' print 'Current vNIC Templates: ' print '' current_vnic_templates() for name in current_vnic_templates.list:", "HANDLE.GetManagedObject(None, None, {\"Dn\": \"fabric/lan\"}) HANDLE.AddManagedObject(obj, \"fabricVlan\", {\"DefaultNet\": \"no\", \"PubNwName\": \"\", \"Dn\": \"fabric/lan/net-{}\".format(add_vlans.vlan_name), \"PolicyOwner\":", "not in ['no' or 'n']: print add_vlans.vlan_name = raw_input('Enter the VLAN Name: ')", "\"vnicEtherIf\", { \"DefaultNet\": \"no\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Dn\": \"{}/if-{}\".format(dn, add_vlans.vlan_name)}, True) HANDLE.CompleteTransaction() ssl_workaround() IP_ADDRESS", "key + ' (' + value + ')' def current_vnic_templates(): \"\"\" Get a", "the following warning message which does not affect funcationality: /Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064: UserWarning: [Warning]: AddManagedObject", "there is very little error handling present so proceed accordingly. \"\"\" from UcsSdk", "vlan_id = raw_input('Enter the VLAN ID: ') obj = HANDLE.GetManagedObject(None, None, {\"Dn\": \"fabric/lan\"})", "vNIC Please note that there is very little error handling present so proceed", "new VLAN? (yes/no): ') while add_vlans.confirm_new_vlan not in ['yes', 'y', 'no', 'n']: print", "{\"Dn\": \"{}\".format(organization)}) mo = HANDLE.AddManagedObject(vnic_obj, \"vnicLanConnTempl\", {\"IdentPoolName\": \"{}\".format(ident_pool_name), \"Dn\": \"{}\".format(dn), \"QosPolicyName\": \"{}\".format(qos_policy_name), \"Descr\":", "' (' + ID + ')' add_vlans() if add_vlans.confirm_new_vlan not in ['no' or", "if add_vlans.confirm_new_vlan not in ['no' or 'n']: print add_vlans.vlan_name = raw_input('Enter the VLAN", "+ add_vlans.vlan_name + '\"' + \" VLAN to a vNIC template? (yes/no): \")", "Please note that there is very little error handling present so proceed accordingly.", "dn = mo.getattr(prop) for org in current_orgs.list: if org in mo.getattr(prop): organization =", "' + name print '' confirm_add_vlan = raw_input( \"Would you like to add", "Create new VLANs on UCS. \"\"\" print '' add_vlans.confirm_new_vlan = raw_input( 'Would you", "Connect to a UCSM domain - View and Add VLANs - Add a", "the Cisco UCS Communities \"\"\" is_verify_certificate = False if not sys.version_info < (2,", "VLAN? (yes/no): ') while add_vlans.confirm_new_vlan not in ['yes', 'y', 'no', 'n']: print ''", "in ['yes', 'y', 'no', 'n']: print '' print '*** Error: Please enter either", "+ ' (' + value + ')' def current_vnic_templates(): \"\"\" Get a list", "enter either \"yes\" or \"no\". ***' print '' cconfirm_add_vlan = raw_input( \"Would you", "proceed accordingly. \"\"\" from UcsSdk import UcsHandle from UcsSdk import UcsUtils from UcsSdk.MoMeta.FabricVlan", "[] obj = HANDLE.GetManagedObject(None, OrgOrg.ClassId()) if obj != None: for mo in obj:", "HANDLE.GetManagedObject( None, None, {\"Dn\": \"{}\".format(organization)}) mo = HANDLE.AddManagedObject(vnic_obj, \"vnicLanConnTempl\", {\"IdentPoolName\": \"{}\".format(ident_pool_name), \"Dn\": \"{}\".format(dn),", "prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vlan_name = mo.getattr(prop) if str(prop) ==", "== \"Name\": vlan_name = mo.getattr(prop) if str(prop) == \"Id\": vlan_id = mo.getattr(prop) current_vlans.list.update({vlan_name:", "which does not affect funcationality: /Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064: UserWarning: [Warning]: AddManagedObject [Description]:Expected Naming Property Name", "\"PolicyOwner\": policy_owner = mo.getattr(prop) if str(prop) == \"NwCtrlPolicyName\": nw_ctrl_policy_name = mo.getattr(prop) if str(prop)", "Please enter either \"yes\" or \"no\". ***' print '' add_vlans.confirm_new_vlan = raw_input( 'Would", "(yes/no): ') while add_vlans.confirm_new_vlan not in ['yes', 'y', 'no', 'n']: print '' print", "VLAN Management\" print '' print 'Current VLANs:' current_vlans() print '' for name, ID", "str(key): print '' print 'The following VLAN has been created: ' print ''", "in UCS \"\"\" current_vnic_templates.list = [] obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId()) if obj !=", "in current_vlans.list.iteritems(): print '- ' + name + ' (' + ID +", "(yes/no): \") while confirm_add_vlan not in ['yes', 'y', 'no', 'n']: print '' print", "VLAN to a vNIC template? (yes/no): \") while confirm_add_vlan not in ['yes', 'y',", "a list of all current VLANs \"\"\" current_vlans.list = {} obj = HANDLE.GetManagedObject(None,", "\"\", \"Id\": \"{}\".format(vlan_id)}) current_vlans() for key, value in current_vlans.list.items(): if add_vlans.vlan_name in str(key):", "= \"\" PASSWORD = \"\" HANDLE = UcsHandle() HANDLE = UcsHandle() connect() print", "for key, value in current_vlans.list.items(): if add_vlans.vlan_name in str(key): print '' print 'The", "current_orgs.list: if org in mo.getattr(prop): organization = org else: organization = \"org-root\" if", "organizations in UCS which will be used in add_vlan_to_vnic \"\"\" current_orgs.list = []", "UcsSdk.MoMeta.FabricVlan import FabricVlan from UcsSdk.MoMeta.VnicLanConnTempl import VnicLanConnTempl from UcsSdk.MoMeta.OrgOrg import OrgOrg import sys", "') print '' obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId(), { VnicLanConnTempl.RN: \"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)}) if obj !=", "HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId(), { VnicLanConnTempl.RN: \"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)}) if obj != None: for mo in obj:", "+ '\"' + \" VLAN to a vNIC template? (yes/no): \") if confirm_add_vlan", "'\"' + \" VLAN to a vNIC template? (yes/no): \") while confirm_add_vlan not", "print '' print '*** Error: Please enter either \"yes\" or \"no\". ***' print", "like to add a new VLAN? (yes/no): ') if add_vlans.confirm_new_vlan not in ['no'", "add_vlan_to_vnic(): \"\"\" Add a VLAN to a vNIC template \"\"\" print add_vlan_to_vnic.vnic_name =", "\"{}\".format(templ_type), \"StatsPolicyName\": \"{}\".format(stats_policy_name), \"Mtu\": \"{}\".format(mtu), \"PinToGroupName\": \"{}\".format(pin_to_group_name), \"SwitchId\": \"{}\".format(switch_id)}, True) mo_1 = HANDLE.AddManagedObject(mo,", "\"\"\" Workaround for SSL certification error that prevents proper UCS domain login when", "\"no\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Dn\": \"{}/if-{}\".format(dn, add_vlans.vlan_name)}, True) HANDLE.CompleteTransaction() ssl_workaround() IP_ADDRESS = \"\" USERNAME", "== \"StatsPolicyName\": stats_policy_name = mo.getattr(prop) if str(prop) == \"Mtu\": mtu = mo.getattr(prop) if", "confirm_add_vlan = raw_input( \"Would you like to add the \" + '\"' +", "current_vlans.list.iteritems(): print '- ' + name + ' (' + ID + ')'", "ClassId VnicLanConnTempl not found warnings.warn(string) ''' warnings.filterwarnings(\"ignore\") def ssl_workaround(): \"\"\" Workaround for SSL", "def ssl_workaround(): \"\"\" Workaround for SSL certification error that prevents proper UCS domain", "to add a new VLAN? (yes/no): ') if add_vlans.confirm_new_vlan not in ['no' or", "been created: ' print '' print '- ' + key + ' ('", "of the current organizations in UCS which will be used in add_vlan_to_vnic \"\"\"", "name print '' confirm_add_vlan = raw_input( \"Would you like to add the \"", "a new VLAN? (yes/no): ') while add_vlans.confirm_new_vlan not in ['yes', 'y', 'no', 'n']:", "using Python 2.7 or higher. Credit to user <NAME> (ragupta4) on the Cisco", "\"Dn\": \"{}/if-{}\".format(dn, add_vlans.vlan_name)}, True) HANDLE.CompleteTransaction() ssl_workaround() IP_ADDRESS = \"\" USERNAME = \"\" PASSWORD", "not found warnings.warn(string) ''' warnings.filterwarnings(\"ignore\") def ssl_workaround(): \"\"\" Workaround for SSL certification error", "policy_owner = mo.getattr(prop) if str(prop) == \"NwCtrlPolicyName\": nw_ctrl_policy_name = mo.getattr(prop) if str(prop) ==", "str(prop) == \"PolicyOwner\": policy_owner = mo.getattr(prop) if str(prop) == \"NwCtrlPolicyName\": nw_ctrl_policy_name = mo.getattr(prop)", "the VLAN Name: ') vlan_id = raw_input('Enter the VLAN ID: ') obj =", "for ClassId VnicLanConnTempl not found warnings.warn(string) ''' warnings.filterwarnings(\"ignore\") def ssl_workaround(): \"\"\" Workaround for", "!= None: for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) ==", "== \"Id\": vlan_id = mo.getattr(prop) current_vlans.list.update({vlan_name: vlan_id}) def add_vlans(): \"\"\" Create new VLANs", "certification error that prevents proper UCS domain login when using Python 2.7 or", "interface that utilizes the Cisco UCS SDK to: - Connect to a UCSM", "'' cconfirm_add_vlan = raw_input( \"Would you like to add the \" + '\"'", "\"Name\": vlan_name = mo.getattr(prop) if str(prop) == \"Id\": vlan_id = mo.getattr(prop) current_vlans.list.update({vlan_name: vlan_id})", "\"DefaultNet\": \"no\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Dn\": \"{}/if-{}\".format(dn, add_vlans.vlan_name)}, True) HANDLE.CompleteTransaction() ssl_workaround() IP_ADDRESS = \"\"", "mo.getattr(prop) current_vnic_templates.list.append(vnic_template_name) def current_orgs(): \"\"\" Get a list of the current organizations in", "vNIC template? (yes/no): \") while confirm_add_vlan not in ['yes', 'y', 'no', 'n']: print", "\"PubNwName\": \"\", \"Dn\": \"fabric/lan/net-{}\".format(add_vlans.vlan_name), \"PolicyOwner\": \"local\", \"CompressionType\": \"included\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Sharing\": \"none\", \"McastPolicyName\":", "+ ')' def current_vnic_templates(): \"\"\" Get a list of current vNICs in UCS", "to \" '\"' + add_vlan_to_vnic.vnic_name + '\"' + \" vNIC template.\") print else:", "\"Name\": vnic_template_name = mo.getattr(prop) current_vnic_templates.list.append(vnic_template_name) def current_orgs(): \"\"\" Get a list of the", "\"no\", \"PubNwName\": \"\", \"Dn\": \"fabric/lan/net-{}\".format(add_vlans.vlan_name), \"PolicyOwner\": \"local\", \"CompressionType\": \"included\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Sharing\": \"none\",", "UCS Domain \"\"\" HANDLE.Login(IP_ADDRESS, USERNAME, PASSWORD) def current_vlans(): \"\"\" Get a list of", "(ragupta4) on the Cisco UCS Communities \"\"\" is_verify_certificate = False if not sys.version_info", "None: for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\":", "str(prop) == \"NwCtrlPolicyName\": nw_ctrl_policy_name = mo.getattr(prop) if str(prop) == \"TemplType\": templ_type = mo.getattr(prop)", "\"Name\": \"{}\".format(add_vlans.vlan_name), \"Sharing\": \"none\", \"McastPolicyName\": \"\", \"Id\": \"{}\".format(vlan_id)}) current_vlans() for key, value in", "raw_input( \"Would you like to add the \" + '\"' + add_vlans.vlan_name +", "switch_id = mo.getattr(prop) HANDLE.StartTransaction() vnic_obj = HANDLE.GetManagedObject( None, None, {\"Dn\": \"{}\".format(organization)}) mo =", "vNICs in UCS \"\"\" current_vnic_templates.list = [] obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId()) if obj", "+ ID + ')' add_vlans() if add_vlans.confirm_new_vlan not in ['no' or 'n']: print", "import warnings ''' Supress the following warning message which does not affect funcationality:", "str(prop) == \"IdentPoolName\": ident_pool_name = mo.getattr(prop) if str(prop) == \"QosPolicyName\": qos_policy_name = mo.getattr(prop)", "created: ' print '' print '- ' + key + ' (' +", "== \"PinToGroupName\": pin_to_group_name = mo.getattr(prop) if str(prop) == \"SwitchId\": switch_id = mo.getattr(prop) HANDLE.StartTransaction()", "ID + ')' add_vlans() if add_vlans.confirm_new_vlan not in ['no' or 'n']: print ''", "+ '\"' + add_vlans.vlan_name + '\"' + \" VLAN has been added to", "\"Mtu\": mtu = mo.getattr(prop) if str(prop) == \"PinToGroupName\": pin_to_group_name = mo.getattr(prop) if str(prop)", "UcsUtils from UcsSdk.MoMeta.FabricVlan import FabricVlan from UcsSdk.MoMeta.VnicLanConnTempl import VnicLanConnTempl from UcsSdk.MoMeta.OrgOrg import OrgOrg", "print '' cconfirm_add_vlan = raw_input( \"Would you like to add the \" +", "import FabricVlan from UcsSdk.MoMeta.VnicLanConnTempl import VnicLanConnTempl from UcsSdk.MoMeta.OrgOrg import OrgOrg import sys import", "HANDLE.StartTransaction() vnic_obj = HANDLE.GetManagedObject( None, None, {\"Dn\": \"{}\".format(organization)}) mo = HANDLE.AddManagedObject(vnic_obj, \"vnicLanConnTempl\", {\"IdentPoolName\":", "' (' + value + ')' def current_vnic_templates(): \"\"\" Get a list of", "= HANDLE.GetManagedObject(None, OrgOrg.ClassId()) if obj != None: for mo in obj: for prop", "current_vlans(): \"\"\" Get a list of all current VLANs \"\"\" current_vlans.list = {}", "['no' or 'n']: current_orgs() add_vlan_to_vnic() print (\"The \" + '\"' + add_vlans.vlan_name +", "= HANDLE.GetManagedObject(None, FabricVlan.ClassId()) if obj != None: for mo in obj: for prop", "\"Dn\": \"{}\".format(dn), \"QosPolicyName\": \"{}\".format(qos_policy_name), \"Descr\": \"{}\".format(descr), \"PolicyOwner\": \"{}\".format(policy_owner), \"NwCtrlPolicyName\": \"{}\".format(nw_ctrl_policy_name), \"TemplType\": \"{}\".format(templ_type), \"StatsPolicyName\":", "VLAN has been added to \" '\"' + add_vlan_to_vnic.vnic_name + '\"' + \"", "\"\"\" Get a list of all current VLANs \"\"\" current_vlans.list = {} obj", "VLAN Name: ') vlan_id = raw_input('Enter the VLAN ID: ') obj = HANDLE.GetManagedObject(None,", "UcsSdk.MoMeta.VnicLanConnTempl import VnicLanConnTempl from UcsSdk.MoMeta.OrgOrg import OrgOrg import sys import warnings ''' Supress", "\"{}\".format(dn), \"QosPolicyName\": \"{}\".format(qos_policy_name), \"Descr\": \"{}\".format(descr), \"PolicyOwner\": \"{}\".format(policy_owner), \"NwCtrlPolicyName\": \"{}\".format(nw_ctrl_policy_name), \"TemplType\": \"{}\".format(templ_type), \"StatsPolicyName\": \"{}\".format(stats_policy_name),", "\"{}\".format(descr), \"PolicyOwner\": \"{}\".format(policy_owner), \"NwCtrlPolicyName\": \"{}\".format(nw_ctrl_policy_name), \"TemplType\": \"{}\".format(templ_type), \"StatsPolicyName\": \"{}\".format(stats_policy_name), \"Mtu\": \"{}\".format(mtu), \"PinToGroupName\": \"{}\".format(pin_to_group_name),", "\"{}\".format(nw_ctrl_policy_name), \"TemplType\": \"{}\".format(templ_type), \"StatsPolicyName\": \"{}\".format(stats_policy_name), \"Mtu\": \"{}\".format(mtu), \"PinToGroupName\": \"{}\".format(pin_to_group_name), \"SwitchId\": \"{}\".format(switch_id)}, True) mo_1", "following VLAN has been created: ' print '' print '- ' + key", "VnicLanConnTempl.RN: \"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)}) if obj != None: for mo in obj: for prop in", "been added to \" '\"' + add_vlan_to_vnic.vnic_name + '\"' + \" vNIC template.\")", "if not sys.version_info < (2, 6): from functools import partial import ssl ssl.wrap_socket", "Get a list of all current VLANs \"\"\" current_vlans.list = {} obj =", "sys.version_info < (2, 7, 9) and not is_verify_certificate: ssl._create_default_https_context = ssl._create_unverified_context def connect():", "\"fabric/lan\"}) HANDLE.AddManagedObject(obj, \"fabricVlan\", {\"DefaultNet\": \"no\", \"PubNwName\": \"\", \"Dn\": \"fabric/lan/net-{}\".format(add_vlans.vlan_name), \"PolicyOwner\": \"local\", \"CompressionType\": \"included\",", "raw_input( 'Would you like to add a new VLAN? (yes/no): ') while add_vlans.confirm_new_vlan", "'\"' + add_vlan_to_vnic.vnic_name + '\"' + \" vNIC template.\") print else: print HANDLE.Logout()", "USERNAME, PASSWORD) def current_vlans(): \"\"\" Get a list of all current VLANs \"\"\"", "prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": dn = mo.getattr(prop) for org in", "mo.getattr(prop) HANDLE.StartTransaction() vnic_obj = HANDLE.GetManagedObject( None, None, {\"Dn\": \"{}\".format(organization)}) mo = HANDLE.AddManagedObject(vnic_obj, \"vnicLanConnTempl\",", "current organizations in UCS which will be used in add_vlan_to_vnic \"\"\" current_orgs.list =", "print '- ' + key + ' (' + value + ')' def", "== \"Dn\": org_name = mo.getattr(prop) current_orgs.list.append(org_name) current_orgs.list.remove('org-root') def add_vlan_to_vnic(): \"\"\" Add a VLAN", "UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": dn = mo.getattr(prop) for org in current_orgs.list: if", "user <NAME> (ragupta4) on the Cisco UCS Communities \"\"\" is_verify_certificate = False if", "')' add_vlans() if add_vlans.confirm_new_vlan not in ['no' or 'n']: print '' print 'Current", "+ add_vlans.vlan_name + '\"' + \" VLAN has been added to \" '\"'", "UCS. \"\"\" print '' add_vlans.confirm_new_vlan = raw_input( 'Would you like to add a", "\"no\". ***' print '' add_vlans.confirm_new_vlan = raw_input( 'Would you like to add a", "\"\"\" Create new VLANs on UCS. \"\"\" print '' add_vlans.confirm_new_vlan = raw_input( 'Would", "mo.getattr(prop) for org in current_orgs.list: if org in mo.getattr(prop): organization = org else:", "\"Would you like to add the \" + '\"' + add_vlans.vlan_name + '\"'", "add_vlan_to_vnic() print (\"The \" + '\"' + add_vlans.vlan_name + '\"' + \" VLAN", "a list of the current organizations in UCS which will be used in", "\"PinToGroupName\": \"{}\".format(pin_to_group_name), \"SwitchId\": \"{}\".format(switch_id)}, True) mo_1 = HANDLE.AddManagedObject(mo, \"vnicEtherIf\", { \"DefaultNet\": \"no\", \"Name\":", "\"StatsPolicyName\": stats_policy_name = mo.getattr(prop) if str(prop) == \"Mtu\": mtu = mo.getattr(prop) if str(prop)", "\"TemplType\": \"{}\".format(templ_type), \"StatsPolicyName\": \"{}\".format(stats_policy_name), \"Mtu\": \"{}\".format(mtu), \"PinToGroupName\": \"{}\".format(pin_to_group_name), \"SwitchId\": \"{}\".format(switch_id)}, True) mo_1 =", "== \"Name\": vnic_template_name = mo.getattr(prop) current_vnic_templates.list.append(vnic_template_name) def current_orgs(): \"\"\" Get a list of", "you like to add the \" + '\"' + add_vlans.vlan_name + '\"' +", "org else: organization = \"org-root\" if str(prop) == \"IdentPoolName\": ident_pool_name = mo.getattr(prop) if", "UCS which will be used in add_vlan_to_vnic \"\"\" current_orgs.list = [] obj =", "print '' print \"Cisco UCS Manager VLAN Management\" print '' print 'Current VLANs:'", "\"vnicLanConnTempl\", {\"IdentPoolName\": \"{}\".format(ident_pool_name), \"Dn\": \"{}\".format(dn), \"QosPolicyName\": \"{}\".format(qos_policy_name), \"Descr\": \"{}\".format(descr), \"PolicyOwner\": \"{}\".format(policy_owner), \"NwCtrlPolicyName\": \"{}\".format(nw_ctrl_policy_name),", "print '' print 'The following VLAN has been created: ' print '' print", "PASSWORD = \"\" HANDLE = UcsHandle() HANDLE = UcsHandle() connect() print '' print", "enter either \"yes\" or \"no\". ***' print '' add_vlans.confirm_new_vlan = raw_input( 'Would you", "\"{}\".format(qos_policy_name), \"Descr\": \"{}\".format(descr), \"PolicyOwner\": \"{}\".format(policy_owner), \"NwCtrlPolicyName\": \"{}\".format(nw_ctrl_policy_name), \"TemplType\": \"{}\".format(templ_type), \"StatsPolicyName\": \"{}\".format(stats_policy_name), \"Mtu\": \"{}\".format(mtu),", "= partial( ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) if not sys.version_info < (2, 7, 9) and not", "template? (yes/no): \") if confirm_add_vlan not in ['no' or 'n']: current_orgs() add_vlan_to_vnic() print", "name, ID in current_vlans.list.iteritems(): print '- ' + name + ' (' +", "current_orgs(): \"\"\" Get a list of the current organizations in UCS which will", "found warnings.warn(string) ''' warnings.filterwarnings(\"ignore\") def ssl_workaround(): \"\"\" Workaround for SSL certification error that", "current_vnic_templates.list.append(vnic_template_name) def current_orgs(): \"\"\" Get a list of the current organizations in UCS", "in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vnic_template_name = mo.getattr(prop)", "obj = HANDLE.GetManagedObject(None, FabricVlan.ClassId()) if obj != None: for mo in obj: for", "+ \" VLAN has been added to \" '\"' + add_vlan_to_vnic.vnic_name + '\"'", "def current_vlans(): \"\"\" Get a list of all current VLANs \"\"\" current_vlans.list =", "if str(prop) == \"Descr\": descr = mo.getattr(prop) if str(prop) == \"PolicyOwner\": policy_owner =", "PASSWORD) def current_vlans(): \"\"\" Get a list of all current VLANs \"\"\" current_vlans.list", "ID in current_vlans.list.iteritems(): print '- ' + name + ' (' + ID", "Property Name for ClassId VnicLanConnTempl not found warnings.warn(string) ''' warnings.filterwarnings(\"ignore\") def ssl_workaround(): \"\"\"", "print add_vlans.vlan_name = raw_input('Enter the VLAN Name: ') vlan_id = raw_input('Enter the VLAN", "add_vlans.vlan_name + '\"' + \" VLAN to a vNIC template? (yes/no): \") if", "\"Id\": vlan_id = mo.getattr(prop) current_vlans.list.update({vlan_name: vlan_id}) def add_vlans(): \"\"\" Create new VLANs on", "+ ' (' + ID + ')' add_vlans() if add_vlans.confirm_new_vlan not in ['no'", "A Python CLI interface that utilizes the Cisco UCS SDK to: - Connect", "print '- ' + name print '' confirm_add_vlan = raw_input( \"Would you like", "[Description]:Expected Naming Property Name for ClassId VnicLanConnTempl not found warnings.warn(string) ''' warnings.filterwarnings(\"ignore\") def", "added to \" '\"' + add_vlan_to_vnic.vnic_name + '\"' + \" vNIC template.\") print", "7, 9) and not is_verify_certificate: ssl._create_default_https_context = ssl._create_unverified_context def connect(): \"\"\" Establish a", "= HANDLE.GetManagedObject( None, None, {\"Dn\": \"{}\".format(organization)}) mo = HANDLE.AddManagedObject(vnic_obj, \"vnicLanConnTempl\", {\"IdentPoolName\": \"{}\".format(ident_pool_name), \"Dn\":", "+ \" VLAN to a vNIC template? (yes/no): \") if confirm_add_vlan not in", "+ key + ' (' + value + ')' def current_vnic_templates(): \"\"\" Get", "current_vnic_templates.list: print '- ' + name print '' confirm_add_vlan = raw_input( \"Would you", "== \"IdentPoolName\": ident_pool_name = mo.getattr(prop) if str(prop) == \"QosPolicyName\": qos_policy_name = mo.getattr(prop) if", "= raw_input( 'Would you like to add a new VLAN? (yes/no): ') if", "\"Sharing\": \"none\", \"McastPolicyName\": \"\", \"Id\": \"{}\".format(vlan_id)}) current_vlans() for key, value in current_vlans.list.items(): if", "str(prop) == \"Dn\": org_name = mo.getattr(prop) current_orgs.list.append(org_name) current_orgs.list.remove('org-root') def add_vlan_to_vnic(): \"\"\" Add a", "a VLAN to a vNIC Please note that there is very little error", "'' print 'The following VLAN has been created: ' print '' print '-", "on the Cisco UCS Communities \"\"\" is_verify_certificate = False if not sys.version_info <", "error that prevents proper UCS domain login when using Python 2.7 or higher.", "\"IdentPoolName\": ident_pool_name = mo.getattr(prop) if str(prop) == \"QosPolicyName\": qos_policy_name = mo.getattr(prop) if str(prop)", "HANDLE.GetManagedObject(None, OrgOrg.ClassId()) if obj != None: for mo in obj: for prop in", "not affect funcationality: /Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064: UserWarning: [Warning]: AddManagedObject [Description]:Expected Naming Property Name for ClassId", "VLAN to a vNIC Please note that there is very little error handling", "9) and not is_verify_certificate: ssl._create_default_https_context = ssl._create_unverified_context def connect(): \"\"\" Establish a connection", "current_vlans() for key, value in current_vlans.list.items(): if add_vlans.vlan_name in str(key): print '' print", "while add_vlans.confirm_new_vlan not in ['yes', 'y', 'no', 'n']: print '' print '*** Error:", "in ['no' or 'n']: print add_vlans.vlan_name = raw_input('Enter the VLAN Name: ') vlan_id", "UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vnic_template_name = mo.getattr(prop) current_vnic_templates.list.append(vnic_template_name) def current_orgs(): \"\"\" Get", "\"yes\" or \"no\". ***' print '' add_vlans.confirm_new_vlan = raw_input( 'Would you like to", "Templates: ' print '' current_vnic_templates() for name in current_vnic_templates.list: print '- ' +", "Name: ') print '' obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId(), { VnicLanConnTempl.RN: \"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)}) if obj", "new VLANs on UCS. \"\"\" print '' add_vlans.confirm_new_vlan = raw_input( 'Would you like", "= mo.getattr(prop) if str(prop) == \"StatsPolicyName\": stats_policy_name = mo.getattr(prop) if str(prop) == \"Mtu\":", "warning message which does not affect funcationality: /Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064: UserWarning: [Warning]: AddManagedObject [Description]:Expected Naming", "if not sys.version_info < (2, 7, 9) and not is_verify_certificate: ssl._create_default_https_context = ssl._create_unverified_context", "***' print '' add_vlans.confirm_new_vlan = raw_input( 'Would you like to add a new", "in current_vnic_templates.list: print '- ' + name print '' confirm_add_vlan = raw_input( \"Would", "'*** Error: Please enter either \"yes\" or \"no\". ***' print '' add_vlans.confirm_new_vlan =", "of all current VLANs \"\"\" current_vlans.list = {} obj = HANDLE.GetManagedObject(None, FabricVlan.ClassId()) if", "== \"Mtu\": mtu = mo.getattr(prop) if str(prop) == \"PinToGroupName\": pin_to_group_name = mo.getattr(prop) if", "domain - View and Add VLANs - Add a VLAN to a vNIC", "to add a new VLAN? (yes/no): ') while add_vlans.confirm_new_vlan not in ['yes', 'y',", "\"Dn\": org_name = mo.getattr(prop) current_orgs.list.append(org_name) current_orgs.list.remove('org-root') def add_vlan_to_vnic(): \"\"\" Add a VLAN to", "mo.getattr(prop) if str(prop) == \"PinToGroupName\": pin_to_group_name = mo.getattr(prop) if str(prop) == \"SwitchId\": switch_id", "\"{}\".format(ident_pool_name), \"Dn\": \"{}\".format(dn), \"QosPolicyName\": \"{}\".format(qos_policy_name), \"Descr\": \"{}\".format(descr), \"PolicyOwner\": \"{}\".format(policy_owner), \"NwCtrlPolicyName\": \"{}\".format(nw_ctrl_policy_name), \"TemplType\": \"{}\".format(templ_type),", "(' + ID + ')' add_vlans() if add_vlans.confirm_new_vlan not in ['no' or 'n']:", "\" VLAN has been added to \" '\"' + add_vlan_to_vnic.vnic_name + '\"' +", "mo.getattr(prop) if str(prop) == \"Descr\": descr = mo.getattr(prop) if str(prop) == \"PolicyOwner\": policy_owner", "like to add a new VLAN? (yes/no): ') while add_vlans.confirm_new_vlan not in ['yes',", "def connect(): \"\"\" Establish a connection to the UCS Domain \"\"\" HANDLE.Login(IP_ADDRESS, USERNAME,", "if str(prop) == \"Name\": vlan_name = mo.getattr(prop) if str(prop) == \"Id\": vlan_id =", "['no' or 'n']: print add_vlans.vlan_name = raw_input('Enter the VLAN Name: ') vlan_id =", "not sys.version_info < (2, 7, 9) and not is_verify_certificate: ssl._create_default_https_context = ssl._create_unverified_context def", "not in ['no' or 'n']: current_orgs() add_vlan_to_vnic() print (\"The \" + '\"' +", "def current_orgs(): \"\"\" Get a list of the current organizations in UCS which", "{} obj = HANDLE.GetManagedObject(None, FabricVlan.ClassId()) if obj != None: for mo in obj:", "'Current VLANs:' current_vlans() print '' for name, ID in current_vlans.list.iteritems(): print '- '", "print '' print 'Current vNIC Templates: ' print '' current_vnic_templates() for name in", "from UcsSdk import UcsHandle from UcsSdk import UcsUtils from UcsSdk.MoMeta.FabricVlan import FabricVlan from", "Credit to user <NAME> (ragupta4) on the Cisco UCS Communities \"\"\" is_verify_certificate =", "obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vlan_name = mo.getattr(prop) if", "import ssl ssl.wrap_socket = partial( ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) if not sys.version_info < (2, 7,", "UCS Manager VLAN Management\" print '' print 'Current VLANs:' current_vlans() print '' for", "\"TemplType\": templ_type = mo.getattr(prop) if str(prop) == \"StatsPolicyName\": stats_policy_name = mo.getattr(prop) if str(prop)", "mo.getattr(prop) current_orgs.list.append(org_name) current_orgs.list.remove('org-root') def add_vlan_to_vnic(): \"\"\" Add a VLAN to a vNIC template", "\"QosPolicyName\": \"{}\".format(qos_policy_name), \"Descr\": \"{}\".format(descr), \"PolicyOwner\": \"{}\".format(policy_owner), \"NwCtrlPolicyName\": \"{}\".format(nw_ctrl_policy_name), \"TemplType\": \"{}\".format(templ_type), \"StatsPolicyName\": \"{}\".format(stats_policy_name), \"Mtu\":", "to add the \" + '\"' + add_vlans.vlan_name + '\"' + \" VLAN", "or higher. Credit to user <NAME> (ragupta4) on the Cisco UCS Communities \"\"\"", "'' print '- ' + key + ' (' + value + ')'", "UcsSdk.MoMeta.OrgOrg import OrgOrg import sys import warnings ''' Supress the following warning message", "\"SwitchId\": switch_id = mo.getattr(prop) HANDLE.StartTransaction() vnic_obj = HANDLE.GetManagedObject( None, None, {\"Dn\": \"{}\".format(organization)}) mo", "or 'n']: print add_vlans.vlan_name = raw_input('Enter the VLAN Name: ') vlan_id = raw_input('Enter", "domain login when using Python 2.7 or higher. Credit to user <NAME> (ragupta4)", "= raw_input('Enter the VLAN Name: ') vlan_id = raw_input('Enter the VLAN ID: ')", "has been added to \" '\"' + add_vlan_to_vnic.vnic_name + '\"' + \" vNIC", "\"Cisco UCS Manager VLAN Management\" print '' print 'Current VLANs:' current_vlans() print ''", "'no', 'n']: print '' print '*** Error: Please enter either \"yes\" or \"no\".", "ssl ssl.wrap_socket = partial( ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) if not sys.version_info < (2, 7, 9)", "mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": org_name =", "mo = HANDLE.AddManagedObject(vnic_obj, \"vnicLanConnTempl\", {\"IdentPoolName\": \"{}\".format(ident_pool_name), \"Dn\": \"{}\".format(dn), \"QosPolicyName\": \"{}\".format(qos_policy_name), \"Descr\": \"{}\".format(descr), \"PolicyOwner\":", "the VLAN ID: ') obj = HANDLE.GetManagedObject(None, None, {\"Dn\": \"fabric/lan\"}) HANDLE.AddManagedObject(obj, \"fabricVlan\", {\"DefaultNet\":", "' print '' print '- ' + key + ' (' + value", "from functools import partial import ssl ssl.wrap_socket = partial( ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) if not", "add a new VLAN? (yes/no): ') while add_vlans.confirm_new_vlan not in ['yes', 'y', 'no',", "obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId(), { VnicLanConnTempl.RN: \"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)}) if obj != None: for mo", "vNIC template? (yes/no): \") if confirm_add_vlan not in ['no' or 'n']: current_orgs() add_vlan_to_vnic()", "\"fabric/lan/net-{}\".format(add_vlans.vlan_name), \"PolicyOwner\": \"local\", \"CompressionType\": \"included\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Sharing\": \"none\", \"McastPolicyName\": \"\", \"Id\": \"{}\".format(vlan_id)})", "value + ')' def current_vnic_templates(): \"\"\" Get a list of current vNICs in", "\"yes\" or \"no\". ***' print '' cconfirm_add_vlan = raw_input( \"Would you like to", "warnings.filterwarnings(\"ignore\") def ssl_workaround(): \"\"\" Workaround for SSL certification error that prevents proper UCS", "Domain \"\"\" HANDLE.Login(IP_ADDRESS, USERNAME, PASSWORD) def current_vlans(): \"\"\" Get a list of all", "in current_vlans.list.items(): if add_vlans.vlan_name in str(key): print '' print 'The following VLAN has", "if obj != None: for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if", "if str(prop) == \"Dn\": org_name = mo.getattr(prop) current_orgs.list.append(org_name) current_orgs.list.remove('org-root') def add_vlan_to_vnic(): \"\"\" Add", "= mo.getattr(prop) if str(prop) == \"PolicyOwner\": policy_owner = mo.getattr(prop) if str(prop) == \"NwCtrlPolicyName\":", "add_vlan_to_vnic.vnic_name = raw_input('vNIC Template Name: ') print '' obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId(), {", "add_vlans.confirm_new_vlan = raw_input( 'Would you like to add a new VLAN? (yes/no): ')", "UserWarning: [Warning]: AddManagedObject [Description]:Expected Naming Property Name for ClassId VnicLanConnTempl not found warnings.warn(string)", "for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vnic_template_name = mo.getattr(prop) current_vnic_templates.list.append(vnic_template_name) def", "ssl._create_default_https_context = ssl._create_unverified_context def connect(): \"\"\" Establish a connection to the UCS Domain", "in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": org_name = mo.getattr(prop) current_orgs.list.append(org_name) current_orgs.list.remove('org-root') def add_vlan_to_vnic():", "sys import warnings ''' Supress the following warning message which does not affect", "= mo.getattr(prop) HANDLE.StartTransaction() vnic_obj = HANDLE.GetManagedObject( None, None, {\"Dn\": \"{}\".format(organization)}) mo = HANDLE.AddManagedObject(vnic_obj,", "to a vNIC template? (yes/no): \") if confirm_add_vlan not in ['no' or 'n']:", "' + name + ' (' + ID + ')' add_vlans() if add_vlans.confirm_new_vlan", "used in add_vlan_to_vnic \"\"\" current_orgs.list = [] obj = HANDLE.GetManagedObject(None, OrgOrg.ClassId()) if obj", "mo.getattr(prop) if str(prop) == \"TemplType\": templ_type = mo.getattr(prop) if str(prop) == \"StatsPolicyName\": stats_policy_name", "VLAN ID: ') obj = HANDLE.GetManagedObject(None, None, {\"Dn\": \"fabric/lan\"}) HANDLE.AddManagedObject(obj, \"fabricVlan\", {\"DefaultNet\": \"no\",", "'The following VLAN has been created: ' print '' print '- ' +", "\"QosPolicyName\": qos_policy_name = mo.getattr(prop) if str(prop) == \"Descr\": descr = mo.getattr(prop) if str(prop)", "= HANDLE.AddManagedObject(mo, \"vnicEtherIf\", { \"DefaultNet\": \"no\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Dn\": \"{}/if-{}\".format(dn, add_vlans.vlan_name)}, True) HANDLE.CompleteTransaction()", "USERNAME = \"\" PASSWORD = \"\" HANDLE = UcsHandle() HANDLE = UcsHandle() connect()", "Template Name: ') print '' obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId(), { VnicLanConnTempl.RN: \"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)}) if", "'Would you like to add a new VLAN? (yes/no): ') while add_vlans.confirm_new_vlan not", "list of current vNICs in UCS \"\"\" current_vnic_templates.list = [] obj = HANDLE.GetManagedObject(None,", "current_orgs() add_vlan_to_vnic() print (\"The \" + '\"' + add_vlans.vlan_name + '\"' + \"", "\"{}\".format(switch_id)}, True) mo_1 = HANDLE.AddManagedObject(mo, \"vnicEtherIf\", { \"DefaultNet\": \"no\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Dn\": \"{}/if-{}\".format(dn,", "\"CompressionType\": \"included\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Sharing\": \"none\", \"McastPolicyName\": \"\", \"Id\": \"{}\".format(vlan_id)}) current_vlans() for key,", "if str(prop) == \"IdentPoolName\": ident_pool_name = mo.getattr(prop) if str(prop) == \"QosPolicyName\": qos_policy_name =", "in add_vlan_to_vnic \"\"\" current_orgs.list = [] obj = HANDLE.GetManagedObject(None, OrgOrg.ClassId()) if obj !=", "mo.getattr(prop) if str(prop) == \"Mtu\": mtu = mo.getattr(prop) if str(prop) == \"PinToGroupName\": pin_to_group_name", "str(prop) == \"PinToGroupName\": pin_to_group_name = mo.getattr(prop) if str(prop) == \"SwitchId\": switch_id = mo.getattr(prop)", "when using Python 2.7 or higher. Credit to user <NAME> (ragupta4) on the", "if add_vlans.vlan_name in str(key): print '' print 'The following VLAN has been created:", "mo.getattr(prop) if str(prop) == \"SwitchId\": switch_id = mo.getattr(prop) HANDLE.StartTransaction() vnic_obj = HANDLE.GetManagedObject( None,", "'n']: print add_vlans.vlan_name = raw_input('Enter the VLAN Name: ') vlan_id = raw_input('Enter the", "print '' add_vlans.confirm_new_vlan = raw_input( 'Would you like to add a new VLAN?", "print '*** Error: Please enter either \"yes\" or \"no\". ***' print '' add_vlans.confirm_new_vlan", "\"org-root\" if str(prop) == \"IdentPoolName\": ident_pool_name = mo.getattr(prop) if str(prop) == \"QosPolicyName\": qos_policy_name", "= raw_input('vNIC Template Name: ') print '' obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId(), { VnicLanConnTempl.RN:", "HANDLE.Login(IP_ADDRESS, USERNAME, PASSWORD) def current_vlans(): \"\"\" Get a list of all current VLANs", "\"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)}) if obj != None: for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name):", "UcsSdk import UcsHandle from UcsSdk import UcsUtils from UcsSdk.MoMeta.FabricVlan import FabricVlan from UcsSdk.MoMeta.VnicLanConnTempl", "+ '\"' + \" VLAN to a vNIC template? (yes/no): \") while confirm_add_vlan", "VLAN? (yes/no): ') if add_vlans.confirm_new_vlan not in ['no' or 'n']: print add_vlans.vlan_name =", "\"SwitchId\": \"{}\".format(switch_id)}, True) mo_1 = HANDLE.AddManagedObject(mo, \"vnicEtherIf\", { \"DefaultNet\": \"no\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Dn\":", "= HANDLE.AddManagedObject(vnic_obj, \"vnicLanConnTempl\", {\"IdentPoolName\": \"{}\".format(ident_pool_name), \"Dn\": \"{}\".format(dn), \"QosPolicyName\": \"{}\".format(qos_policy_name), \"Descr\": \"{}\".format(descr), \"PolicyOwner\": \"{}\".format(policy_owner),", "org_name = mo.getattr(prop) current_orgs.list.append(org_name) current_orgs.list.remove('org-root') def add_vlan_to_vnic(): \"\"\" Add a VLAN to a", "templ_type = mo.getattr(prop) if str(prop) == \"StatsPolicyName\": stats_policy_name = mo.getattr(prop) if str(prop) ==", "add_vlans.vlan_name in str(key): print '' print 'The following VLAN has been created: '", "warnings.warn(string) ''' warnings.filterwarnings(\"ignore\") def ssl_workaround(): \"\"\" Workaround for SSL certification error that prevents", "Name: ') vlan_id = raw_input('Enter the VLAN ID: ') obj = HANDLE.GetManagedObject(None, None,", "Workaround for SSL certification error that prevents proper UCS domain login when using", "or \"no\". ***' print '' add_vlans.confirm_new_vlan = raw_input( 'Would you like to add", "new VLAN? (yes/no): ') if add_vlans.confirm_new_vlan not in ['no' or 'n']: print add_vlans.vlan_name", "for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": org_name = mo.getattr(prop) current_orgs.list.append(org_name) current_orgs.list.remove('org-root')", "== \"PolicyOwner\": policy_owner = mo.getattr(prop) if str(prop) == \"NwCtrlPolicyName\": nw_ctrl_policy_name = mo.getattr(prop) if", "\"{}\".format(stats_policy_name), \"Mtu\": \"{}\".format(mtu), \"PinToGroupName\": \"{}\".format(pin_to_group_name), \"SwitchId\": \"{}\".format(switch_id)}, True) mo_1 = HANDLE.AddManagedObject(mo, \"vnicEtherIf\", {", "not in ['yes', 'y', 'no', 'n']: print '' print '*** Error: Please enter", "VLANs \"\"\" current_vlans.list = {} obj = HANDLE.GetManagedObject(None, FabricVlan.ClassId()) if obj != None:", "import UcsUtils from UcsSdk.MoMeta.FabricVlan import FabricVlan from UcsSdk.MoMeta.VnicLanConnTempl import VnicLanConnTempl from UcsSdk.MoMeta.OrgOrg import", "' print '' current_vnic_templates() for name in current_vnic_templates.list: print '- ' + name", "UCS Communities \"\"\" is_verify_certificate = False if not sys.version_info < (2, 6): from", "None, None, {\"Dn\": \"{}\".format(organization)}) mo = HANDLE.AddManagedObject(vnic_obj, \"vnicLanConnTempl\", {\"IdentPoolName\": \"{}\".format(ident_pool_name), \"Dn\": \"{}\".format(dn), \"QosPolicyName\":", "so proceed accordingly. \"\"\" from UcsSdk import UcsHandle from UcsSdk import UcsUtils from", "add_vlans.vlan_name + '\"' + \" VLAN has been added to \" '\"' +", "= mo.getattr(prop) if str(prop) == \"Mtu\": mtu = mo.getattr(prop) if str(prop) == \"PinToGroupName\":", "Manager VLAN Management\" print '' print 'Current VLANs:' current_vlans() print '' for name,", "\"StatsPolicyName\": \"{}\".format(stats_policy_name), \"Mtu\": \"{}\".format(mtu), \"PinToGroupName\": \"{}\".format(pin_to_group_name), \"SwitchId\": \"{}\".format(switch_id)}, True) mo_1 = HANDLE.AddManagedObject(mo, \"vnicEtherIf\",", "warnings ''' Supress the following warning message which does not affect funcationality: /Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064:", "mo.getattr(prop) if str(prop) == \"NwCtrlPolicyName\": nw_ctrl_policy_name = mo.getattr(prop) if str(prop) == \"TemplType\": templ_type", "following warning message which does not affect funcationality: /Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064: UserWarning: [Warning]: AddManagedObject [Description]:Expected", "handling present so proceed accordingly. \"\"\" from UcsSdk import UcsHandle from UcsSdk import", "the \" + '\"' + add_vlans.vlan_name + '\"' + \" VLAN to a", "raw_input('Enter the VLAN ID: ') obj = HANDLE.GetManagedObject(None, None, {\"Dn\": \"fabric/lan\"}) HANDLE.AddManagedObject(obj, \"fabricVlan\",", "raw_input('Enter the VLAN Name: ') vlan_id = raw_input('Enter the VLAN ID: ') obj", "Python CLI interface that utilizes the Cisco UCS SDK to: - Connect to", "if str(prop) == \"Id\": vlan_id = mo.getattr(prop) current_vlans.list.update({vlan_name: vlan_id}) def add_vlans(): \"\"\" Create", "print '' for name, ID in current_vlans.list.iteritems(): print '- ' + name +", "stats_policy_name = mo.getattr(prop) if str(prop) == \"Mtu\": mtu = mo.getattr(prop) if str(prop) ==", "str(prop) == \"Name\": vnic_template_name = mo.getattr(prop) current_vnic_templates.list.append(vnic_template_name) def current_orgs(): \"\"\" Get a list", "current_vlans.list.update({vlan_name: vlan_id}) def add_vlans(): \"\"\" Create new VLANs on UCS. \"\"\" print ''", "str(prop) == \"Dn\": dn = mo.getattr(prop) for org in current_orgs.list: if org in", "== \"TemplType\": templ_type = mo.getattr(prop) if str(prop) == \"StatsPolicyName\": stats_policy_name = mo.getattr(prop) if", "current_vnic_templates() for name in current_vnic_templates.list: print '- ' + name print '' confirm_add_vlan", "\" '\"' + add_vlan_to_vnic.vnic_name + '\"' + \" vNIC template.\") print else: print", "UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": org_name = mo.getattr(prop) current_orgs.list.append(org_name) current_orgs.list.remove('org-root') def add_vlan_to_vnic(): \"\"\"", "organization = org else: organization = \"org-root\" if str(prop) == \"IdentPoolName\": ident_pool_name =", "\"\"\" from UcsSdk import UcsHandle from UcsSdk import UcsUtils from UcsSdk.MoMeta.FabricVlan import FabricVlan", "login when using Python 2.7 or higher. Credit to user <NAME> (ragupta4) on", "'Current vNIC Templates: ' print '' current_vnic_templates() for name in current_vnic_templates.list: print '-", "or \"no\". ***' print '' cconfirm_add_vlan = raw_input( \"Would you like to add", "ssl_version=ssl.PROTOCOL_TLSv1) if not sys.version_info < (2, 7, 9) and not is_verify_certificate: ssl._create_default_https_context =", "= mo.getattr(prop) current_vnic_templates.list.append(vnic_template_name) def current_orgs(): \"\"\" Get a list of the current organizations", "raw_input('vNIC Template Name: ') print '' obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId(), { VnicLanConnTempl.RN: \"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)})", "<NAME> (ragupta4) on the Cisco UCS Communities \"\"\" is_verify_certificate = False if not", "funcationality: /Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064: UserWarning: [Warning]: AddManagedObject [Description]:Expected Naming Property Name for ClassId VnicLanConnTempl not", "you like to add a new VLAN? (yes/no): ') if add_vlans.confirm_new_vlan not in", "is_verify_certificate: ssl._create_default_https_context = ssl._create_unverified_context def connect(): \"\"\" Establish a connection to the UCS", "HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId()) if obj != None: for mo in obj: for prop in", "'' confirm_add_vlan = raw_input( \"Would you like to add the \" + '\"'", "'' print '*** Error: Please enter either \"yes\" or \"no\". ***' print ''", "if str(prop) == \"Dn\": dn = mo.getattr(prop) for org in current_orgs.list: if org", "does not affect funcationality: /Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064: UserWarning: [Warning]: AddManagedObject [Description]:Expected Naming Property Name for", "in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vnic_template_name = mo.getattr(prop) current_vnic_templates.list.append(vnic_template_name) def current_orgs(): \"\"\"", "current_orgs.list.remove('org-root') def add_vlan_to_vnic(): \"\"\" Add a VLAN to a vNIC template \"\"\" print", "\"\"\" A Python CLI interface that utilizes the Cisco UCS SDK to: -", "\"fabricVlan\", {\"DefaultNet\": \"no\", \"PubNwName\": \"\", \"Dn\": \"fabric/lan/net-{}\".format(add_vlans.vlan_name), \"PolicyOwner\": \"local\", \"CompressionType\": \"included\", \"Name\": \"{}\".format(add_vlans.vlan_name),", "UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vlan_name = mo.getattr(prop) if str(prop) == \"Id\": vlan_id", "- Connect to a UCSM domain - View and Add VLANs - Add", "Cisco UCS SDK to: - Connect to a UCSM domain - View and", "and not is_verify_certificate: ssl._create_default_https_context = ssl._create_unverified_context def connect(): \"\"\" Establish a connection to", "= mo.getattr(prop) if str(prop) == \"PinToGroupName\": pin_to_group_name = mo.getattr(prop) if str(prop) == \"SwitchId\":", "UcsHandle() connect() print '' print \"Cisco UCS Manager VLAN Management\" print '' print", "'- ' + name print '' confirm_add_vlan = raw_input( \"Would you like to", "pin_to_group_name = mo.getattr(prop) if str(prop) == \"SwitchId\": switch_id = mo.getattr(prop) HANDLE.StartTransaction() vnic_obj =", "HANDLE.GetManagedObject(None, FabricVlan.ClassId()) if obj != None: for mo in obj: for prop in", "that utilizes the Cisco UCS SDK to: - Connect to a UCSM domain", "in str(key): print '' print 'The following VLAN has been created: ' print", "ident_pool_name = mo.getattr(prop) if str(prop) == \"QosPolicyName\": qos_policy_name = mo.getattr(prop) if str(prop) ==", "None: for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\":", "if add_vlans.confirm_new_vlan not in ['no' or 'n']: print '' print 'Current vNIC Templates:", "add_vlans.confirm_new_vlan not in ['no' or 'n']: print '' print 'Current vNIC Templates: '", "connect(): \"\"\" Establish a connection to the UCS Domain \"\"\" HANDLE.Login(IP_ADDRESS, USERNAME, PASSWORD)", "in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vlan_name = mo.getattr(prop)", "Error: Please enter either \"yes\" or \"no\". ***' print '' cconfirm_add_vlan = raw_input(", "\"\" HANDLE = UcsHandle() HANDLE = UcsHandle() connect() print '' print \"Cisco UCS", "for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vlan_name", "== \"QosPolicyName\": qos_policy_name = mo.getattr(prop) if str(prop) == \"Descr\": descr = mo.getattr(prop) if", "from UcsSdk.MoMeta.FabricVlan import FabricVlan from UcsSdk.MoMeta.VnicLanConnTempl import VnicLanConnTempl from UcsSdk.MoMeta.OrgOrg import OrgOrg import", "Add a VLAN to a vNIC Please note that there is very little", "obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": dn = mo.getattr(prop) for", "\"Dn\": \"fabric/lan/net-{}\".format(add_vlans.vlan_name), \"PolicyOwner\": \"local\", \"CompressionType\": \"included\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Sharing\": \"none\", \"McastPolicyName\": \"\", \"Id\":", "''' warnings.filterwarnings(\"ignore\") def ssl_workaround(): \"\"\" Workaround for SSL certification error that prevents proper", "= mo.getattr(prop) if str(prop) == \"TemplType\": templ_type = mo.getattr(prop) if str(prop) == \"StatsPolicyName\":", "OrgOrg import sys import warnings ''' Supress the following warning message which does", "VnicLanConnTempl.ClassId(), { VnicLanConnTempl.RN: \"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)}) if obj != None: for mo in obj: for", "{ \"DefaultNet\": \"no\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Dn\": \"{}/if-{}\".format(dn, add_vlans.vlan_name)}, True) HANDLE.CompleteTransaction() ssl_workaround() IP_ADDRESS =", "if str(prop) == \"PolicyOwner\": policy_owner = mo.getattr(prop) if str(prop) == \"NwCtrlPolicyName\": nw_ctrl_policy_name =", "ssl_workaround(): \"\"\" Workaround for SSL certification error that prevents proper UCS domain login", "on UCS. \"\"\" print '' add_vlans.confirm_new_vlan = raw_input( 'Would you like to add", "\"NwCtrlPolicyName\": nw_ctrl_policy_name = mo.getattr(prop) if str(prop) == \"TemplType\": templ_type = mo.getattr(prop) if str(prop)", "VnicLanConnTempl not found warnings.warn(string) ''' warnings.filterwarnings(\"ignore\") def ssl_workaround(): \"\"\" Workaround for SSL certification", "to the UCS Domain \"\"\" HANDLE.Login(IP_ADDRESS, USERNAME, PASSWORD) def current_vlans(): \"\"\" Get a", "if confirm_add_vlan not in ['no' or 'n']: current_orgs() add_vlan_to_vnic() print (\"The \" +", "vnic_template_name = mo.getattr(prop) current_vnic_templates.list.append(vnic_template_name) def current_orgs(): \"\"\" Get a list of the current", "= [] obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId()) if obj != None: for mo in", "add_vlan_to_vnic \"\"\" current_orgs.list = [] obj = HANDLE.GetManagedObject(None, OrgOrg.ClassId()) if obj != None:", "the current organizations in UCS which will be used in add_vlan_to_vnic \"\"\" current_orgs.list", "in mo.getattr(prop): organization = org else: organization = \"org-root\" if str(prop) == \"IdentPoolName\":", "if str(prop) == \"TemplType\": templ_type = mo.getattr(prop) if str(prop) == \"StatsPolicyName\": stats_policy_name =", "in ['no' or 'n']: print '' print 'Current vNIC Templates: ' print ''", "very little error handling present so proceed accordingly. \"\"\" from UcsSdk import UcsHandle", "\"{}\".format(policy_owner), \"NwCtrlPolicyName\": \"{}\".format(nw_ctrl_policy_name), \"TemplType\": \"{}\".format(templ_type), \"StatsPolicyName\": \"{}\".format(stats_policy_name), \"Mtu\": \"{}\".format(mtu), \"PinToGroupName\": \"{}\".format(pin_to_group_name), \"SwitchId\": \"{}\".format(switch_id)},", "a UCSM domain - View and Add VLANs - Add a VLAN to", "a vNIC Please note that there is very little error handling present so", "HANDLE = UcsHandle() HANDLE = UcsHandle() connect() print '' print \"Cisco UCS Manager", "has been created: ' print '' print '- ' + key + '", "print 'The following VLAN has been created: ' print '' print '- '", "'- ' + key + ' (' + value + ')' def current_vnic_templates():", "+ ')' add_vlans() if add_vlans.confirm_new_vlan not in ['no' or 'n']: print '' print", "')' def current_vnic_templates(): \"\"\" Get a list of current vNICs in UCS \"\"\"", "\"PinToGroupName\": pin_to_group_name = mo.getattr(prop) if str(prop) == \"SwitchId\": switch_id = mo.getattr(prop) HANDLE.StartTransaction() vnic_obj", "a VLAN to a vNIC template \"\"\" print add_vlan_to_vnic.vnic_name = raw_input('vNIC Template Name:", "current vNICs in UCS \"\"\" current_vnic_templates.list = [] obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId()) if", "to a vNIC Please note that there is very little error handling present", "the Cisco UCS SDK to: - Connect to a UCSM domain - View", "VLAN to a vNIC template? (yes/no): \") if confirm_add_vlan not in ['no' or", "print \"Cisco UCS Manager VLAN Management\" print '' print 'Current VLANs:' current_vlans() print", "print (\"The \" + '\"' + add_vlans.vlan_name + '\"' + \" VLAN has", "'- ' + name + ' (' + ID + ')' add_vlans() if", "obj = HANDLE.GetManagedObject(None, OrgOrg.ClassId()) if obj != None: for mo in obj: for", "- View and Add VLANs - Add a VLAN to a vNIC Please", "(2, 7, 9) and not is_verify_certificate: ssl._create_default_https_context = ssl._create_unverified_context def connect(): \"\"\" Establish", "\"\"\" Get a list of current vNICs in UCS \"\"\" current_vnic_templates.list = []", "Name for ClassId VnicLanConnTempl not found warnings.warn(string) ''' warnings.filterwarnings(\"ignore\") def ssl_workaround(): \"\"\" Workaround", "else: organization = \"org-root\" if str(prop) == \"IdentPoolName\": ident_pool_name = mo.getattr(prop) if str(prop)", "note that there is very little error handling present so proceed accordingly. \"\"\"", "str(prop) == \"StatsPolicyName\": stats_policy_name = mo.getattr(prop) if str(prop) == \"Mtu\": mtu = mo.getattr(prop)", "\"{}\".format(add_vlans.vlan_name), \"Dn\": \"{}/if-{}\".format(dn, add_vlans.vlan_name)}, True) HANDLE.CompleteTransaction() ssl_workaround() IP_ADDRESS = \"\" USERNAME = \"\"", "None, {\"Dn\": \"fabric/lan\"}) HANDLE.AddManagedObject(obj, \"fabricVlan\", {\"DefaultNet\": \"no\", \"PubNwName\": \"\", \"Dn\": \"fabric/lan/net-{}\".format(add_vlans.vlan_name), \"PolicyOwner\": \"local\",", "connect() print '' print \"Cisco UCS Manager VLAN Management\" print '' print 'Current", "higher. Credit to user <NAME> (ragupta4) on the Cisco UCS Communities \"\"\" is_verify_certificate", "print '' confirm_add_vlan = raw_input( \"Would you like to add the \" +", "False if not sys.version_info < (2, 6): from functools import partial import ssl", "template \"\"\" print add_vlan_to_vnic.vnic_name = raw_input('vNIC Template Name: ') print '' obj =", "either \"yes\" or \"no\". ***' print '' add_vlans.confirm_new_vlan = raw_input( 'Would you like", "\" VLAN to a vNIC template? (yes/no): \") while confirm_add_vlan not in ['yes',", "\"\"\" Establish a connection to the UCS Domain \"\"\" HANDLE.Login(IP_ADDRESS, USERNAME, PASSWORD) def", "add_vlans.confirm_new_vlan not in ['no' or 'n']: print add_vlans.vlan_name = raw_input('Enter the VLAN Name:", "import sys import warnings ''' Supress the following warning message which does not", "\"{}\".format(add_vlans.vlan_name), \"Sharing\": \"none\", \"McastPolicyName\": \"\", \"Id\": \"{}\".format(vlan_id)}) current_vlans() for key, value in current_vlans.list.items():", "organization = \"org-root\" if str(prop) == \"IdentPoolName\": ident_pool_name = mo.getattr(prop) if str(prop) ==", "str(prop) == \"Id\": vlan_id = mo.getattr(prop) current_vlans.list.update({vlan_name: vlan_id}) def add_vlans(): \"\"\" Create new", "name + ' (' + ID + ')' add_vlans() if add_vlans.confirm_new_vlan not in", "vNIC Templates: ' print '' current_vnic_templates() for name in current_vnic_templates.list: print '- '", "\"PolicyOwner\": \"{}\".format(policy_owner), \"NwCtrlPolicyName\": \"{}\".format(nw_ctrl_policy_name), \"TemplType\": \"{}\".format(templ_type), \"StatsPolicyName\": \"{}\".format(stats_policy_name), \"Mtu\": \"{}\".format(mtu), \"PinToGroupName\": \"{}\".format(pin_to_group_name), \"SwitchId\":", "mo.getattr(prop) if str(prop) == \"PolicyOwner\": policy_owner = mo.getattr(prop) if str(prop) == \"NwCtrlPolicyName\": nw_ctrl_policy_name", "will be used in add_vlan_to_vnic \"\"\" current_orgs.list = [] obj = HANDLE.GetManagedObject(None, OrgOrg.ClassId())", "in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": dn = mo.getattr(prop)", "'' obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId(), { VnicLanConnTempl.RN: \"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)}) if obj != None: for", "if str(prop) == \"StatsPolicyName\": stats_policy_name = mo.getattr(prop) if str(prop) == \"Mtu\": mtu =", "= UcsHandle() connect() print '' print \"Cisco UCS Manager VLAN Management\" print ''", "partial import ssl ssl.wrap_socket = partial( ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) if not sys.version_info < (2,", "Management\" print '' print 'Current VLANs:' current_vlans() print '' for name, ID in", "Error: Please enter either \"yes\" or \"no\". ***' print '' add_vlans.confirm_new_vlan = raw_input(", "a list of current vNICs in UCS \"\"\" current_vnic_templates.list = [] obj =", "VLANs:' current_vlans() print '' for name, ID in current_vlans.list.iteritems(): print '- ' +", "') while add_vlans.confirm_new_vlan not in ['yes', 'y', 'no', 'n']: print '' print '***", "print '- ' + name + ' (' + ID + ')' add_vlans()", "UCS SDK to: - Connect to a UCSM domain - View and Add", "Supress the following warning message which does not affect funcationality: /Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064: UserWarning: [Warning]:", "ssl._create_unverified_context def connect(): \"\"\" Establish a connection to the UCS Domain \"\"\" HANDLE.Login(IP_ADDRESS,", "cconfirm_add_vlan = raw_input( \"Would you like to add the \" + '\"' +", "= {} obj = HANDLE.GetManagedObject(None, FabricVlan.ClassId()) if obj != None: for mo in", "'\"' + add_vlans.vlan_name + '\"' + \" VLAN has been added to \"", "mo_1 = HANDLE.AddManagedObject(mo, \"vnicEtherIf\", { \"DefaultNet\": \"no\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Dn\": \"{}/if-{}\".format(dn, add_vlans.vlan_name)}, True)", "value in current_vlans.list.items(): if add_vlans.vlan_name in str(key): print '' print 'The following VLAN", "/Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064: UserWarning: [Warning]: AddManagedObject [Description]:Expected Naming Property Name for ClassId VnicLanConnTempl not found", "mo.getattr(prop) current_vlans.list.update({vlan_name: vlan_id}) def add_vlans(): \"\"\" Create new VLANs on UCS. \"\"\" print", "accordingly. \"\"\" from UcsSdk import UcsHandle from UcsSdk import UcsUtils from UcsSdk.MoMeta.FabricVlan import", "UcsSdk import UcsUtils from UcsSdk.MoMeta.FabricVlan import FabricVlan from UcsSdk.MoMeta.VnicLanConnTempl import VnicLanConnTempl from UcsSdk.MoMeta.OrgOrg", "confirm_add_vlan not in ['no' or 'n']: current_orgs() add_vlan_to_vnic() print (\"The \" + '\"'", "if str(prop) == \"QosPolicyName\": qos_policy_name = mo.getattr(prop) if str(prop) == \"Descr\": descr =", "mo.getattr(prop): organization = org else: organization = \"org-root\" if str(prop) == \"IdentPoolName\": ident_pool_name", "mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vlan_name =", "= mo.getattr(prop) if str(prop) == \"Descr\": descr = mo.getattr(prop) if str(prop) == \"PolicyOwner\":", "if str(prop) == \"NwCtrlPolicyName\": nw_ctrl_policy_name = mo.getattr(prop) if str(prop) == \"TemplType\": templ_type =", "(yes/no): ') if add_vlans.confirm_new_vlan not in ['no' or 'n']: print add_vlans.vlan_name = raw_input('Enter", "\" VLAN to a vNIC template? (yes/no): \") if confirm_add_vlan not in ['no'", "utilizes the Cisco UCS SDK to: - Connect to a UCSM domain -", "proper UCS domain login when using Python 2.7 or higher. Credit to user", "str(prop) == \"Descr\": descr = mo.getattr(prop) if str(prop) == \"PolicyOwner\": policy_owner = mo.getattr(prop)", "\"NwCtrlPolicyName\": \"{}\".format(nw_ctrl_policy_name), \"TemplType\": \"{}\".format(templ_type), \"StatsPolicyName\": \"{}\".format(stats_policy_name), \"Mtu\": \"{}\".format(mtu), \"PinToGroupName\": \"{}\".format(pin_to_group_name), \"SwitchId\": \"{}\".format(switch_id)}, True)", "mo.getattr(prop) if str(prop) == \"Id\": vlan_id = mo.getattr(prop) current_vlans.list.update({vlan_name: vlan_id}) def add_vlans(): \"\"\"", "HANDLE.CompleteTransaction() ssl_workaround() IP_ADDRESS = \"\" USERNAME = \"\" PASSWORD = \"\" HANDLE =", "== \"SwitchId\": switch_id = mo.getattr(prop) HANDLE.StartTransaction() vnic_obj = HANDLE.GetManagedObject( None, None, {\"Dn\": \"{}\".format(organization)})", "descr = mo.getattr(prop) if str(prop) == \"PolicyOwner\": policy_owner = mo.getattr(prop) if str(prop) ==", "'' add_vlans.confirm_new_vlan = raw_input( 'Would you like to add a new VLAN? (yes/no):", "= HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId()) if obj != None: for mo in obj: for prop", "the UCS Domain \"\"\" HANDLE.Login(IP_ADDRESS, USERNAME, PASSWORD) def current_vlans(): \"\"\" Get a list", "***' print '' cconfirm_add_vlan = raw_input( \"Would you like to add the \"", "str(prop) == \"QosPolicyName\": qos_policy_name = mo.getattr(prop) if str(prop) == \"Descr\": descr = mo.getattr(prop)", "== \"Dn\": dn = mo.getattr(prop) for org in current_orgs.list: if org in mo.getattr(prop):", "like to add the \" + '\"' + add_vlans.vlan_name + '\"' + \"", "= mo.getattr(prop) if str(prop) == \"QosPolicyName\": qos_policy_name = mo.getattr(prop) if str(prop) == \"Descr\":", "= [] obj = HANDLE.GetManagedObject(None, OrgOrg.ClassId()) if obj != None: for mo in", "'\"' + add_vlans.vlan_name + '\"' + \" VLAN to a vNIC template? (yes/no):", "add_vlans(): \"\"\" Create new VLANs on UCS. \"\"\" print '' add_vlans.confirm_new_vlan = raw_input(", "' + key + ' (' + value + ')' def current_vnic_templates(): \"\"\"", "VnicLanConnTempl from UcsSdk.MoMeta.OrgOrg import OrgOrg import sys import warnings ''' Supress the following", "list of the current organizations in UCS which will be used in add_vlan_to_vnic", "(\"The \" + '\"' + add_vlans.vlan_name + '\"' + \" VLAN has been", "{\"Dn\": \"fabric/lan\"}) HANDLE.AddManagedObject(obj, \"fabricVlan\", {\"DefaultNet\": \"no\", \"PubNwName\": \"\", \"Dn\": \"fabric/lan/net-{}\".format(add_vlans.vlan_name), \"PolicyOwner\": \"local\", \"CompressionType\":", "to: - Connect to a UCSM domain - View and Add VLANs -", "mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vnic_template_name =", "Please enter either \"yes\" or \"no\". ***' print '' cconfirm_add_vlan = raw_input( \"Would", "add_vlans() if add_vlans.confirm_new_vlan not in ['no' or 'n']: print '' print 'Current vNIC", "from UcsSdk.MoMeta.VnicLanConnTempl import VnicLanConnTempl from UcsSdk.MoMeta.OrgOrg import OrgOrg import sys import warnings '''", "\"included\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Sharing\": \"none\", \"McastPolicyName\": \"\", \"Id\": \"{}\".format(vlan_id)}) current_vlans() for key, value", "name in current_vnic_templates.list: print '- ' + name print '' confirm_add_vlan = raw_input(", "'*** Error: Please enter either \"yes\" or \"no\". ***' print '' cconfirm_add_vlan =", "Get a list of current vNICs in UCS \"\"\" current_vnic_templates.list = [] obj", "mo.getattr(prop) if str(prop) == \"QosPolicyName\": qos_policy_name = mo.getattr(prop) if str(prop) == \"Descr\": descr", "add a new VLAN? (yes/no): ') if add_vlans.confirm_new_vlan not in ['no' or 'n']:", "'\"' + \" VLAN to a vNIC template? (yes/no): \") if confirm_add_vlan not", "VLAN to a vNIC template \"\"\" print add_vlan_to_vnic.vnic_name = raw_input('vNIC Template Name: ')", "vNIC template \"\"\" print add_vlan_to_vnic.vnic_name = raw_input('vNIC Template Name: ') print '' obj", "HANDLE.AddManagedObject(vnic_obj, \"vnicLanConnTempl\", {\"IdentPoolName\": \"{}\".format(ident_pool_name), \"Dn\": \"{}\".format(dn), \"QosPolicyName\": \"{}\".format(qos_policy_name), \"Descr\": \"{}\".format(descr), \"PolicyOwner\": \"{}\".format(policy_owner), \"NwCtrlPolicyName\":", "in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": org_name = mo.getattr(prop)", "str(prop) == \"TemplType\": templ_type = mo.getattr(prop) if str(prop) == \"StatsPolicyName\": stats_policy_name = mo.getattr(prop)", "import OrgOrg import sys import warnings ''' Supress the following warning message which", "that there is very little error handling present so proceed accordingly. \"\"\" from", "def add_vlan_to_vnic(): \"\"\" Add a VLAN to a vNIC template \"\"\" print add_vlan_to_vnic.vnic_name", "for SSL certification error that prevents proper UCS domain login when using Python", "'' for name, ID in current_vlans.list.iteritems(): print '- ' + name + '", "ID: ') obj = HANDLE.GetManagedObject(None, None, {\"Dn\": \"fabric/lan\"}) HANDLE.AddManagedObject(obj, \"fabricVlan\", {\"DefaultNet\": \"no\", \"PubNwName\":", "for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vnic_template_name", "to a vNIC template \"\"\" print add_vlan_to_vnic.vnic_name = raw_input('vNIC Template Name: ') print", "2.7 or higher. Credit to user <NAME> (ragupta4) on the Cisco UCS Communities", "add_vlans.vlan_name = raw_input('Enter the VLAN Name: ') vlan_id = raw_input('Enter the VLAN ID:", "HANDLE.AddManagedObject(mo, \"vnicEtherIf\", { \"DefaultNet\": \"no\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Dn\": \"{}/if-{}\".format(dn, add_vlans.vlan_name)}, True) HANDLE.CompleteTransaction() ssl_workaround()", "') vlan_id = raw_input('Enter the VLAN ID: ') obj = HANDLE.GetManagedObject(None, None, {\"Dn\":", "ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) if not sys.version_info < (2, 7, 9) and not is_verify_certificate: ssl._create_default_https_context", "VLAN has been created: ' print '' print '- ' + key +", "\"\"\" Get a list of the current organizations in UCS which will be", "\"Dn\": dn = mo.getattr(prop) for org in current_orgs.list: if org in mo.getattr(prop): organization", "current_orgs.list.append(org_name) current_orgs.list.remove('org-root') def add_vlan_to_vnic(): \"\"\" Add a VLAN to a vNIC template \"\"\"", "FabricVlan.ClassId()) if obj != None: for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name):", "= \"org-root\" if str(prop) == \"IdentPoolName\": ident_pool_name = mo.getattr(prop) if str(prop) == \"QosPolicyName\":", "print 'Current VLANs:' current_vlans() print '' for name, ID in current_vlans.list.iteritems(): print '-", "\" + '\"' + add_vlans.vlan_name + '\"' + \" VLAN to a vNIC", "message which does not affect funcationality: /Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064: UserWarning: [Warning]: AddManagedObject [Description]:Expected Naming Property", "+ value + ')' def current_vnic_templates(): \"\"\" Get a list of current vNICs", "\"no\". ***' print '' cconfirm_add_vlan = raw_input( \"Would you like to add the", "= mo.getattr(prop) if str(prop) == \"Id\": vlan_id = mo.getattr(prop) current_vlans.list.update({vlan_name: vlan_id}) def add_vlans():", "Python 2.7 or higher. Credit to user <NAME> (ragupta4) on the Cisco UCS", "connection to the UCS Domain \"\"\" HANDLE.Login(IP_ADDRESS, USERNAME, PASSWORD) def current_vlans(): \"\"\" Get", "prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vnic_template_name = mo.getattr(prop) current_vnic_templates.list.append(vnic_template_name) def current_orgs():", "prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": org_name = mo.getattr(prop) current_orgs.list.append(org_name) current_orgs.list.remove('org-root') def", "if str(prop) == \"Name\": vnic_template_name = mo.getattr(prop) current_vnic_templates.list.append(vnic_template_name) def current_orgs(): \"\"\" Get a", "vlan_id}) def add_vlans(): \"\"\" Create new VLANs on UCS. \"\"\" print '' add_vlans.confirm_new_vlan", "current_vlans() print '' for name, ID in current_vlans.list.iteritems(): print '- ' + name", "for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": org_name", "list of all current VLANs \"\"\" current_vlans.list = {} obj = HANDLE.GetManagedObject(None, FabricVlan.ClassId())", "\"local\", \"CompressionType\": \"included\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Sharing\": \"none\", \"McastPolicyName\": \"\", \"Id\": \"{}\".format(vlan_id)}) current_vlans() for", "present so proceed accordingly. \"\"\" from UcsSdk import UcsHandle from UcsSdk import UcsUtils", "print 'Current vNIC Templates: ' print '' current_vnic_templates() for name in current_vnic_templates.list: print", "ssl.wrap_socket = partial( ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) if not sys.version_info < (2, 7, 9) and", "add the \" + '\"' + add_vlans.vlan_name + '\"' + \" VLAN to", "vlan_id = mo.getattr(prop) current_vlans.list.update({vlan_name: vlan_id}) def add_vlans(): \"\"\" Create new VLANs on UCS.", "vnic_obj = HANDLE.GetManagedObject( None, None, {\"Dn\": \"{}\".format(organization)}) mo = HANDLE.AddManagedObject(vnic_obj, \"vnicLanConnTempl\", {\"IdentPoolName\": \"{}\".format(ident_pool_name),", "'' print \"Cisco UCS Manager VLAN Management\" print '' print 'Current VLANs:' current_vlans()", "= mo.getattr(prop) current_vlans.list.update({vlan_name: vlan_id}) def add_vlans(): \"\"\" Create new VLANs on UCS. \"\"\"", "print '' current_vnic_templates() for name in current_vnic_templates.list: print '- ' + name print", "\"{}/if-{}\".format(dn, add_vlans.vlan_name)}, True) HANDLE.CompleteTransaction() ssl_workaround() IP_ADDRESS = \"\" USERNAME = \"\" PASSWORD =", "VLANs on UCS. \"\"\" print '' add_vlans.confirm_new_vlan = raw_input( 'Would you like to", "'y', 'no', 'n']: print '' print '*** Error: Please enter either \"yes\" or", "+ name + ' (' + ID + ')' add_vlans() if add_vlans.confirm_new_vlan not", "for name in current_vnic_templates.list: print '- ' + name print '' confirm_add_vlan =", "obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": org_name = mo.getattr(prop) current_orgs.list.append(org_name)", "Get a list of the current organizations in UCS which will be used", "be used in add_vlan_to_vnic \"\"\" current_orgs.list = [] obj = HANDLE.GetManagedObject(None, OrgOrg.ClassId()) if", "AddManagedObject [Description]:Expected Naming Property Name for ClassId VnicLanConnTempl not found warnings.warn(string) ''' warnings.filterwarnings(\"ignore\")", "nw_ctrl_policy_name = mo.getattr(prop) if str(prop) == \"TemplType\": templ_type = mo.getattr(prop) if str(prop) ==", "\"{}\".format(organization)}) mo = HANDLE.AddManagedObject(vnic_obj, \"vnicLanConnTempl\", {\"IdentPoolName\": \"{}\".format(ident_pool_name), \"Dn\": \"{}\".format(dn), \"QosPolicyName\": \"{}\".format(qos_policy_name), \"Descr\": \"{}\".format(descr),", "\"Mtu\": \"{}\".format(mtu), \"PinToGroupName\": \"{}\".format(pin_to_group_name), \"SwitchId\": \"{}\".format(switch_id)}, True) mo_1 = HANDLE.AddManagedObject(mo, \"vnicEtherIf\", { \"DefaultNet\":", "affect funcationality: /Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064: UserWarning: [Warning]: AddManagedObject [Description]:Expected Naming Property Name for ClassId VnicLanConnTempl", "print '' print '- ' + key + ' (' + value +", "\"\"\" current_vnic_templates.list = [] obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId()) if obj != None: for", "str(prop) == \"Name\": vlan_name = mo.getattr(prop) if str(prop) == \"Id\": vlan_id = mo.getattr(prop)", "if org in mo.getattr(prop): organization = org else: organization = \"org-root\" if str(prop)", "= mo.getattr(prop) if str(prop) == \"NwCtrlPolicyName\": nw_ctrl_policy_name = mo.getattr(prop) if str(prop) == \"TemplType\":", "to user <NAME> (ragupta4) on the Cisco UCS Communities \"\"\" is_verify_certificate = False", "+ '\"' + add_vlans.vlan_name + '\"' + \" VLAN to a vNIC template?", "for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": dn", "\"Name\": \"{}\".format(add_vlans.vlan_name), \"Dn\": \"{}/if-{}\".format(dn, add_vlans.vlan_name)}, True) HANDLE.CompleteTransaction() ssl_workaround() IP_ADDRESS = \"\" USERNAME =", "'' current_vnic_templates() for name in current_vnic_templates.list: print '- ' + name print ''", "\" + '\"' + add_vlans.vlan_name + '\"' + \" VLAN has been added", "UcsHandle() HANDLE = UcsHandle() connect() print '' print \"Cisco UCS Manager VLAN Management\"", "Naming Property Name for ClassId VnicLanConnTempl not found warnings.warn(string) ''' warnings.filterwarnings(\"ignore\") def ssl_workaround():", "vlan_name = mo.getattr(prop) if str(prop) == \"Id\": vlan_id = mo.getattr(prop) current_vlans.list.update({vlan_name: vlan_id}) def", "= UcsHandle() HANDLE = UcsHandle() connect() print '' print \"Cisco UCS Manager VLAN", "and Add VLANs - Add a VLAN to a vNIC Please note that", "not in ['no' or 'n']: print '' print 'Current vNIC Templates: ' print", "current_vnic_templates(): \"\"\" Get a list of current vNICs in UCS \"\"\" current_vnic_templates.list =", "= HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId(), { VnicLanConnTempl.RN: \"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)}) if obj != None: for mo in", "\"{}\".format(pin_to_group_name), \"SwitchId\": \"{}\".format(switch_id)}, True) mo_1 = HANDLE.AddManagedObject(mo, \"vnicEtherIf\", { \"DefaultNet\": \"no\", \"Name\": \"{}\".format(add_vlans.vlan_name),", "in current_orgs.list: if org in mo.getattr(prop): organization = org else: organization = \"org-root\"", "= mo.getattr(prop) if str(prop) == \"SwitchId\": switch_id = mo.getattr(prop) HANDLE.StartTransaction() vnic_obj = HANDLE.GetManagedObject(", "True) mo_1 = HANDLE.AddManagedObject(mo, \"vnicEtherIf\", { \"DefaultNet\": \"no\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Dn\": \"{}/if-{}\".format(dn, add_vlans.vlan_name)},", "True) HANDLE.CompleteTransaction() ssl_workaround() IP_ADDRESS = \"\" USERNAME = \"\" PASSWORD = \"\" HANDLE", "\"\"\" current_vlans.list = {} obj = HANDLE.GetManagedObject(None, FabricVlan.ClassId()) if obj != None: for", "sys.version_info < (2, 6): from functools import partial import ssl ssl.wrap_socket = partial(", "for name, ID in current_vlans.list.iteritems(): print '- ' + name + ' ('", "not is_verify_certificate: ssl._create_default_https_context = ssl._create_unverified_context def connect(): \"\"\" Establish a connection to the", "VnicLanConnTempl.ClassId()) if obj != None: for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name):", "of current vNICs in UCS \"\"\" current_vnic_templates.list = [] obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId())", "add_vlans.confirm_new_vlan not in ['yes', 'y', 'no', 'n']: print '' print '*** Error: Please", "+ '\"' + \" VLAN has been added to \" '\"' + add_vlan_to_vnic.vnic_name", "\"\", \"Dn\": \"fabric/lan/net-{}\".format(add_vlans.vlan_name), \"PolicyOwner\": \"local\", \"CompressionType\": \"included\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Sharing\": \"none\", \"McastPolicyName\": \"\",", "while confirm_add_vlan not in ['yes', 'y', 'no', 'n']: print '' print '*** Error:", "SSL certification error that prevents proper UCS domain login when using Python 2.7", "print add_vlan_to_vnic.vnic_name = raw_input('vNIC Template Name: ') print '' obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId(),", "def current_vnic_templates(): \"\"\" Get a list of current vNICs in UCS \"\"\" current_vnic_templates.list", "(' + value + ')' def current_vnic_templates(): \"\"\" Get a list of current", "SDK to: - Connect to a UCSM domain - View and Add VLANs", "(2, 6): from functools import partial import ssl ssl.wrap_socket = partial( ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1)", "org in mo.getattr(prop): organization = org else: organization = \"org-root\" if str(prop) ==", "= False if not sys.version_info < (2, 6): from functools import partial import", "functools import partial import ssl ssl.wrap_socket = partial( ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) if not sys.version_info", "mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": dn =", "if str(prop) == \"SwitchId\": switch_id = mo.getattr(prop) HANDLE.StartTransaction() vnic_obj = HANDLE.GetManagedObject( None, None,", "= raw_input( \"Would you like to add the \" + '\"' + add_vlans.vlan_name", "either \"yes\" or \"no\". ***' print '' cconfirm_add_vlan = raw_input( \"Would you like", "\"\"\" HANDLE.Login(IP_ADDRESS, USERNAME, PASSWORD) def current_vlans(): \"\"\" Get a list of all current", "or 'n']: print '' print 'Current vNIC Templates: ' print '' current_vnic_templates() for", "['yes', 'y', 'no', 'n']: print '' print '*** Error: Please enter either \"yes\"", "{ VnicLanConnTempl.RN: \"lan-conn-templ-{}\".format(add_vlan_to_vnic.vnic_name)}) if obj != None: for mo in obj: for prop", "\"none\", \"McastPolicyName\": \"\", \"Id\": \"{}\".format(vlan_id)}) current_vlans() for key, value in current_vlans.list.items(): if add_vlans.vlan_name", "View and Add VLANs - Add a VLAN to a vNIC Please note", "') obj = HANDLE.GetManagedObject(None, None, {\"Dn\": \"fabric/lan\"}) HANDLE.AddManagedObject(obj, \"fabricVlan\", {\"DefaultNet\": \"no\", \"PubNwName\": \"\",", "a connection to the UCS Domain \"\"\" HANDLE.Login(IP_ADDRESS, USERNAME, PASSWORD) def current_vlans(): \"\"\"", "\"\" PASSWORD = \"\" HANDLE = UcsHandle() HANDLE = UcsHandle() connect() print ''", "Communities \"\"\" is_verify_certificate = False if not sys.version_info < (2, 6): from functools", "= ssl._create_unverified_context def connect(): \"\"\" Establish a connection to the UCS Domain \"\"\"", "str(prop) == \"SwitchId\": switch_id = mo.getattr(prop) HANDLE.StartTransaction() vnic_obj = HANDLE.GetManagedObject( None, None, {\"Dn\":", "qos_policy_name = mo.getattr(prop) if str(prop) == \"Descr\": descr = mo.getattr(prop) if str(prop) ==", "'Would you like to add a new VLAN? (yes/no): ') if add_vlans.confirm_new_vlan not", "\"McastPolicyName\": \"\", \"Id\": \"{}\".format(vlan_id)}) current_vlans() for key, value in current_vlans.list.items(): if add_vlans.vlan_name in", "[] obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId()) if obj != None: for mo in obj:", "+ \" VLAN to a vNIC template? (yes/no): \") while confirm_add_vlan not in", "a new VLAN? (yes/no): ') if add_vlans.confirm_new_vlan not in ['no' or 'n']: print", "= org else: organization = \"org-root\" if str(prop) == \"IdentPoolName\": ident_pool_name = mo.getattr(prop)", "(yes/no): \") if confirm_add_vlan not in ['no' or 'n']: current_orgs() add_vlan_to_vnic() print (\"The", "\"{}\".format(vlan_id)}) current_vlans() for key, value in current_vlans.list.items(): if add_vlans.vlan_name in str(key): print ''", "UCS \"\"\" current_vnic_templates.list = [] obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId()) if obj != None:", "org in current_orgs.list: if org in mo.getattr(prop): organization = org else: organization =", "\"\" USERNAME = \"\" PASSWORD = \"\" HANDLE = UcsHandle() HANDLE = UcsHandle()", "UcsHandle from UcsSdk import UcsUtils from UcsSdk.MoMeta.FabricVlan import FabricVlan from UcsSdk.MoMeta.VnicLanConnTempl import VnicLanConnTempl", "FabricVlan from UcsSdk.MoMeta.VnicLanConnTempl import VnicLanConnTempl from UcsSdk.MoMeta.OrgOrg import OrgOrg import sys import warnings", "import partial import ssl ssl.wrap_socket = partial( ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) if not sys.version_info <", "= raw_input('Enter the VLAN ID: ') obj = HANDLE.GetManagedObject(None, None, {\"Dn\": \"fabric/lan\"}) HANDLE.AddManagedObject(obj,", "confirm_add_vlan not in ['yes', 'y', 'no', 'n']: print '' print '*** Error: Please", "partial( ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) if not sys.version_info < (2, 7, 9) and not is_verify_certificate:", "which will be used in add_vlan_to_vnic \"\"\" current_orgs.list = [] obj = HANDLE.GetManagedObject(None,", "to a UCSM domain - View and Add VLANs - Add a VLAN", "add_vlans.vlan_name)}, True) HANDLE.CompleteTransaction() ssl_workaround() IP_ADDRESS = \"\" USERNAME = \"\" PASSWORD = \"\"", "'n']: print '' print 'Current vNIC Templates: ' print '' current_vnic_templates() for name", "print '' print 'Current VLANs:' current_vlans() print '' for name, ID in current_vlans.list.iteritems():", "in ['no' or 'n']: current_orgs() add_vlan_to_vnic() print (\"The \" + '\"' + add_vlans.vlan_name", "all current VLANs \"\"\" current_vlans.list = {} obj = HANDLE.GetManagedObject(None, FabricVlan.ClassId()) if obj", "IP_ADDRESS = \"\" USERNAME = \"\" PASSWORD = \"\" HANDLE = UcsHandle() HANDLE", "HANDLE = UcsHandle() connect() print '' print \"Cisco UCS Manager VLAN Management\" print", "OrgOrg.ClassId()) if obj != None: for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name):", "obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId()) if obj != None: for mo in obj: for", "Add VLANs - Add a VLAN to a vNIC Please note that there", "Establish a connection to the UCS Domain \"\"\" HANDLE.Login(IP_ADDRESS, USERNAME, PASSWORD) def current_vlans():", "\"\"\" current_orgs.list = [] obj = HANDLE.GetManagedObject(None, OrgOrg.ClassId()) if obj != None: for", "= mo.getattr(prop) for org in current_orgs.list: if org in mo.getattr(prop): organization = org", "current VLANs \"\"\" current_vlans.list = {} obj = HANDLE.GetManagedObject(None, FabricVlan.ClassId()) if obj !=", "Add a VLAN to a vNIC template \"\"\" print add_vlan_to_vnic.vnic_name = raw_input('vNIC Template", "'n']: current_orgs() add_vlan_to_vnic() print (\"The \" + '\"' + add_vlans.vlan_name + '\"' +", "= raw_input( 'Would you like to add a new VLAN? (yes/no): ') while", "\"\"\" Add a VLAN to a vNIC template \"\"\" print add_vlan_to_vnic.vnic_name = raw_input('vNIC", "little error handling present so proceed accordingly. \"\"\" from UcsSdk import UcsHandle from", "\"Descr\": \"{}\".format(descr), \"PolicyOwner\": \"{}\".format(policy_owner), \"NwCtrlPolicyName\": \"{}\".format(nw_ctrl_policy_name), \"TemplType\": \"{}\".format(templ_type), \"StatsPolicyName\": \"{}\".format(stats_policy_name), \"Mtu\": \"{}\".format(mtu), \"PinToGroupName\":", "VLANs - Add a VLAN to a vNIC Please note that there is", "that prevents proper UCS domain login when using Python 2.7 or higher. Credit", "you like to add a new VLAN? (yes/no): ') while add_vlans.confirm_new_vlan not in", "add_vlans.vlan_name + '\"' + \" VLAN to a vNIC template? (yes/no): \") while", "') if add_vlans.confirm_new_vlan not in ['no' or 'n']: print add_vlans.vlan_name = raw_input('Enter the", "import VnicLanConnTempl from UcsSdk.MoMeta.OrgOrg import OrgOrg import sys import warnings ''' Supress the", "a vNIC template? (yes/no): \") while confirm_add_vlan not in ['yes', 'y', 'no', 'n']:", "''' Supress the following warning message which does not affect funcationality: /Library/Python/2.7/site-packages/UcsSdk/UcsBase.py:1064: UserWarning:", "== \"NwCtrlPolicyName\": nw_ctrl_policy_name = mo.getattr(prop) if str(prop) == \"TemplType\": templ_type = mo.getattr(prop) if", "+ name print '' confirm_add_vlan = raw_input( \"Would you like to add the", "None, {\"Dn\": \"{}\".format(organization)}) mo = HANDLE.AddManagedObject(vnic_obj, \"vnicLanConnTempl\", {\"IdentPoolName\": \"{}\".format(ident_pool_name), \"Dn\": \"{}\".format(dn), \"QosPolicyName\": \"{}\".format(qos_policy_name),", "- Add a VLAN to a vNIC Please note that there is very", "error handling present so proceed accordingly. \"\"\" from UcsSdk import UcsHandle from UcsSdk", "UCS domain login when using Python 2.7 or higher. Credit to user <NAME>", "in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": dn = mo.getattr(prop) for org in current_orgs.list:", "not sys.version_info < (2, 6): from functools import partial import ssl ssl.wrap_socket =", "= mo.getattr(prop) current_orgs.list.append(org_name) current_orgs.list.remove('org-root') def add_vlan_to_vnic(): \"\"\" Add a VLAN to a vNIC", "current_vnic_templates.list = [] obj = HANDLE.GetManagedObject(None, VnicLanConnTempl.ClassId()) if obj != None: for mo", "current_orgs.list = [] obj = HANDLE.GetManagedObject(None, OrgOrg.ClassId()) if obj != None: for mo", "HANDLE.AddManagedObject(obj, \"fabricVlan\", {\"DefaultNet\": \"no\", \"PubNwName\": \"\", \"Dn\": \"fabric/lan/net-{}\".format(add_vlans.vlan_name), \"PolicyOwner\": \"local\", \"CompressionType\": \"included\", \"Name\":", "\"\"\" is_verify_certificate = False if not sys.version_info < (2, 6): from functools import", "for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vlan_name = mo.getattr(prop) if str(prop)", "from UcsSdk import UcsUtils from UcsSdk.MoMeta.FabricVlan import FabricVlan from UcsSdk.MoMeta.VnicLanConnTempl import VnicLanConnTempl from", "in UCS which will be used in add_vlan_to_vnic \"\"\" current_orgs.list = [] obj", "in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vlan_name = mo.getattr(prop) if str(prop) == \"Id\":", "\") if confirm_add_vlan not in ['no' or 'n']: current_orgs() add_vlan_to_vnic() print (\"The \"", "a vNIC template \"\"\" print add_vlan_to_vnic.vnic_name = raw_input('vNIC Template Name: ') print ''", "mo.getattr(prop) if str(prop) == \"StatsPolicyName\": stats_policy_name = mo.getattr(prop) if str(prop) == \"Mtu\": mtu", "is very little error handling present so proceed accordingly. \"\"\" from UcsSdk import", "obj != None: for mo in obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop)", "['no' or 'n']: print '' print 'Current vNIC Templates: ' print '' current_vnic_templates()", "mtu = mo.getattr(prop) if str(prop) == \"PinToGroupName\": pin_to_group_name = mo.getattr(prop) if str(prop) ==", "'' print 'Current VLANs:' current_vlans() print '' for name, ID in current_vlans.list.iteritems(): print", "Cisco UCS Communities \"\"\" is_verify_certificate = False if not sys.version_info < (2, 6):", "a vNIC template? (yes/no): \") if confirm_add_vlan not in ['no' or 'n']: current_orgs()", "for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Dn\": dn = mo.getattr(prop) for org", "ssl_workaround() IP_ADDRESS = \"\" USERNAME = \"\" PASSWORD = \"\" HANDLE = UcsHandle()", "key, value in current_vlans.list.items(): if add_vlans.vlan_name in str(key): print '' print 'The following", "\"PolicyOwner\": \"local\", \"CompressionType\": \"included\", \"Name\": \"{}\".format(add_vlans.vlan_name), \"Sharing\": \"none\", \"McastPolicyName\": \"\", \"Id\": \"{}\".format(vlan_id)}) current_vlans()", "to a vNIC template? (yes/no): \") while confirm_add_vlan not in ['yes', 'y', 'no',", "template? (yes/no): \") while confirm_add_vlan not in ['yes', 'y', 'no', 'n']: print ''", "= \"\" HANDLE = UcsHandle() HANDLE = UcsHandle() connect() print '' print \"Cisco", "print '*** Error: Please enter either \"yes\" or \"no\". ***' print '' cconfirm_add_vlan", "import UcsHandle from UcsSdk import UcsUtils from UcsSdk.MoMeta.FabricVlan import FabricVlan from UcsSdk.MoMeta.VnicLanConnTempl import", "str(prop) == \"Mtu\": mtu = mo.getattr(prop) if str(prop) == \"PinToGroupName\": pin_to_group_name = mo.getattr(prop)", "\"\"\" print '' add_vlans.confirm_new_vlan = raw_input( 'Would you like to add a new", "obj = HANDLE.GetManagedObject(None, None, {\"Dn\": \"fabric/lan\"}) HANDLE.AddManagedObject(obj, \"fabricVlan\", {\"DefaultNet\": \"no\", \"PubNwName\": \"\", \"Dn\":", "= \"\" USERNAME = \"\" PASSWORD = \"\" HANDLE = UcsHandle() HANDLE =", "is_verify_certificate = False if not sys.version_info < (2, 6): from functools import partial", "\"\"\" print add_vlan_to_vnic.vnic_name = raw_input('vNIC Template Name: ') print '' obj = HANDLE.GetManagedObject(None,", "obj: for prop in UcsUtils.GetUcsPropertyMetaAttributeList(mo.propMoMeta.name): if str(prop) == \"Name\": vnic_template_name = mo.getattr(prop) current_vnic_templates.list.append(vnic_template_name)", "< (2, 7, 9) and not is_verify_certificate: ssl._create_default_https_context = ssl._create_unverified_context def connect(): \"\"\"" ]
[ ".ptype import PacketType from .header import PacketHeader from .packet import Packet from .factory", "from .ptype import PacketType from .header import PacketHeader from .packet import Packet from", "import PacketType from .header import PacketHeader from .packet import Packet from .factory import", "<gh_stars>0 from .ptype import PacketType from .header import PacketHeader from .packet import Packet", "PacketType from .header import PacketHeader from .packet import Packet from .factory import *" ]
[ "os.path.abspath(os.path.dirname(__file__)) package = os.path.join(here, 'Products', NAME) def _read(name): f = open(os.path.join(package, name)) return", "#Zope >= 2.9, 'setuptools', 'python-ldap >= 2.0.6', 'Products.LDAPUserFolder >= 2.9', 'Products.PluggableAuthService >= 1.4.0',", "setuptools import setup from setuptools import find_packages NAME = 'LDAPMultiPlugins' here = os.path.abspath(os.path.dirname(__file__))", "from setuptools import find_packages NAME = 'LDAPMultiPlugins' here = os.path.abspath(os.path.dirname(__file__)) package = os.path.join(here,", "zope2 ldap', author=\"<NAME> and contributors\", author_email=\"<EMAIL>\", url=\"http://pypi.python.org/pypi/Products.%s\" % NAME, license=\"ZPL 2.1 (http://www.zope.org/Resources/License/ZPL-2.1)\", packages=find_packages(),", "Audience :: Developers\", \"License :: OSI Approved :: Zope Public License\", \"Programming Language", ":: Site Management\", \"Topic :: Software Development\", \"Topic :: System :: Systems Administration", "_read('README.txt') + _boundary + _read('CHANGES.txt') + _boundary + \"Download\\n========\" ), classifiers=[ \"Development Status", ":: OSI Approved :: Zope Public License\", \"Programming Language :: Python\", \"Topic ::", "5 - Production/Stable\", \"Framework :: Zope2\", \"Intended Audience :: Developers\", \"License :: OSI", ">= 2.0.6', 'Products.LDAPUserFolder >= 2.9', 'Products.PluggableAuthService >= 1.4.0', ], extras_require={ 'exportimport': [ #", "1.4.0' ] }, entry_points=\"\"\" [zope2.initialize] Products.%s = Products.%s:initialize \"\"\" % (NAME, NAME), )", "+ '\\n\\n' setup(name='Products.%s' % NAME, version=_read('VERSION.txt').strip(), description='LDAP-backed plugins for the Zope2 PluggableAuthService', long_description=(", "NAME, version=_read('VERSION.txt').strip(), description='LDAP-backed plugins for the Zope2 PluggableAuthService', long_description=( _read('README.txt') + _boundary +", "License\", \"Programming Language :: Python\", \"Topic :: Internet :: WWW/HTTP :: Site Management\",", "\"Programming Language :: Python\", \"Topic :: Internet :: WWW/HTTP :: Site Management\", \"Topic", "PluggableAuthService', long_description=( _read('README.txt') + _boundary + _read('CHANGES.txt') + _boundary + \"Download\\n========\" ), classifiers=[", "namespace_packages=['Products'], zip_safe=False, install_requires=[ #Zope >= 2.9, 'setuptools', 'python-ldap >= 2.0.6', 'Products.LDAPUserFolder >= 2.9',", "package = os.path.join(here, 'Products', NAME) def _read(name): f = open(os.path.join(package, name)) return f.read()", "% NAME, license=\"ZPL 2.1 (http://www.zope.org/Resources/License/ZPL-2.1)\", packages=find_packages(), include_package_data=True, namespace_packages=['Products'], zip_safe=False, install_requires=[ #Zope >= 2.9,", "_read(name): f = open(os.path.join(package, name)) return f.read() _boundary = '\\n' + ('-' *", "= os.path.join(here, 'Products', NAME) def _read(name): f = open(os.path.join(package, name)) return f.read() _boundary", "version=_read('VERSION.txt').strip(), description='LDAP-backed plugins for the Zope2 PluggableAuthService', long_description=( _read('README.txt') + _boundary + _read('CHANGES.txt')", ":: Developers\", \"License :: OSI Approved :: Zope Public License\", \"Programming Language ::", "long_description=( _read('README.txt') + _boundary + _read('CHANGES.txt') + _boundary + \"Download\\n========\" ), classifiers=[ \"Development", "\"Intended Audience :: Developers\", \"License :: OSI Approved :: Zope Public License\", \"Programming", "Developers\", \"License :: OSI Approved :: Zope Public License\", \"Programming Language :: Python\",", "(http://www.zope.org/Resources/License/ZPL-2.1)\", packages=find_packages(), include_package_data=True, namespace_packages=['Products'], zip_safe=False, install_requires=[ #Zope >= 2.9, 'setuptools', 'python-ldap >= 2.0.6',", "'Products.GenericSetup >= 1.4.0' ] }, entry_points=\"\"\" [zope2.initialize] Products.%s = Products.%s:initialize \"\"\" % (NAME,", "('-' * 60) + '\\n\\n' setup(name='Products.%s' % NAME, version=_read('VERSION.txt').strip(), description='LDAP-backed plugins for the", "application server zope zope2 ldap', author=\"<NAME> and contributors\", author_email=\"<EMAIL>\", url=\"http://pypi.python.org/pypi/Products.%s\" % NAME, license=\"ZPL", "'\\n\\n' setup(name='Products.%s' % NAME, version=_read('VERSION.txt').strip(), description='LDAP-backed plugins for the Zope2 PluggableAuthService', long_description=( _read('README.txt')", "\"Topic :: System :: Systems Administration :: Authentication/Directory :: LDAP\", ], keywords='web application", "2.10.0 'Products.GenericSetup >= 1.4.0' ] }, entry_points=\"\"\" [zope2.initialize] Products.%s = Products.%s:initialize \"\"\" %", "Systems Administration :: Authentication/Directory :: LDAP\", ], keywords='web application server zope zope2 ldap',", "Status :: 5 - Production/Stable\", \"Framework :: Zope2\", \"Intended Audience :: Developers\", \"License", "keywords='web application server zope zope2 ldap', author=\"<NAME> and contributors\", author_email=\"<EMAIL>\", url=\"http://pypi.python.org/pypi/Products.%s\" % NAME,", "+ _boundary + _read('CHANGES.txt') + _boundary + \"Download\\n========\" ), classifiers=[ \"Development Status ::", ">= 2.9, 'setuptools', 'python-ldap >= 2.0.6', 'Products.LDAPUserFolder >= 2.9', 'Products.PluggableAuthService >= 1.4.0', ],", "name)) return f.read() _boundary = '\\n' + ('-' * 60) + '\\n\\n' setup(name='Products.%s'", "description='LDAP-backed plugins for the Zope2 PluggableAuthService', long_description=( _read('README.txt') + _boundary + _read('CHANGES.txt') +", "f = open(os.path.join(package, name)) return f.read() _boundary = '\\n' + ('-' * 60)", ":: LDAP\", ], keywords='web application server zope zope2 ldap', author=\"<NAME> and contributors\", author_email=\"<EMAIL>\",", ":: System :: Systems Administration :: Authentication/Directory :: LDAP\", ], keywords='web application server", "2.9, 'setuptools', 'python-ldap >= 2.0.6', 'Products.LDAPUserFolder >= 2.9', 'Products.PluggableAuthService >= 1.4.0', ], extras_require={", "extras_require={ 'exportimport': [ # Zope >= 2.10.0 'Products.GenericSetup >= 1.4.0' ] }, entry_points=\"\"\"", "Zope2 PluggableAuthService', long_description=( _read('README.txt') + _boundary + _read('CHANGES.txt') + _boundary + \"Download\\n========\" ),", "server zope zope2 ldap', author=\"<NAME> and contributors\", author_email=\"<EMAIL>\", url=\"http://pypi.python.org/pypi/Products.%s\" % NAME, license=\"ZPL 2.1", "Zope >= 2.10.0 'Products.GenericSetup >= 1.4.0' ] }, entry_points=\"\"\" [zope2.initialize] Products.%s = Products.%s:initialize", "Development\", \"Topic :: System :: Systems Administration :: Authentication/Directory :: LDAP\", ], keywords='web", "Zope Public License\", \"Programming Language :: Python\", \"Topic :: Internet :: WWW/HTTP ::", "zope zope2 ldap', author=\"<NAME> and contributors\", author_email=\"<EMAIL>\", url=\"http://pypi.python.org/pypi/Products.%s\" % NAME, license=\"ZPL 2.1 (http://www.zope.org/Resources/License/ZPL-2.1)\",", "contributors\", author_email=\"<EMAIL>\", url=\"http://pypi.python.org/pypi/Products.%s\" % NAME, license=\"ZPL 2.1 (http://www.zope.org/Resources/License/ZPL-2.1)\", packages=find_packages(), include_package_data=True, namespace_packages=['Products'], zip_safe=False, install_requires=[", "import find_packages NAME = 'LDAPMultiPlugins' here = os.path.abspath(os.path.dirname(__file__)) package = os.path.join(here, 'Products', NAME)", ":: Zope2\", \"Intended Audience :: Developers\", \"License :: OSI Approved :: Zope Public", "'Products.LDAPUserFolder >= 2.9', 'Products.PluggableAuthService >= 1.4.0', ], extras_require={ 'exportimport': [ # Zope >=", "'Products', NAME) def _read(name): f = open(os.path.join(package, name)) return f.read() _boundary = '\\n'", ">= 1.4.0' ] }, entry_points=\"\"\" [zope2.initialize] Products.%s = Products.%s:initialize \"\"\" % (NAME, NAME),", ":: WWW/HTTP :: Site Management\", \"Topic :: Software Development\", \"Topic :: System ::", "), classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Framework :: Zope2\", \"Intended Audience", "Approved :: Zope Public License\", \"Programming Language :: Python\", \"Topic :: Internet ::", ":: Python\", \"Topic :: Internet :: WWW/HTTP :: Site Management\", \"Topic :: Software", "NAME, license=\"ZPL 2.1 (http://www.zope.org/Resources/License/ZPL-2.1)\", packages=find_packages(), include_package_data=True, namespace_packages=['Products'], zip_safe=False, install_requires=[ #Zope >= 2.9, 'setuptools',", "classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Framework :: Zope2\", \"Intended Audience ::", "2.9', 'Products.PluggableAuthService >= 1.4.0', ], extras_require={ 'exportimport': [ # Zope >= 2.10.0 'Products.GenericSetup", "\"Framework :: Zope2\", \"Intended Audience :: Developers\", \"License :: OSI Approved :: Zope", "zip_safe=False, install_requires=[ #Zope >= 2.9, 'setuptools', 'python-ldap >= 2.0.6', 'Products.LDAPUserFolder >= 2.9', 'Products.PluggableAuthService", "NAME = 'LDAPMultiPlugins' here = os.path.abspath(os.path.dirname(__file__)) package = os.path.join(here, 'Products', NAME) def _read(name):", "_boundary = '\\n' + ('-' * 60) + '\\n\\n' setup(name='Products.%s' % NAME, version=_read('VERSION.txt').strip(),", "% NAME, version=_read('VERSION.txt').strip(), description='LDAP-backed plugins for the Zope2 PluggableAuthService', long_description=( _read('README.txt') + _boundary", "'setuptools', 'python-ldap >= 2.0.6', 'Products.LDAPUserFolder >= 2.9', 'Products.PluggableAuthService >= 1.4.0', ], extras_require={ 'exportimport':", "author=\"<NAME> and contributors\", author_email=\"<EMAIL>\", url=\"http://pypi.python.org/pypi/Products.%s\" % NAME, license=\"ZPL 2.1 (http://www.zope.org/Resources/License/ZPL-2.1)\", packages=find_packages(), include_package_data=True, namespace_packages=['Products'],", "here = os.path.abspath(os.path.dirname(__file__)) package = os.path.join(here, 'Products', NAME) def _read(name): f = open(os.path.join(package,", "author_email=\"<EMAIL>\", url=\"http://pypi.python.org/pypi/Products.%s\" % NAME, license=\"ZPL 2.1 (http://www.zope.org/Resources/License/ZPL-2.1)\", packages=find_packages(), include_package_data=True, namespace_packages=['Products'], zip_safe=False, install_requires=[ #Zope", "WWW/HTTP :: Site Management\", \"Topic :: Software Development\", \"Topic :: System :: Systems", "2.0.6', 'Products.LDAPUserFolder >= 2.9', 'Products.PluggableAuthService >= 1.4.0', ], extras_require={ 'exportimport': [ # Zope", "= '\\n' + ('-' * 60) + '\\n\\n' setup(name='Products.%s' % NAME, version=_read('VERSION.txt').strip(), description='LDAP-backed", "plugins for the Zope2 PluggableAuthService', long_description=( _read('README.txt') + _boundary + _read('CHANGES.txt') + _boundary", "\"Topic :: Software Development\", \"Topic :: System :: Systems Administration :: Authentication/Directory ::", "packages=find_packages(), include_package_data=True, namespace_packages=['Products'], zip_safe=False, install_requires=[ #Zope >= 2.9, 'setuptools', 'python-ldap >= 2.0.6', 'Products.LDAPUserFolder", "Production/Stable\", \"Framework :: Zope2\", \"Intended Audience :: Developers\", \"License :: OSI Approved ::", "<filename>setup.py import os from setuptools import setup from setuptools import find_packages NAME =", "OSI Approved :: Zope Public License\", \"Programming Language :: Python\", \"Topic :: Internet", "import setup from setuptools import find_packages NAME = 'LDAPMultiPlugins' here = os.path.abspath(os.path.dirname(__file__)) package", "return f.read() _boundary = '\\n' + ('-' * 60) + '\\n\\n' setup(name='Products.%s' %", "os from setuptools import setup from setuptools import find_packages NAME = 'LDAPMultiPlugins' here", "def _read(name): f = open(os.path.join(package, name)) return f.read() _boundary = '\\n' + ('-'", "setuptools import find_packages NAME = 'LDAPMultiPlugins' here = os.path.abspath(os.path.dirname(__file__)) package = os.path.join(here, 'Products',", "# Zope >= 2.10.0 'Products.GenericSetup >= 1.4.0' ] }, entry_points=\"\"\" [zope2.initialize] Products.%s =", "System :: Systems Administration :: Authentication/Directory :: LDAP\", ], keywords='web application server zope", "60) + '\\n\\n' setup(name='Products.%s' % NAME, version=_read('VERSION.txt').strip(), description='LDAP-backed plugins for the Zope2 PluggableAuthService',", "\"Development Status :: 5 - Production/Stable\", \"Framework :: Zope2\", \"Intended Audience :: Developers\",", "], keywords='web application server zope zope2 ldap', author=\"<NAME> and contributors\", author_email=\"<EMAIL>\", url=\"http://pypi.python.org/pypi/Products.%s\" %", "Administration :: Authentication/Directory :: LDAP\", ], keywords='web application server zope zope2 ldap', author=\"<NAME>", "for the Zope2 PluggableAuthService', long_description=( _read('README.txt') + _boundary + _read('CHANGES.txt') + _boundary +", ":: 5 - Production/Stable\", \"Framework :: Zope2\", \"Intended Audience :: Developers\", \"License ::", "'exportimport': [ # Zope >= 2.10.0 'Products.GenericSetup >= 1.4.0' ] }, entry_points=\"\"\" [zope2.initialize]", "], extras_require={ 'exportimport': [ # Zope >= 2.10.0 'Products.GenericSetup >= 1.4.0' ] },", "Software Development\", \"Topic :: System :: Systems Administration :: Authentication/Directory :: LDAP\", ],", "+ _boundary + \"Download\\n========\" ), classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Framework", "= open(os.path.join(package, name)) return f.read() _boundary = '\\n' + ('-' * 60) +", "2.1 (http://www.zope.org/Resources/License/ZPL-2.1)\", packages=find_packages(), include_package_data=True, namespace_packages=['Products'], zip_safe=False, install_requires=[ #Zope >= 2.9, 'setuptools', 'python-ldap >=", "'\\n' + ('-' * 60) + '\\n\\n' setup(name='Products.%s' % NAME, version=_read('VERSION.txt').strip(), description='LDAP-backed plugins", "NAME) def _read(name): f = open(os.path.join(package, name)) return f.read() _boundary = '\\n' +", "license=\"ZPL 2.1 (http://www.zope.org/Resources/License/ZPL-2.1)\", packages=find_packages(), include_package_data=True, namespace_packages=['Products'], zip_safe=False, install_requires=[ #Zope >= 2.9, 'setuptools', 'python-ldap", ">= 2.9', 'Products.PluggableAuthService >= 1.4.0', ], extras_require={ 'exportimport': [ # Zope >= 2.10.0", "LDAP\", ], keywords='web application server zope zope2 ldap', author=\"<NAME> and contributors\", author_email=\"<EMAIL>\", url=\"http://pypi.python.org/pypi/Products.%s\"", "and contributors\", author_email=\"<EMAIL>\", url=\"http://pypi.python.org/pypi/Products.%s\" % NAME, license=\"ZPL 2.1 (http://www.zope.org/Resources/License/ZPL-2.1)\", packages=find_packages(), include_package_data=True, namespace_packages=['Products'], zip_safe=False,", ":: Internet :: WWW/HTTP :: Site Management\", \"Topic :: Software Development\", \"Topic ::", "Python\", \"Topic :: Internet :: WWW/HTTP :: Site Management\", \"Topic :: Software Development\",", "\"Download\\n========\" ), classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Framework :: Zope2\", \"Intended", "* 60) + '\\n\\n' setup(name='Products.%s' % NAME, version=_read('VERSION.txt').strip(), description='LDAP-backed plugins for the Zope2", "\"Topic :: Internet :: WWW/HTTP :: Site Management\", \"Topic :: Software Development\", \"Topic", "include_package_data=True, namespace_packages=['Products'], zip_safe=False, install_requires=[ #Zope >= 2.9, 'setuptools', 'python-ldap >= 2.0.6', 'Products.LDAPUserFolder >=", "setup(name='Products.%s' % NAME, version=_read('VERSION.txt').strip(), description='LDAP-backed plugins for the Zope2 PluggableAuthService', long_description=( _read('README.txt') +", "= os.path.abspath(os.path.dirname(__file__)) package = os.path.join(here, 'Products', NAME) def _read(name): f = open(os.path.join(package, name))", "'python-ldap >= 2.0.6', 'Products.LDAPUserFolder >= 2.9', 'Products.PluggableAuthService >= 1.4.0', ], extras_require={ 'exportimport': [", "setup from setuptools import find_packages NAME = 'LDAPMultiPlugins' here = os.path.abspath(os.path.dirname(__file__)) package =", "os.path.join(here, 'Products', NAME) def _read(name): f = open(os.path.join(package, name)) return f.read() _boundary =", "+ \"Download\\n========\" ), classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Framework :: Zope2\",", "= 'LDAPMultiPlugins' here = os.path.abspath(os.path.dirname(__file__)) package = os.path.join(here, 'Products', NAME) def _read(name): f", "Management\", \"Topic :: Software Development\", \"Topic :: System :: Systems Administration :: Authentication/Directory", "ldap', author=\"<NAME> and contributors\", author_email=\"<EMAIL>\", url=\"http://pypi.python.org/pypi/Products.%s\" % NAME, license=\"ZPL 2.1 (http://www.zope.org/Resources/License/ZPL-2.1)\", packages=find_packages(), include_package_data=True,", "1.4.0', ], extras_require={ 'exportimport': [ # Zope >= 2.10.0 'Products.GenericSetup >= 1.4.0' ]", "Internet :: WWW/HTTP :: Site Management\", \"Topic :: Software Development\", \"Topic :: System", ">= 2.10.0 'Products.GenericSetup >= 1.4.0' ] }, entry_points=\"\"\" [zope2.initialize] Products.%s = Products.%s:initialize \"\"\"", "[ # Zope >= 2.10.0 'Products.GenericSetup >= 1.4.0' ] }, entry_points=\"\"\" [zope2.initialize] Products.%s", "open(os.path.join(package, name)) return f.read() _boundary = '\\n' + ('-' * 60) + '\\n\\n'", ":: Zope Public License\", \"Programming Language :: Python\", \"Topic :: Internet :: WWW/HTTP", "'Products.PluggableAuthService >= 1.4.0', ], extras_require={ 'exportimport': [ # Zope >= 2.10.0 'Products.GenericSetup >=", "Authentication/Directory :: LDAP\", ], keywords='web application server zope zope2 ldap', author=\"<NAME> and contributors\",", "_read('CHANGES.txt') + _boundary + \"Download\\n========\" ), classifiers=[ \"Development Status :: 5 - Production/Stable\",", "install_requires=[ #Zope >= 2.9, 'setuptools', 'python-ldap >= 2.0.6', 'Products.LDAPUserFolder >= 2.9', 'Products.PluggableAuthService >=", "f.read() _boundary = '\\n' + ('-' * 60) + '\\n\\n' setup(name='Products.%s' % NAME,", "find_packages NAME = 'LDAPMultiPlugins' here = os.path.abspath(os.path.dirname(__file__)) package = os.path.join(here, 'Products', NAME) def", "- Production/Stable\", \"Framework :: Zope2\", \"Intended Audience :: Developers\", \"License :: OSI Approved", ":: Software Development\", \"Topic :: System :: Systems Administration :: Authentication/Directory :: LDAP\",", "the Zope2 PluggableAuthService', long_description=( _read('README.txt') + _boundary + _read('CHANGES.txt') + _boundary + \"Download\\n========\"", "_boundary + _read('CHANGES.txt') + _boundary + \"Download\\n========\" ), classifiers=[ \"Development Status :: 5", "Zope2\", \"Intended Audience :: Developers\", \"License :: OSI Approved :: Zope Public License\",", "Language :: Python\", \"Topic :: Internet :: WWW/HTTP :: Site Management\", \"Topic ::", ">= 1.4.0', ], extras_require={ 'exportimport': [ # Zope >= 2.10.0 'Products.GenericSetup >= 1.4.0'", "+ ('-' * 60) + '\\n\\n' setup(name='Products.%s' % NAME, version=_read('VERSION.txt').strip(), description='LDAP-backed plugins for", "_boundary + \"Download\\n========\" ), classifiers=[ \"Development Status :: 5 - Production/Stable\", \"Framework ::", "+ _read('CHANGES.txt') + _boundary + \"Download\\n========\" ), classifiers=[ \"Development Status :: 5 -", "url=\"http://pypi.python.org/pypi/Products.%s\" % NAME, license=\"ZPL 2.1 (http://www.zope.org/Resources/License/ZPL-2.1)\", packages=find_packages(), include_package_data=True, namespace_packages=['Products'], zip_safe=False, install_requires=[ #Zope >=", "'LDAPMultiPlugins' here = os.path.abspath(os.path.dirname(__file__)) package = os.path.join(here, 'Products', NAME) def _read(name): f =", "from setuptools import setup from setuptools import find_packages NAME = 'LDAPMultiPlugins' here =", "Public License\", \"Programming Language :: Python\", \"Topic :: Internet :: WWW/HTTP :: Site", "\"License :: OSI Approved :: Zope Public License\", \"Programming Language :: Python\", \"Topic", ":: Authentication/Directory :: LDAP\", ], keywords='web application server zope zope2 ldap', author=\"<NAME> and", "import os from setuptools import setup from setuptools import find_packages NAME = 'LDAPMultiPlugins'", "Site Management\", \"Topic :: Software Development\", \"Topic :: System :: Systems Administration ::", ":: Systems Administration :: Authentication/Directory :: LDAP\", ], keywords='web application server zope zope2" ]
[ "for old_path, new_path in zip(args.src, args.dest): methods = [] for n, path in", "path', methods[0], methods[1]) cg = changegraph.build_from_files(old_path, new_path, repo_info=repo_info) change_graphs.append(cg) miner = Miner() if", "Starting ------------------------------') if settings.get('use_stackimpact', required=False): _ = stackimpact.start( agent_key=settings.get('stackimpact_agent_key'), app_name='CodeChangesMiner', debug=True, app_version=str(datetime.datetime.now()) )", "cg = changegraph.build_from_files(old_path, new_path, repo_info=repo_info) change_graphs.append(cg) miner = Miner() if args.fake_mining: for cg", "= cg fragment.nodes = cg.nodes pattern = Pattern([fragment]) miner.add_pattern(pattern) else: miner.mine_patterns(change_graphs) miner.print_patterns() else:", "not args.src or len(args.src) != len(args.dest): raise ValueError('src and dest have different size", "len(args.dest): raise ValueError('src and dest have different size or unset') change_graphs = []", "MINE_PATTERNS] def main(): logger.info('------------------------------ Starting ------------------------------') if settings.get('use_stackimpact', required=False): _ = stackimpact.start( agent_key=settings.get('stackimpact_agent_key'),", ") sys.setrecursionlimit(2**31-1) multiprocessing.set_start_method('spawn', force=True) parser = argparse.ArgumentParser() parser.add_argument('mode', help=f'One of {RunModes.ALL}', type=str) args,", "to output file', type=str, default='changegraph.dot') args = parser.parse_args() fg = changegraph.build_from_files(args.src, args.dest) changegraph.export_graph_image(fg,", "args.dest): methods = [] for n, path in enumerate([old_path, new_path]): with open(path, 'r+')", "BUILD_PY_FLOW_GRAPH = 'pfg' BUILD_CHANGE_GRAPH = 'cg' COLLECT_CHANGE_GRAPHS = 'collect-cgs' MINE_PATTERNS = 'patterns' ALL", "import Fragment, Pattern from vcs.traverse import GitAnalyzer, RepoInfo, Method import pyflowgraph import changegraph", "args.input, show_dependencies=args.show_deps, build_closure=not args.no_closure) pyflowgraph.export_graph_image( fg, args.output, show_op_kinds=not args.hide_op_kinds, show_data_keys=args.show_data_keys) elif current_mode ==", "BUILD_CHANGE_GRAPH = 'cg' COLLECT_CHANGE_GRAPHS = 'collect-cgs' MINE_PATTERNS = 'patterns' ALL = [BUILD_PY_FLOW_GRAPH, BUILD_CHANGE_GRAPH,", "parser.add_argument('--show-deps', action='store_true') parser.add_argument('--hide-op-kinds', action='store_true') parser.add_argument('--show-data-keys', action='store_true') args = parser.parse_args() fg = pyflowgraph.build_from_file( args.input,", "RunModes.BUILD_CHANGE_GRAPH: parser.add_argument('-s', '--src', help='Path to source code before changes', type=str, required=True) parser.add_argument('-d', '--dest',", "= os.path.join(storage_dir, file_name) try: with open(file_path, 'rb') as f: graphs = pickle.load(f) for", "mock_commit_dtm = datetime.datetime.now(tz=datetime.timezone.utc) repo_info = RepoInfo( 'mock repo path', 'mock repo name', 'mock", "for graph in graphs: change_graphs.append(pickle.loads(graph)) except: logger.warning(f'Incorrect file {file_path}') if file_num % 1000", "args.src or len(args.src) != len(args.dest): raise ValueError('src and dest have different size or", "file', type=str, default='changegraph.dot') args = parser.parse_args() fg = changegraph.build_from_files(args.src, args.dest) changegraph.export_graph_image(fg, args.output) elif", "change_graphs = [] for file_num, file_name in enumerate(file_names): file_path = os.path.join(storage_dir, file_name) try:", "file_name) try: with open(file_path, 'rb') as f: graphs = pickle.load(f) for graph in", "current_mode == RunModes.COLLECT_CHANGE_GRAPHS: GitAnalyzer().build_change_graphs() elif current_mode == RunModes.MINE_PATTERNS: parser.add_argument('-s', '--src', help='Path to source", "fg = changegraph.build_from_files(args.src, args.dest) changegraph.export_graph_image(fg, args.output) elif current_mode == RunModes.COLLECT_CHANGE_GRAPHS: GitAnalyzer().build_change_graphs() elif current_mode", "or len(args.src) != len(args.dest): raise ValueError('src and dest have different size or unset')", "import Miner from patterns.models import Fragment, Pattern from vcs.traverse import GitAnalyzer, RepoInfo, Method", "args.output, show_op_kinds=not args.hide_op_kinds, show_data_keys=args.show_data_keys) elif current_mode == RunModes.BUILD_CHANGE_GRAPH: parser.add_argument('-s', '--src', help='Path to source", "current_mode = args.mode if current_mode == RunModes.BUILD_PY_FLOW_GRAPH: parser.add_argument('-i', '--input', help='Path to source code", "= cg.nodes pattern = Pattern([fragment]) miner.add_pattern(pattern) else: miner.mine_patterns(change_graphs) miner.print_patterns() else: storage_dir = settings.get('change_graphs_storage_dir')", "else: storage_dir = settings.get('change_graphs_storage_dir') file_names = os.listdir(storage_dir) logger.warning(f'Found {len(file_names)} files in storage directory')", "Miner() try: miner.mine_patterns(change_graphs) except KeyboardInterrupt: logger.warning('KeyboardInterrupt: mined patterns will be stored before exit')", "required=True) parser.add_argument('-o', '--output', help='Path to output file', type=str, default='changegraph.dot') args = parser.parse_args() fg", "from vcs.traverse import GitAnalyzer, RepoInfo, Method import pyflowgraph import changegraph import settings class", "action='store_true') parser.add_argument('--show-data-keys', action='store_true') args = parser.parse_args() fg = pyflowgraph.build_from_file( args.input, show_dependencies=args.show_deps, build_closure=not args.no_closure)", "parser = argparse.ArgumentParser() parser.add_argument('mode', help=f'One of {RunModes.ALL}', type=str) args, _ = parser.parse_known_args() current_mode", "miner.mine_patterns(change_graphs) miner.print_patterns() else: storage_dir = settings.get('change_graphs_storage_dir') file_names = os.listdir(storage_dir) logger.warning(f'Found {len(file_names)} files in", "miner = Miner() try: miner.mine_patterns(change_graphs) except KeyboardInterrupt: logger.warning('KeyboardInterrupt: mined patterns will be stored", "'pfg' BUILD_CHANGE_GRAPH = 'cg' COLLECT_CHANGE_GRAPHS = 'collect-cgs' MINE_PATTERNS = 'patterns' ALL = [BUILD_PY_FLOW_GRAPH,", "'--src', help='Path to source code before changes', type=str, required=True) parser.add_argument('-d', '--dest', help='Path to", "= [] for n, path in enumerate([old_path, new_path]): with open(path, 'r+') as f:", "if file_num % 1000 == 0: logger.warning(f'Loaded [{1+file_num}/{len(file_names)}] files') logger.warning('Pattern mining has started')", "== 0: logger.warning(f'Loaded [{1+file_num}/{len(file_names)}] files') logger.warning('Pattern mining has started') miner = Miner() try:", "help='Path to source code before changes', type=str, required=True) parser.add_argument('-d', '--dest', help='Path to source", "nargs='+') parser.add_argument('-d', '--dest', help='Path to source code after changes', type=str, nargs='+') parser.add_argument('--fake-mining', action='store_true')", "[] for old_path, new_path in zip(args.src, args.dest): methods = [] for n, path", "repo url', 'mock hash', mock_commit_dtm, 'mock old file path', 'mock new file path',", "args.hide_op_kinds, show_data_keys=args.show_data_keys) elif current_mode == RunModes.BUILD_CHANGE_GRAPH: parser.add_argument('-s', '--src', help='Path to source code before", "with open(path, 'r+') as f: src = f.read() methods.append(Method(path, 'test_name', ast.parse(src, mode='exec').body[0], src))", "== RunModes.BUILD_CHANGE_GRAPH: parser.add_argument('-s', '--src', help='Path to source code before changes', type=str, required=True) parser.add_argument('-d',", "will be stored before exit') miner.print_patterns() else: raise ValueError if __name__ == '__main__':", "or args.fake_mining: if not args.src or len(args.src) != len(args.dest): raise ValueError('src and dest", "raise ValueError('src and dest have different size or unset') change_graphs = [] for", "------------------------------') if settings.get('use_stackimpact', required=False): _ = stackimpact.start( agent_key=settings.get('stackimpact_agent_key'), app_name='CodeChangesMiner', debug=True, app_version=str(datetime.datetime.now()) ) sys.setrecursionlimit(2**31-1)", "{file_path}') if file_num % 1000 == 0: logger.warning(f'Loaded [{1+file_num}/{len(file_names)}] files') logger.warning('Pattern mining has", "build_closure=not args.no_closure) pyflowgraph.export_graph_image( fg, args.output, show_op_kinds=not args.hide_op_kinds, show_data_keys=args.show_data_keys) elif current_mode == RunModes.BUILD_CHANGE_GRAPH: parser.add_argument('-s',", "patterns.models import Fragment, Pattern from vcs.traverse import GitAnalyzer, RepoInfo, Method import pyflowgraph import", "changes', type=str, nargs='+') parser.add_argument('-d', '--dest', help='Path to source code after changes', type=str, nargs='+')", "parser.add_argument('-o', '--output', help='Path to output file', type=str, default='changegraph.dot') args = parser.parse_args() fg =", "parser.add_argument('--no-closure', action='store_true') parser.add_argument('--show-deps', action='store_true') parser.add_argument('--hide-op-kinds', action='store_true') parser.add_argument('--show-data-keys', action='store_true') args = parser.parse_args() fg =", "methods = [] for n, path in enumerate([old_path, new_path]): with open(path, 'r+') as", "file_path = os.path.join(storage_dir, file_name) try: with open(file_path, 'rb') as f: graphs = pickle.load(f)", "storage directory') change_graphs = [] for file_num, file_name in enumerate(file_names): file_path = os.path.join(storage_dir,", "zip(args.src, args.dest): methods = [] for n, path in enumerate([old_path, new_path]): with open(path,", "else: miner.mine_patterns(change_graphs) miner.print_patterns() else: storage_dir = settings.get('change_graphs_storage_dir') file_names = os.listdir(storage_dir) logger.warning(f'Found {len(file_names)} files", "elif current_mode == RunModes.MINE_PATTERNS: parser.add_argument('-s', '--src', help='Path to source code before changes', type=str,", "patterns will be stored before exit') miner.print_patterns() else: raise ValueError if __name__ ==", "to source code after changes', type=str, required=True) parser.add_argument('-o', '--output', help='Path to output file',", "open(path, 'r+') as f: src = f.read() methods.append(Method(path, 'test_name', ast.parse(src, mode='exec').body[0], src)) mock_commit_dtm", "Fragment, Pattern from vcs.traverse import GitAnalyzer, RepoInfo, Method import pyflowgraph import changegraph import", "except KeyboardInterrupt: logger.warning('KeyboardInterrupt: mined patterns will be stored before exit') miner.print_patterns() else: raise", "RepoInfo, Method import pyflowgraph import changegraph import settings class RunModes: BUILD_PY_FLOW_GRAPH = 'pfg'", "pyflowgraph.build_from_file( args.input, show_dependencies=args.show_deps, build_closure=not args.no_closure) pyflowgraph.export_graph_image( fg, args.output, show_op_kinds=not args.hide_op_kinds, show_data_keys=args.show_data_keys) elif current_mode", "try: with open(file_path, 'rb') as f: graphs = pickle.load(f) for graph in graphs:", "methods.append(Method(path, 'test_name', ast.parse(src, mode='exec').body[0], src)) mock_commit_dtm = datetime.datetime.now(tz=datetime.timezone.utc) repo_info = RepoInfo( 'mock repo", "multiprocessing from log import logger from patterns import Miner from patterns.models import Fragment,", "parser.add_argument('-s', '--src', help='Path to source code before changes', type=str, required=True) parser.add_argument('-d', '--dest', help='Path", "logger.warning('KeyboardInterrupt: mined patterns will be stored before exit') miner.print_patterns() else: raise ValueError if", "'mock new file path', methods[0], methods[1]) cg = changegraph.build_from_files(old_path, new_path, repo_info=repo_info) change_graphs.append(cg) miner", "code after changes', type=str, required=True) parser.add_argument('-o', '--output', help='Path to output file', type=str, default='changegraph.dot')", "% 1000 == 0: logger.warning(f'Loaded [{1+file_num}/{len(file_names)}] files') logger.warning('Pattern mining has started') miner =", "argparse.ArgumentParser() parser.add_argument('mode', help=f'One of {RunModes.ALL}', type=str) args, _ = parser.parse_known_args() current_mode = args.mode", "cg in change_graphs: fragment = Fragment() fragment.graph = cg fragment.nodes = cg.nodes pattern", "output file', type=str, default='changegraph.dot') args = parser.parse_args() fg = changegraph.build_from_files(args.src, args.dest) changegraph.export_graph_image(fg, args.output)", "'--output', help='Path to output file', type=str, default='pyflowgraph.dot') parser.add_argument('--no-closure', action='store_true') parser.add_argument('--show-deps', action='store_true') parser.add_argument('--hide-op-kinds', action='store_true')", "ast import os import pickle import sys import stackimpact import datetime import argparse", "path in enumerate([old_path, new_path]): with open(path, 'r+') as f: src = f.read() methods.append(Method(path,", "source code before changes', type=str, required=True) parser.add_argument('-d', '--dest', help='Path to source code after", "settings.get('use_stackimpact', required=False): _ = stackimpact.start( agent_key=settings.get('stackimpact_agent_key'), app_name='CodeChangesMiner', debug=True, app_version=str(datetime.datetime.now()) ) sys.setrecursionlimit(2**31-1) multiprocessing.set_start_method('spawn', force=True)", "GitAnalyzer, RepoInfo, Method import pyflowgraph import changegraph import settings class RunModes: BUILD_PY_FLOW_GRAPH =", "required=False): _ = stackimpact.start( agent_key=settings.get('stackimpact_agent_key'), app_name='CodeChangesMiner', debug=True, app_version=str(datetime.datetime.now()) ) sys.setrecursionlimit(2**31-1) multiprocessing.set_start_method('spawn', force=True) parser", "if settings.get('use_stackimpact', required=False): _ = stackimpact.start( agent_key=settings.get('stackimpact_agent_key'), app_name='CodeChangesMiner', debug=True, app_version=str(datetime.datetime.now()) ) sys.setrecursionlimit(2**31-1) multiprocessing.set_start_method('spawn',", "parser.parse_args() if args.src or args.dest or args.fake_mining: if not args.src or len(args.src) !=", "= 'patterns' ALL = [BUILD_PY_FLOW_GRAPH, BUILD_CHANGE_GRAPH, COLLECT_CHANGE_GRAPHS, MINE_PATTERNS] def main(): logger.info('------------------------------ Starting ------------------------------')", "changegraph.export_graph_image(fg, args.output) elif current_mode == RunModes.COLLECT_CHANGE_GRAPHS: GitAnalyzer().build_change_graphs() elif current_mode == RunModes.MINE_PATTERNS: parser.add_argument('-s', '--src',", "for file_num, file_name in enumerate(file_names): file_path = os.path.join(storage_dir, file_name) try: with open(file_path, 'rb')", "graphs = pickle.load(f) for graph in graphs: change_graphs.append(pickle.loads(graph)) except: logger.warning(f'Incorrect file {file_path}') if", "datetime import argparse import multiprocessing from log import logger from patterns import Miner", "source code file', type=str, required=True) parser.add_argument('-o', '--output', help='Path to output file', type=str, default='pyflowgraph.dot')", "mined patterns will be stored before exit') miner.print_patterns() else: raise ValueError if __name__", "parser.parse_known_args() current_mode = args.mode if current_mode == RunModes.BUILD_PY_FLOW_GRAPH: parser.add_argument('-i', '--input', help='Path to source", "'--src', help='Path to source code before changes', type=str, nargs='+') parser.add_argument('-d', '--dest', help='Path to", "debug=True, app_version=str(datetime.datetime.now()) ) sys.setrecursionlimit(2**31-1) multiprocessing.set_start_method('spawn', force=True) parser = argparse.ArgumentParser() parser.add_argument('mode', help=f'One of {RunModes.ALL}',", "app_version=str(datetime.datetime.now()) ) sys.setrecursionlimit(2**31-1) multiprocessing.set_start_method('spawn', force=True) parser = argparse.ArgumentParser() parser.add_argument('mode', help=f'One of {RunModes.ALL}', type=str)", "type=str, nargs='+') parser.add_argument('--fake-mining', action='store_true') args = parser.parse_args() if args.src or args.dest or args.fake_mining:", "'patterns' ALL = [BUILD_PY_FLOW_GRAPH, BUILD_CHANGE_GRAPH, COLLECT_CHANGE_GRAPHS, MINE_PATTERNS] def main(): logger.info('------------------------------ Starting ------------------------------') if", "miner.print_patterns() else: storage_dir = settings.get('change_graphs_storage_dir') file_names = os.listdir(storage_dir) logger.warning(f'Found {len(file_names)} files in storage", "= stackimpact.start( agent_key=settings.get('stackimpact_agent_key'), app_name='CodeChangesMiner', debug=True, app_version=str(datetime.datetime.now()) ) sys.setrecursionlimit(2**31-1) multiprocessing.set_start_method('spawn', force=True) parser = argparse.ArgumentParser()", "miner.mine_patterns(change_graphs) except KeyboardInterrupt: logger.warning('KeyboardInterrupt: mined patterns will be stored before exit') miner.print_patterns() else:", "file path', 'mock new file path', methods[0], methods[1]) cg = changegraph.build_from_files(old_path, new_path, repo_info=repo_info)", "== RunModes.MINE_PATTERNS: parser.add_argument('-s', '--src', help='Path to source code before changes', type=str, nargs='+') parser.add_argument('-d',", "miner.add_pattern(pattern) else: miner.mine_patterns(change_graphs) miner.print_patterns() else: storage_dir = settings.get('change_graphs_storage_dir') file_names = os.listdir(storage_dir) logger.warning(f'Found {len(file_names)}", "RunModes: BUILD_PY_FLOW_GRAPH = 'pfg' BUILD_CHANGE_GRAPH = 'cg' COLLECT_CHANGE_GRAPHS = 'collect-cgs' MINE_PATTERNS = 'patterns'", "Fragment() fragment.graph = cg fragment.nodes = cg.nodes pattern = Pattern([fragment]) miner.add_pattern(pattern) else: miner.mine_patterns(change_graphs)", "os import pickle import sys import stackimpact import datetime import argparse import multiprocessing", "parser.parse_args() fg = pyflowgraph.build_from_file( args.input, show_dependencies=args.show_deps, build_closure=not args.no_closure) pyflowgraph.export_graph_image( fg, args.output, show_op_kinds=not args.hide_op_kinds,", "action='store_true') parser.add_argument('--show-deps', action='store_true') parser.add_argument('--hide-op-kinds', action='store_true') parser.add_argument('--show-data-keys', action='store_true') args = parser.parse_args() fg = pyflowgraph.build_from_file(", "args.fake_mining: if not args.src or len(args.src) != len(args.dest): raise ValueError('src and dest have", "in change_graphs: fragment = Fragment() fragment.graph = cg fragment.nodes = cg.nodes pattern =", "pyflowgraph.export_graph_image( fg, args.output, show_op_kinds=not args.hide_op_kinds, show_data_keys=args.show_data_keys) elif current_mode == RunModes.BUILD_CHANGE_GRAPH: parser.add_argument('-s', '--src', help='Path", "dest have different size or unset') change_graphs = [] for old_path, new_path in", "{RunModes.ALL}', type=str) args, _ = parser.parse_known_args() current_mode = args.mode if current_mode == RunModes.BUILD_PY_FLOW_GRAPH:", "fg = pyflowgraph.build_from_file( args.input, show_dependencies=args.show_deps, build_closure=not args.no_closure) pyflowgraph.export_graph_image( fg, args.output, show_op_kinds=not args.hide_op_kinds, show_data_keys=args.show_data_keys)", "change_graphs: fragment = Fragment() fragment.graph = cg fragment.nodes = cg.nodes pattern = Pattern([fragment])", "elif current_mode == RunModes.COLLECT_CHANGE_GRAPHS: GitAnalyzer().build_change_graphs() elif current_mode == RunModes.MINE_PATTERNS: parser.add_argument('-s', '--src', help='Path to", "args, _ = parser.parse_known_args() current_mode = args.mode if current_mode == RunModes.BUILD_PY_FLOW_GRAPH: parser.add_argument('-i', '--input',", "if args.src or args.dest or args.fake_mining: if not args.src or len(args.src) != len(args.dest):", "0: logger.warning(f'Loaded [{1+file_num}/{len(file_names)}] files') logger.warning('Pattern mining has started') miner = Miner() try: miner.mine_patterns(change_graphs)", "src = f.read() methods.append(Method(path, 'test_name', ast.parse(src, mode='exec').body[0], src)) mock_commit_dtm = datetime.datetime.now(tz=datetime.timezone.utc) repo_info =", "== RunModes.COLLECT_CHANGE_GRAPHS: GitAnalyzer().build_change_graphs() elif current_mode == RunModes.MINE_PATTERNS: parser.add_argument('-s', '--src', help='Path to source code", "from patterns.models import Fragment, Pattern from vcs.traverse import GitAnalyzer, RepoInfo, Method import pyflowgraph", "to source code before changes', type=str, required=True) parser.add_argument('-d', '--dest', help='Path to source code", "RepoInfo( 'mock repo path', 'mock repo name', 'mock repo url', 'mock hash', mock_commit_dtm,", "in graphs: change_graphs.append(pickle.loads(graph)) except: logger.warning(f'Incorrect file {file_path}') if file_num % 1000 == 0:", "Method import pyflowgraph import changegraph import settings class RunModes: BUILD_PY_FLOW_GRAPH = 'pfg' BUILD_CHANGE_GRAPH", "= f.read() methods.append(Method(path, 'test_name', ast.parse(src, mode='exec').body[0], src)) mock_commit_dtm = datetime.datetime.now(tz=datetime.timezone.utc) repo_info = RepoInfo(", "class RunModes: BUILD_PY_FLOW_GRAPH = 'pfg' BUILD_CHANGE_GRAPH = 'cg' COLLECT_CHANGE_GRAPHS = 'collect-cgs' MINE_PATTERNS =", "COLLECT_CHANGE_GRAPHS = 'collect-cgs' MINE_PATTERNS = 'patterns' ALL = [BUILD_PY_FLOW_GRAPH, BUILD_CHANGE_GRAPH, COLLECT_CHANGE_GRAPHS, MINE_PATTERNS] def", "import stackimpact import datetime import argparse import multiprocessing from log import logger from", "MINE_PATTERNS = 'patterns' ALL = [BUILD_PY_FLOW_GRAPH, BUILD_CHANGE_GRAPH, COLLECT_CHANGE_GRAPHS, MINE_PATTERNS] def main(): logger.info('------------------------------ Starting", "'collect-cgs' MINE_PATTERNS = 'patterns' ALL = [BUILD_PY_FLOW_GRAPH, BUILD_CHANGE_GRAPH, COLLECT_CHANGE_GRAPHS, MINE_PATTERNS] def main(): logger.info('------------------------------", "files in storage directory') change_graphs = [] for file_num, file_name in enumerate(file_names): file_path", "args.src or args.dest or args.fake_mining: if not args.src or len(args.src) != len(args.dest): raise", "new_path]): with open(path, 'r+') as f: src = f.read() methods.append(Method(path, 'test_name', ast.parse(src, mode='exec').body[0],", "'r+') as f: src = f.read() methods.append(Method(path, 'test_name', ast.parse(src, mode='exec').body[0], src)) mock_commit_dtm =", "import settings class RunModes: BUILD_PY_FLOW_GRAPH = 'pfg' BUILD_CHANGE_GRAPH = 'cg' COLLECT_CHANGE_GRAPHS = 'collect-cgs'", "= 'cg' COLLECT_CHANGE_GRAPHS = 'collect-cgs' MINE_PATTERNS = 'patterns' ALL = [BUILD_PY_FLOW_GRAPH, BUILD_CHANGE_GRAPH, COLLECT_CHANGE_GRAPHS,", "repo_info = RepoInfo( 'mock repo path', 'mock repo name', 'mock repo url', 'mock", "= args.mode if current_mode == RunModes.BUILD_PY_FLOW_GRAPH: parser.add_argument('-i', '--input', help='Path to source code file',", "started') miner = Miner() try: miner.mine_patterns(change_graphs) except KeyboardInterrupt: logger.warning('KeyboardInterrupt: mined patterns will be", "new file path', methods[0], methods[1]) cg = changegraph.build_from_files(old_path, new_path, repo_info=repo_info) change_graphs.append(cg) miner =", "help='Path to source code before changes', type=str, nargs='+') parser.add_argument('-d', '--dest', help='Path to source", "and dest have different size or unset') change_graphs = [] for old_path, new_path", "'cg' COLLECT_CHANGE_GRAPHS = 'collect-cgs' MINE_PATTERNS = 'patterns' ALL = [BUILD_PY_FLOW_GRAPH, BUILD_CHANGE_GRAPH, COLLECT_CHANGE_GRAPHS, MINE_PATTERNS]", "changes', type=str, required=True) parser.add_argument('-d', '--dest', help='Path to source code after changes', type=str, required=True)", "import sys import stackimpact import datetime import argparse import multiprocessing from log import", "output file', type=str, default='pyflowgraph.dot') parser.add_argument('--no-closure', action='store_true') parser.add_argument('--show-deps', action='store_true') parser.add_argument('--hide-op-kinds', action='store_true') parser.add_argument('--show-data-keys', action='store_true') args", "= RepoInfo( 'mock repo path', 'mock repo name', 'mock repo url', 'mock hash',", "Miner() if args.fake_mining: for cg in change_graphs: fragment = Fragment() fragment.graph = cg", "to source code file', type=str, required=True) parser.add_argument('-o', '--output', help='Path to output file', type=str,", "code before changes', type=str, nargs='+') parser.add_argument('-d', '--dest', help='Path to source code after changes',", "ValueError('src and dest have different size or unset') change_graphs = [] for old_path,", "repo_info=repo_info) change_graphs.append(cg) miner = Miner() if args.fake_mining: for cg in change_graphs: fragment =", "in storage directory') change_graphs = [] for file_num, file_name in enumerate(file_names): file_path =", "'test_name', ast.parse(src, mode='exec').body[0], src)) mock_commit_dtm = datetime.datetime.now(tz=datetime.timezone.utc) repo_info = RepoInfo( 'mock repo path',", "help='Path to output file', type=str, default='pyflowgraph.dot') parser.add_argument('--no-closure', action='store_true') parser.add_argument('--show-deps', action='store_true') parser.add_argument('--hide-op-kinds', action='store_true') parser.add_argument('--show-data-keys',", "current_mode == RunModes.MINE_PATTERNS: parser.add_argument('-s', '--src', help='Path to source code before changes', type=str, nargs='+')", "before changes', type=str, nargs='+') parser.add_argument('-d', '--dest', help='Path to source code after changes', type=str,", "changes', type=str, nargs='+') parser.add_argument('--fake-mining', action='store_true') args = parser.parse_args() if args.src or args.dest or", "= Miner() if args.fake_mining: for cg in change_graphs: fragment = Fragment() fragment.graph =", "source code after changes', type=str, nargs='+') parser.add_argument('--fake-mining', action='store_true') args = parser.parse_args() if args.src", "old file path', 'mock new file path', methods[0], methods[1]) cg = changegraph.build_from_files(old_path, new_path,", "enumerate(file_names): file_path = os.path.join(storage_dir, file_name) try: with open(file_path, 'rb') as f: graphs =", "logger from patterns import Miner from patterns.models import Fragment, Pattern from vcs.traverse import", "if not args.src or len(args.src) != len(args.dest): raise ValueError('src and dest have different", "or args.dest or args.fake_mining: if not args.src or len(args.src) != len(args.dest): raise ValueError('src", "= 'pfg' BUILD_CHANGE_GRAPH = 'cg' COLLECT_CHANGE_GRAPHS = 'collect-cgs' MINE_PATTERNS = 'patterns' ALL =", "agent_key=settings.get('stackimpact_agent_key'), app_name='CodeChangesMiner', debug=True, app_version=str(datetime.datetime.now()) ) sys.setrecursionlimit(2**31-1) multiprocessing.set_start_method('spawn', force=True) parser = argparse.ArgumentParser() parser.add_argument('mode', help=f'One", "for n, path in enumerate([old_path, new_path]): with open(path, 'r+') as f: src =", "import GitAnalyzer, RepoInfo, Method import pyflowgraph import changegraph import settings class RunModes: BUILD_PY_FLOW_GRAPH", "args = parser.parse_args() fg = changegraph.build_from_files(args.src, args.dest) changegraph.export_graph_image(fg, args.output) elif current_mode == RunModes.COLLECT_CHANGE_GRAPHS:", "= parser.parse_args() fg = changegraph.build_from_files(args.src, args.dest) changegraph.export_graph_image(fg, args.output) elif current_mode == RunModes.COLLECT_CHANGE_GRAPHS: GitAnalyzer().build_change_graphs()", "or unset') change_graphs = [] for old_path, new_path in zip(args.src, args.dest): methods =", "change_graphs.append(pickle.loads(graph)) except: logger.warning(f'Incorrect file {file_path}') if file_num % 1000 == 0: logger.warning(f'Loaded [{1+file_num}/{len(file_names)}]", "storage_dir = settings.get('change_graphs_storage_dir') file_names = os.listdir(storage_dir) logger.warning(f'Found {len(file_names)} files in storage directory') change_graphs", "to source code before changes', type=str, nargs='+') parser.add_argument('-d', '--dest', help='Path to source code", "= Miner() try: miner.mine_patterns(change_graphs) except KeyboardInterrupt: logger.warning('KeyboardInterrupt: mined patterns will be stored before", "type=str, required=True) parser.add_argument('-o', '--output', help='Path to output file', type=str, default='pyflowgraph.dot') parser.add_argument('--no-closure', action='store_true') parser.add_argument('--show-deps',", "{len(file_names)} files in storage directory') change_graphs = [] for file_num, file_name in enumerate(file_names):", "parser.add_argument('-o', '--output', help='Path to output file', type=str, default='pyflowgraph.dot') parser.add_argument('--no-closure', action='store_true') parser.add_argument('--show-deps', action='store_true') parser.add_argument('--hide-op-kinds',", "if args.fake_mining: for cg in change_graphs: fragment = Fragment() fragment.graph = cg fragment.nodes", "if current_mode == RunModes.BUILD_PY_FLOW_GRAPH: parser.add_argument('-i', '--input', help='Path to source code file', type=str, required=True)", "stackimpact import datetime import argparse import multiprocessing from log import logger from patterns", "required=True) parser.add_argument('-d', '--dest', help='Path to source code after changes', type=str, required=True) parser.add_argument('-o', '--output',", "current_mode == RunModes.BUILD_CHANGE_GRAPH: parser.add_argument('-s', '--src', help='Path to source code before changes', type=str, required=True)", "cg fragment.nodes = cg.nodes pattern = Pattern([fragment]) miner.add_pattern(pattern) else: miner.mine_patterns(change_graphs) miner.print_patterns() else: storage_dir", "fragment = Fragment() fragment.graph = cg fragment.nodes = cg.nodes pattern = Pattern([fragment]) miner.add_pattern(pattern)", "type=str, required=True) parser.add_argument('-o', '--output', help='Path to output file', type=str, default='changegraph.dot') args = parser.parse_args()", "new_path, repo_info=repo_info) change_graphs.append(cg) miner = Miner() if args.fake_mining: for cg in change_graphs: fragment", "settings.get('change_graphs_storage_dir') file_names = os.listdir(storage_dir) logger.warning(f'Found {len(file_names)} files in storage directory') change_graphs = []", "argparse import multiprocessing from log import logger from patterns import Miner from patterns.models", "fragment.graph = cg fragment.nodes = cg.nodes pattern = Pattern([fragment]) miner.add_pattern(pattern) else: miner.mine_patterns(change_graphs) miner.print_patterns()", "import changegraph import settings class RunModes: BUILD_PY_FLOW_GRAPH = 'pfg' BUILD_CHANGE_GRAPH = 'cg' COLLECT_CHANGE_GRAPHS", "pyflowgraph import changegraph import settings class RunModes: BUILD_PY_FLOW_GRAPH = 'pfg' BUILD_CHANGE_GRAPH = 'cg'", "changes', type=str, required=True) parser.add_argument('-o', '--output', help='Path to output file', type=str, default='changegraph.dot') args =", "!= len(args.dest): raise ValueError('src and dest have different size or unset') change_graphs =", "hash', mock_commit_dtm, 'mock old file path', 'mock new file path', methods[0], methods[1]) cg", "import logger from patterns import Miner from patterns.models import Fragment, Pattern from vcs.traverse", "fragment.nodes = cg.nodes pattern = Pattern([fragment]) miner.add_pattern(pattern) else: miner.mine_patterns(change_graphs) miner.print_patterns() else: storage_dir =", "parser.add_argument('mode', help=f'One of {RunModes.ALL}', type=str) args, _ = parser.parse_known_args() current_mode = args.mode if", "files') logger.warning('Pattern mining has started') miner = Miner() try: miner.mine_patterns(change_graphs) except KeyboardInterrupt: logger.warning('KeyboardInterrupt:", "import datetime import argparse import multiprocessing from log import logger from patterns import", "code file', type=str, required=True) parser.add_argument('-o', '--output', help='Path to output file', type=str, default='pyflowgraph.dot') parser.add_argument('--no-closure',", "to source code after changes', type=str, nargs='+') parser.add_argument('--fake-mining', action='store_true') args = parser.parse_args() if", "logger.warning(f'Found {len(file_names)} files in storage directory') change_graphs = [] for file_num, file_name in", "ALL = [BUILD_PY_FLOW_GRAPH, BUILD_CHANGE_GRAPH, COLLECT_CHANGE_GRAPHS, MINE_PATTERNS] def main(): logger.info('------------------------------ Starting ------------------------------') if settings.get('use_stackimpact',", "after changes', type=str, nargs='+') parser.add_argument('--fake-mining', action='store_true') args = parser.parse_args() if args.src or args.dest", "path', 'mock repo name', 'mock repo url', 'mock hash', mock_commit_dtm, 'mock old file", "changegraph.build_from_files(old_path, new_path, repo_info=repo_info) change_graphs.append(cg) miner = Miner() if args.fake_mining: for cg in change_graphs:", "= pyflowgraph.build_from_file( args.input, show_dependencies=args.show_deps, build_closure=not args.no_closure) pyflowgraph.export_graph_image( fg, args.output, show_op_kinds=not args.hide_op_kinds, show_data_keys=args.show_data_keys) elif", "mock_commit_dtm, 'mock old file path', 'mock new file path', methods[0], methods[1]) cg =", "import pickle import sys import stackimpact import datetime import argparse import multiprocessing from", "[] for n, path in enumerate([old_path, new_path]): with open(path, 'r+') as f: src", "graph in graphs: change_graphs.append(pickle.loads(graph)) except: logger.warning(f'Incorrect file {file_path}') if file_num % 1000 ==", "= [BUILD_PY_FLOW_GRAPH, BUILD_CHANGE_GRAPH, COLLECT_CHANGE_GRAPHS, MINE_PATTERNS] def main(): logger.info('------------------------------ Starting ------------------------------') if settings.get('use_stackimpact', required=False):", "'--dest', help='Path to source code after changes', type=str, nargs='+') parser.add_argument('--fake-mining', action='store_true') args =", "stackimpact.start( agent_key=settings.get('stackimpact_agent_key'), app_name='CodeChangesMiner', debug=True, app_version=str(datetime.datetime.now()) ) sys.setrecursionlimit(2**31-1) multiprocessing.set_start_method('spawn', force=True) parser = argparse.ArgumentParser() parser.add_argument('mode',", "pattern = Pattern([fragment]) miner.add_pattern(pattern) else: miner.mine_patterns(change_graphs) miner.print_patterns() else: storage_dir = settings.get('change_graphs_storage_dir') file_names =", "import os import pickle import sys import stackimpact import datetime import argparse import", "nargs='+') parser.add_argument('--fake-mining', action='store_true') args = parser.parse_args() if args.src or args.dest or args.fake_mining: if", "repo path', 'mock repo name', 'mock repo url', 'mock hash', mock_commit_dtm, 'mock old", "import multiprocessing from log import logger from patterns import Miner from patterns.models import", "= Pattern([fragment]) miner.add_pattern(pattern) else: miner.mine_patterns(change_graphs) miner.print_patterns() else: storage_dir = settings.get('change_graphs_storage_dir') file_names = os.listdir(storage_dir)", "'--dest', help='Path to source code after changes', type=str, required=True) parser.add_argument('-o', '--output', help='Path to", "Miner from patterns.models import Fragment, Pattern from vcs.traverse import GitAnalyzer, RepoInfo, Method import", "in enumerate(file_names): file_path = os.path.join(storage_dir, file_name) try: with open(file_path, 'rb') as f: graphs", "old_path, new_path in zip(args.src, args.dest): methods = [] for n, path in enumerate([old_path,", "methods[0], methods[1]) cg = changegraph.build_from_files(old_path, new_path, repo_info=repo_info) change_graphs.append(cg) miner = Miner() if args.fake_mining:", "change_graphs = [] for old_path, new_path in zip(args.src, args.dest): methods = [] for", "methods[1]) cg = changegraph.build_from_files(old_path, new_path, repo_info=repo_info) change_graphs.append(cg) miner = Miner() if args.fake_mining: for", "logger.info('------------------------------ Starting ------------------------------') if settings.get('use_stackimpact', required=False): _ = stackimpact.start( agent_key=settings.get('stackimpact_agent_key'), app_name='CodeChangesMiner', debug=True, app_version=str(datetime.datetime.now())", "force=True) parser = argparse.ArgumentParser() parser.add_argument('mode', help=f'One of {RunModes.ALL}', type=str) args, _ = parser.parse_known_args()", "file', type=str, default='pyflowgraph.dot') parser.add_argument('--no-closure', action='store_true') parser.add_argument('--show-deps', action='store_true') parser.add_argument('--hide-op-kinds', action='store_true') parser.add_argument('--show-data-keys', action='store_true') args =", "= parser.parse_args() fg = pyflowgraph.build_from_file( args.input, show_dependencies=args.show_deps, build_closure=not args.no_closure) pyflowgraph.export_graph_image( fg, args.output, show_op_kinds=not", "parser.add_argument('-s', '--src', help='Path to source code before changes', type=str, nargs='+') parser.add_argument('-d', '--dest', help='Path", "len(args.src) != len(args.dest): raise ValueError('src and dest have different size or unset') change_graphs", "os.listdir(storage_dir) logger.warning(f'Found {len(file_names)} files in storage directory') change_graphs = [] for file_num, file_name", "size or unset') change_graphs = [] for old_path, new_path in zip(args.src, args.dest): methods", "logger.warning('Pattern mining has started') miner = Miner() try: miner.mine_patterns(change_graphs) except KeyboardInterrupt: logger.warning('KeyboardInterrupt: mined", "main(): logger.info('------------------------------ Starting ------------------------------') if settings.get('use_stackimpact', required=False): _ = stackimpact.start( agent_key=settings.get('stackimpact_agent_key'), app_name='CodeChangesMiner', debug=True,", "in enumerate([old_path, new_path]): with open(path, 'r+') as f: src = f.read() methods.append(Method(path, 'test_name',", "name', 'mock repo url', 'mock hash', mock_commit_dtm, 'mock old file path', 'mock new", "args.dest or args.fake_mining: if not args.src or len(args.src) != len(args.dest): raise ValueError('src and", "action='store_true') parser.add_argument('--hide-op-kinds', action='store_true') parser.add_argument('--show-data-keys', action='store_true') args = parser.parse_args() fg = pyflowgraph.build_from_file( args.input, show_dependencies=args.show_deps,", "f.read() methods.append(Method(path, 'test_name', ast.parse(src, mode='exec').body[0], src)) mock_commit_dtm = datetime.datetime.now(tz=datetime.timezone.utc) repo_info = RepoInfo( 'mock", "changegraph import settings class RunModes: BUILD_PY_FLOW_GRAPH = 'pfg' BUILD_CHANGE_GRAPH = 'cg' COLLECT_CHANGE_GRAPHS =", "pickle import sys import stackimpact import datetime import argparse import multiprocessing from log", "args.fake_mining: for cg in change_graphs: fragment = Fragment() fragment.graph = cg fragment.nodes =", "'mock repo path', 'mock repo name', 'mock repo url', 'mock hash', mock_commit_dtm, 'mock", "COLLECT_CHANGE_GRAPHS, MINE_PATTERNS] def main(): logger.info('------------------------------ Starting ------------------------------') if settings.get('use_stackimpact', required=False): _ = stackimpact.start(", "current_mode == RunModes.BUILD_PY_FLOW_GRAPH: parser.add_argument('-i', '--input', help='Path to source code file', type=str, required=True) parser.add_argument('-o',", "from patterns import Miner from patterns.models import Fragment, Pattern from vcs.traverse import GitAnalyzer,", "default='changegraph.dot') args = parser.parse_args() fg = changegraph.build_from_files(args.src, args.dest) changegraph.export_graph_image(fg, args.output) elif current_mode ==", "directory') change_graphs = [] for file_num, file_name in enumerate(file_names): file_path = os.path.join(storage_dir, file_name)", "[BUILD_PY_FLOW_GRAPH, BUILD_CHANGE_GRAPH, COLLECT_CHANGE_GRAPHS, MINE_PATTERNS] def main(): logger.info('------------------------------ Starting ------------------------------') if settings.get('use_stackimpact', required=False): _", "parser.add_argument('--show-data-keys', action='store_true') args = parser.parse_args() fg = pyflowgraph.build_from_file( args.input, show_dependencies=args.show_deps, build_closure=not args.no_closure) pyflowgraph.export_graph_image(", "ast.parse(src, mode='exec').body[0], src)) mock_commit_dtm = datetime.datetime.now(tz=datetime.timezone.utc) repo_info = RepoInfo( 'mock repo path', 'mock", "file_name in enumerate(file_names): file_path = os.path.join(storage_dir, file_name) try: with open(file_path, 'rb') as f:", "= pickle.load(f) for graph in graphs: change_graphs.append(pickle.loads(graph)) except: logger.warning(f'Incorrect file {file_path}') if file_num", "[] for file_num, file_name in enumerate(file_names): file_path = os.path.join(storage_dir, file_name) try: with open(file_path,", "= parser.parse_known_args() current_mode = args.mode if current_mode == RunModes.BUILD_PY_FLOW_GRAPH: parser.add_argument('-i', '--input', help='Path to", "type=str) args, _ = parser.parse_known_args() current_mode = args.mode if current_mode == RunModes.BUILD_PY_FLOW_GRAPH: parser.add_argument('-i',", "vcs.traverse import GitAnalyzer, RepoInfo, Method import pyflowgraph import changegraph import settings class RunModes:", "elif current_mode == RunModes.BUILD_CHANGE_GRAPH: parser.add_argument('-s', '--src', help='Path to source code before changes', type=str,", "_ = parser.parse_known_args() current_mode = args.mode if current_mode == RunModes.BUILD_PY_FLOW_GRAPH: parser.add_argument('-i', '--input', help='Path", "= datetime.datetime.now(tz=datetime.timezone.utc) repo_info = RepoInfo( 'mock repo path', 'mock repo name', 'mock repo", "open(file_path, 'rb') as f: graphs = pickle.load(f) for graph in graphs: change_graphs.append(pickle.loads(graph)) except:", "type=str, required=True) parser.add_argument('-d', '--dest', help='Path to source code after changes', type=str, required=True) parser.add_argument('-o',", "show_dependencies=args.show_deps, build_closure=not args.no_closure) pyflowgraph.export_graph_image( fg, args.output, show_op_kinds=not args.hide_op_kinds, show_data_keys=args.show_data_keys) elif current_mode == RunModes.BUILD_CHANGE_GRAPH:", "changegraph.build_from_files(args.src, args.dest) changegraph.export_graph_image(fg, args.output) elif current_mode == RunModes.COLLECT_CHANGE_GRAPHS: GitAnalyzer().build_change_graphs() elif current_mode == RunModes.MINE_PATTERNS:", "Pattern from vcs.traverse import GitAnalyzer, RepoInfo, Method import pyflowgraph import changegraph import settings", "url', 'mock hash', mock_commit_dtm, 'mock old file path', 'mock new file path', methods[0],", "app_name='CodeChangesMiner', debug=True, app_version=str(datetime.datetime.now()) ) sys.setrecursionlimit(2**31-1) multiprocessing.set_start_method('spawn', force=True) parser = argparse.ArgumentParser() parser.add_argument('mode', help=f'One of", "different size or unset') change_graphs = [] for old_path, new_path in zip(args.src, args.dest):", "_ = stackimpact.start( agent_key=settings.get('stackimpact_agent_key'), app_name='CodeChangesMiner', debug=True, app_version=str(datetime.datetime.now()) ) sys.setrecursionlimit(2**31-1) multiprocessing.set_start_method('spawn', force=True) parser =", "RunModes.BUILD_PY_FLOW_GRAPH: parser.add_argument('-i', '--input', help='Path to source code file', type=str, required=True) parser.add_argument('-o', '--output', help='Path", "has started') miner = Miner() try: miner.mine_patterns(change_graphs) except KeyboardInterrupt: logger.warning('KeyboardInterrupt: mined patterns will", "= 'collect-cgs' MINE_PATTERNS = 'patterns' ALL = [BUILD_PY_FLOW_GRAPH, BUILD_CHANGE_GRAPH, COLLECT_CHANGE_GRAPHS, MINE_PATTERNS] def main():", "args.dest) changegraph.export_graph_image(fg, args.output) elif current_mode == RunModes.COLLECT_CHANGE_GRAPHS: GitAnalyzer().build_change_graphs() elif current_mode == RunModes.MINE_PATTERNS: parser.add_argument('-s',", "1000 == 0: logger.warning(f'Loaded [{1+file_num}/{len(file_names)}] files') logger.warning('Pattern mining has started') miner = Miner()", "import argparse import multiprocessing from log import logger from patterns import Miner from", "parser.add_argument('-d', '--dest', help='Path to source code after changes', type=str, nargs='+') parser.add_argument('--fake-mining', action='store_true') args", "logger.warning(f'Incorrect file {file_path}') if file_num % 1000 == 0: logger.warning(f'Loaded [{1+file_num}/{len(file_names)}] files') logger.warning('Pattern", "datetime.datetime.now(tz=datetime.timezone.utc) repo_info = RepoInfo( 'mock repo path', 'mock repo name', 'mock repo url',", "mining has started') miner = Miner() try: miner.mine_patterns(change_graphs) except KeyboardInterrupt: logger.warning('KeyboardInterrupt: mined patterns", "default='pyflowgraph.dot') parser.add_argument('--no-closure', action='store_true') parser.add_argument('--show-deps', action='store_true') parser.add_argument('--hide-op-kinds', action='store_true') parser.add_argument('--show-data-keys', action='store_true') args = parser.parse_args() fg", "help='Path to source code after changes', type=str, nargs='+') parser.add_argument('--fake-mining', action='store_true') args = parser.parse_args()", "import pyflowgraph import changegraph import settings class RunModes: BUILD_PY_FLOW_GRAPH = 'pfg' BUILD_CHANGE_GRAPH =", "parser.add_argument('--hide-op-kinds', action='store_true') parser.add_argument('--show-data-keys', action='store_true') args = parser.parse_args() fg = pyflowgraph.build_from_file( args.input, show_dependencies=args.show_deps, build_closure=not", "as f: src = f.read() methods.append(Method(path, 'test_name', ast.parse(src, mode='exec').body[0], src)) mock_commit_dtm = datetime.datetime.now(tz=datetime.timezone.utc)", "args = parser.parse_args() fg = pyflowgraph.build_from_file( args.input, show_dependencies=args.show_deps, build_closure=not args.no_closure) pyflowgraph.export_graph_image( fg, args.output,", "repo name', 'mock repo url', 'mock hash', mock_commit_dtm, 'mock old file path', 'mock", "import ast import os import pickle import sys import stackimpact import datetime import", "graphs: change_graphs.append(pickle.loads(graph)) except: logger.warning(f'Incorrect file {file_path}') if file_num % 1000 == 0: logger.warning(f'Loaded", "help='Path to source code after changes', type=str, required=True) parser.add_argument('-o', '--output', help='Path to output", "'mock repo name', 'mock repo url', 'mock hash', mock_commit_dtm, 'mock old file path',", "required=True) parser.add_argument('-o', '--output', help='Path to output file', type=str, default='pyflowgraph.dot') parser.add_argument('--no-closure', action='store_true') parser.add_argument('--show-deps', action='store_true')", "type=str, default='pyflowgraph.dot') parser.add_argument('--no-closure', action='store_true') parser.add_argument('--show-deps', action='store_true') parser.add_argument('--hide-op-kinds', action='store_true') parser.add_argument('--show-data-keys', action='store_true') args = parser.parse_args()", "code before changes', type=str, required=True) parser.add_argument('-d', '--dest', help='Path to source code after changes',", "os.path.join(storage_dir, file_name) try: with open(file_path, 'rb') as f: graphs = pickle.load(f) for graph", "Pattern([fragment]) miner.add_pattern(pattern) else: miner.mine_patterns(change_graphs) miner.print_patterns() else: storage_dir = settings.get('change_graphs_storage_dir') file_names = os.listdir(storage_dir) logger.warning(f'Found", "= [] for file_num, file_name in enumerate(file_names): file_path = os.path.join(storage_dir, file_name) try: with", "sys import stackimpact import datetime import argparse import multiprocessing from log import logger", "'rb') as f: graphs = pickle.load(f) for graph in graphs: change_graphs.append(pickle.loads(graph)) except: logger.warning(f'Incorrect", "file_num % 1000 == 0: logger.warning(f'Loaded [{1+file_num}/{len(file_names)}] files') logger.warning('Pattern mining has started') miner", "type=str, default='changegraph.dot') args = parser.parse_args() fg = changegraph.build_from_files(args.src, args.dest) changegraph.export_graph_image(fg, args.output) elif current_mode", "args.output) elif current_mode == RunModes.COLLECT_CHANGE_GRAPHS: GitAnalyzer().build_change_graphs() elif current_mode == RunModes.MINE_PATTERNS: parser.add_argument('-s', '--src', help='Path", "new_path in zip(args.src, args.dest): methods = [] for n, path in enumerate([old_path, new_path]):", "show_data_keys=args.show_data_keys) elif current_mode == RunModes.BUILD_CHANGE_GRAPH: parser.add_argument('-s', '--src', help='Path to source code before changes',", "show_op_kinds=not args.hide_op_kinds, show_data_keys=args.show_data_keys) elif current_mode == RunModes.BUILD_CHANGE_GRAPH: parser.add_argument('-s', '--src', help='Path to source code", "file_num, file_name in enumerate(file_names): file_path = os.path.join(storage_dir, file_name) try: with open(file_path, 'rb') as", "pickle.load(f) for graph in graphs: change_graphs.append(pickle.loads(graph)) except: logger.warning(f'Incorrect file {file_path}') if file_num %", "as f: graphs = pickle.load(f) for graph in graphs: change_graphs.append(pickle.loads(graph)) except: logger.warning(f'Incorrect file", "after changes', type=str, required=True) parser.add_argument('-o', '--output', help='Path to output file', type=str, default='changegraph.dot') args", "enumerate([old_path, new_path]): with open(path, 'r+') as f: src = f.read() methods.append(Method(path, 'test_name', ast.parse(src,", "= parser.parse_args() if args.src or args.dest or args.fake_mining: if not args.src or len(args.src)", "before changes', type=str, required=True) parser.add_argument('-d', '--dest', help='Path to source code after changes', type=str,", "from log import logger from patterns import Miner from patterns.models import Fragment, Pattern", "f: src = f.read() methods.append(Method(path, 'test_name', ast.parse(src, mode='exec').body[0], src)) mock_commit_dtm = datetime.datetime.now(tz=datetime.timezone.utc) repo_info", "'mock repo url', 'mock hash', mock_commit_dtm, 'mock old file path', 'mock new file", "multiprocessing.set_start_method('spawn', force=True) parser = argparse.ArgumentParser() parser.add_argument('mode', help=f'One of {RunModes.ALL}', type=str) args, _ =", "[{1+file_num}/{len(file_names)}] files') logger.warning('Pattern mining has started') miner = Miner() try: miner.mine_patterns(change_graphs) except KeyboardInterrupt:", "= Fragment() fragment.graph = cg fragment.nodes = cg.nodes pattern = Pattern([fragment]) miner.add_pattern(pattern) else:", "cg.nodes pattern = Pattern([fragment]) miner.add_pattern(pattern) else: miner.mine_patterns(change_graphs) miner.print_patterns() else: storage_dir = settings.get('change_graphs_storage_dir') file_names", "args = parser.parse_args() if args.src or args.dest or args.fake_mining: if not args.src or", "f: graphs = pickle.load(f) for graph in graphs: change_graphs.append(pickle.loads(graph)) except: logger.warning(f'Incorrect file {file_path}')", "help=f'One of {RunModes.ALL}', type=str) args, _ = parser.parse_known_args() current_mode = args.mode if current_mode", "RunModes.COLLECT_CHANGE_GRAPHS: GitAnalyzer().build_change_graphs() elif current_mode == RunModes.MINE_PATTERNS: parser.add_argument('-s', '--src', help='Path to source code before", "parser.add_argument('-d', '--dest', help='Path to source code after changes', type=str, required=True) parser.add_argument('-o', '--output', help='Path", "action='store_true') args = parser.parse_args() fg = pyflowgraph.build_from_file( args.input, show_dependencies=args.show_deps, build_closure=not args.no_closure) pyflowgraph.export_graph_image( fg,", "file path', methods[0], methods[1]) cg = changegraph.build_from_files(old_path, new_path, repo_info=repo_info) change_graphs.append(cg) miner = Miner()", "with open(file_path, 'rb') as f: graphs = pickle.load(f) for graph in graphs: change_graphs.append(pickle.loads(graph))", "parser.add_argument('--fake-mining', action='store_true') args = parser.parse_args() if args.src or args.dest or args.fake_mining: if not", "= settings.get('change_graphs_storage_dir') file_names = os.listdir(storage_dir) logger.warning(f'Found {len(file_names)} files in storage directory') change_graphs =", "= changegraph.build_from_files(args.src, args.dest) changegraph.export_graph_image(fg, args.output) elif current_mode == RunModes.COLLECT_CHANGE_GRAPHS: GitAnalyzer().build_change_graphs() elif current_mode ==", "BUILD_CHANGE_GRAPH, COLLECT_CHANGE_GRAPHS, MINE_PATTERNS] def main(): logger.info('------------------------------ Starting ------------------------------') if settings.get('use_stackimpact', required=False): _ =", "'mock hash', mock_commit_dtm, 'mock old file path', 'mock new file path', methods[0], methods[1])", "n, path in enumerate([old_path, new_path]): with open(path, 'r+') as f: src = f.read()", "settings class RunModes: BUILD_PY_FLOW_GRAPH = 'pfg' BUILD_CHANGE_GRAPH = 'cg' COLLECT_CHANGE_GRAPHS = 'collect-cgs' MINE_PATTERNS", "except: logger.warning(f'Incorrect file {file_path}') if file_num % 1000 == 0: logger.warning(f'Loaded [{1+file_num}/{len(file_names)}] files')", "== RunModes.BUILD_PY_FLOW_GRAPH: parser.add_argument('-i', '--input', help='Path to source code file', type=str, required=True) parser.add_argument('-o', '--output',", "action='store_true') args = parser.parse_args() if args.src or args.dest or args.fake_mining: if not args.src", "= argparse.ArgumentParser() parser.add_argument('mode', help=f'One of {RunModes.ALL}', type=str) args, _ = parser.parse_known_args() current_mode =", "of {RunModes.ALL}', type=str) args, _ = parser.parse_known_args() current_mode = args.mode if current_mode ==", "'mock old file path', 'mock new file path', methods[0], methods[1]) cg = changegraph.build_from_files(old_path,", "file', type=str, required=True) parser.add_argument('-o', '--output', help='Path to output file', type=str, default='pyflowgraph.dot') parser.add_argument('--no-closure', action='store_true')", "= changegraph.build_from_files(old_path, new_path, repo_info=repo_info) change_graphs.append(cg) miner = Miner() if args.fake_mining: for cg in", "GitAnalyzer().build_change_graphs() elif current_mode == RunModes.MINE_PATTERNS: parser.add_argument('-s', '--src', help='Path to source code before changes',", "'--output', help='Path to output file', type=str, default='changegraph.dot') args = parser.parse_args() fg = changegraph.build_from_files(args.src,", "code after changes', type=str, nargs='+') parser.add_argument('--fake-mining', action='store_true') args = parser.parse_args() if args.src or", "log import logger from patterns import Miner from patterns.models import Fragment, Pattern from", "source code after changes', type=str, required=True) parser.add_argument('-o', '--output', help='Path to output file', type=str,", "= [] for old_path, new_path in zip(args.src, args.dest): methods = [] for n,", "parser.add_argument('-i', '--input', help='Path to source code file', type=str, required=True) parser.add_argument('-o', '--output', help='Path to", "for cg in change_graphs: fragment = Fragment() fragment.graph = cg fragment.nodes = cg.nodes", "file {file_path}') if file_num % 1000 == 0: logger.warning(f'Loaded [{1+file_num}/{len(file_names)}] files') logger.warning('Pattern mining", "RunModes.MINE_PATTERNS: parser.add_argument('-s', '--src', help='Path to source code before changes', type=str, nargs='+') parser.add_argument('-d', '--dest',", "src)) mock_commit_dtm = datetime.datetime.now(tz=datetime.timezone.utc) repo_info = RepoInfo( 'mock repo path', 'mock repo name',", "mode='exec').body[0], src)) mock_commit_dtm = datetime.datetime.now(tz=datetime.timezone.utc) repo_info = RepoInfo( 'mock repo path', 'mock repo", "type=str, nargs='+') parser.add_argument('-d', '--dest', help='Path to source code after changes', type=str, nargs='+') parser.add_argument('--fake-mining',", "to output file', type=str, default='pyflowgraph.dot') parser.add_argument('--no-closure', action='store_true') parser.add_argument('--show-deps', action='store_true') parser.add_argument('--hide-op-kinds', action='store_true') parser.add_argument('--show-data-keys', action='store_true')", "in zip(args.src, args.dest): methods = [] for n, path in enumerate([old_path, new_path]): with", "be stored before exit') miner.print_patterns() else: raise ValueError if __name__ == '__main__': main()", "'--input', help='Path to source code file', type=str, required=True) parser.add_argument('-o', '--output', help='Path to output", "miner = Miner() if args.fake_mining: for cg in change_graphs: fragment = Fragment() fragment.graph", "path', 'mock new file path', methods[0], methods[1]) cg = changegraph.build_from_files(old_path, new_path, repo_info=repo_info) change_graphs.append(cg)", "change_graphs.append(cg) miner = Miner() if args.fake_mining: for cg in change_graphs: fragment = Fragment()", "args.mode if current_mode == RunModes.BUILD_PY_FLOW_GRAPH: parser.add_argument('-i', '--input', help='Path to source code file', type=str,", "have different size or unset') change_graphs = [] for old_path, new_path in zip(args.src,", "= os.listdir(storage_dir) logger.warning(f'Found {len(file_names)} files in storage directory') change_graphs = [] for file_num,", "help='Path to output file', type=str, default='changegraph.dot') args = parser.parse_args() fg = changegraph.build_from_files(args.src, args.dest)", "parser.parse_args() fg = changegraph.build_from_files(args.src, args.dest) changegraph.export_graph_image(fg, args.output) elif current_mode == RunModes.COLLECT_CHANGE_GRAPHS: GitAnalyzer().build_change_graphs() elif", "logger.warning(f'Loaded [{1+file_num}/{len(file_names)}] files') logger.warning('Pattern mining has started') miner = Miner() try: miner.mine_patterns(change_graphs) except", "def main(): logger.info('------------------------------ Starting ------------------------------') if settings.get('use_stackimpact', required=False): _ = stackimpact.start( agent_key=settings.get('stackimpact_agent_key'), app_name='CodeChangesMiner',", "unset') change_graphs = [] for old_path, new_path in zip(args.src, args.dest): methods = []", "sys.setrecursionlimit(2**31-1) multiprocessing.set_start_method('spawn', force=True) parser = argparse.ArgumentParser() parser.add_argument('mode', help=f'One of {RunModes.ALL}', type=str) args, _", "file_names = os.listdir(storage_dir) logger.warning(f'Found {len(file_names)} files in storage directory') change_graphs = [] for", "help='Path to source code file', type=str, required=True) parser.add_argument('-o', '--output', help='Path to output file',", "KeyboardInterrupt: logger.warning('KeyboardInterrupt: mined patterns will be stored before exit') miner.print_patterns() else: raise ValueError", "try: miner.mine_patterns(change_graphs) except KeyboardInterrupt: logger.warning('KeyboardInterrupt: mined patterns will be stored before exit') miner.print_patterns()", "fg, args.output, show_op_kinds=not args.hide_op_kinds, show_data_keys=args.show_data_keys) elif current_mode == RunModes.BUILD_CHANGE_GRAPH: parser.add_argument('-s', '--src', help='Path to", "source code before changes', type=str, nargs='+') parser.add_argument('-d', '--dest', help='Path to source code after", "patterns import Miner from patterns.models import Fragment, Pattern from vcs.traverse import GitAnalyzer, RepoInfo,", "args.no_closure) pyflowgraph.export_graph_image( fg, args.output, show_op_kinds=not args.hide_op_kinds, show_data_keys=args.show_data_keys) elif current_mode == RunModes.BUILD_CHANGE_GRAPH: parser.add_argument('-s', '--src'," ]
[ "3: the car is behind door C: # p(open A): 0 # p(open", "doors.P(d.name) likelihood = d.P('B') print('{:^5} {:<12.5f} {:<12.5f} {:<12.5f} {:<12.5f}'.format(d.name, prior, likelihood, prior *", "behind door C: # p(open A): 0 # p(open B): 1 # p(open", "# p(open A): 0 # p(open B): 0 # p(open C): 1 hypo_2", "'P(H)*P(D|H)', 'P(H|D)')) for d in doors: prior = doors.P(d.name) likelihood = d.P('B') print('{:^5}", "_and_ there is no car there # H: # 1: the car is", "C): .5 hypo_1 = Distribution(name='1') hypo_1.update({'A': 0, 'B': 0.5, 'C': 0.5}) # 2:", "0 # p(open B): 0 # p(open C): 1 hypo_2 = Distribution(name='2') hypo_2.update({'A':", "1 hypo_2 = Distribution(name='2') hypo_2.update({'A': 0, 'B': 0, 'C': 1}) # 3: the", "d.P('B') print('{:^5} {:<12.5f} {:<12.5f} {:<12.5f} {:<12.5f}'.format(d.name, prior, likelihood, prior * likelihood, prior *", "A): 0 # p(open B): 0 # p(open C): 1 hypo_2 = Distribution(name='2')", "# 3: the car is behind door C: # p(open A): 0 #", "Distribution, DistGroup # Monty hall problem # you have chosen door A. Do", "'B': 0, 'C': 1}) # 3: the car is behind door C: #", "0 (we picked A) # p(open B): .5 # p(open C): .5 hypo_1", "'C': 0}) # Priors doors = DistGroup([hypo_1, hypo_2, hypo_3]) print('{:^5} {:<12} {:<12} {:<12}", ".5 # p(open C): .5 hypo_1 = Distribution(name='1') hypo_1.update({'A': 0, 'B': 0.5, 'C':", "B: # p(open A): 0 # p(open B): 0 # p(open C): 1", "DistGroup([hypo_1, hypo_2, hypo_3]) print('{:^5} {:<12} {:<12} {:<12} {:<12}'.format(' ', 'P(H)', 'P(D|H)', 'P(H)*P(D|H)', 'P(H|D)'))", "= DistGroup([hypo_1, hypo_2, hypo_3]) print('{:^5} {:<12} {:<12} {:<12} {:<12}'.format(' ', 'P(H)', 'P(D|H)', 'P(H)*P(D|H)',", "0 # p(open B): 1 # p(open C): 0 hypo_3 = Distribution(name='3') hypo_3.update({'A':", "p(open B): 0 # p(open C): 1 hypo_2 = Distribution(name='2') hypo_2.update({'A': 0, 'B':", "is behind door B: # p(open A): 0 # p(open B): 0 #", "opens door B _and_ there is no car there # H: # 1:", "behind door B: # p(open A): 0 # p(open B): 0 # p(open", "B _and_ there is no car there # H: # 1: the car", "{:<12} {:<12} {:<12} {:<12}'.format(' ', 'P(H)', 'P(D|H)', 'P(H)*P(D|H)', 'P(H|D)')) for d in doors:", "# p(open B): 0 # p(open C): 1 hypo_2 = Distribution(name='2') hypo_2.update({'A': 0,", "0, 'B': 0, 'C': 1}) # 3: the car is behind door C:", "0, 'B': 0.5, 'C': 0.5}) # 2: the car is behind door B:", "import Distribution, DistGroup # Monty hall problem # you have chosen door A.", "{:<12} {:<12}'.format(' ', 'P(H)', 'P(D|H)', 'P(H)*P(D|H)', 'P(H|D)')) for d in doors: prior =", "<filename>distribution/monty.py from distribution import Distribution, DistGroup # Monty hall problem # you have", "Monty hall problem # you have chosen door A. Do you switch to", "to win a car? # D: # Monty opens door B _and_ there", "A): 0 # p(open B): 1 # p(open C): 0 hypo_3 = Distribution(name='3')", "DistGroup # Monty hall problem # you have chosen door A. Do you", "the car is behind door C: # p(open A): 0 # p(open B):", "= Distribution(name='1') hypo_1.update({'A': 0, 'B': 0.5, 'C': 0.5}) # 2: the car is", "door A. Do you switch to win a car? # D: # Monty", "you switch to win a car? # D: # Monty opens door B", "p(open A): 0 # p(open B): 0 # p(open C): 1 hypo_2 =", "# Priors doors = DistGroup([hypo_1, hypo_2, hypo_3]) print('{:^5} {:<12} {:<12} {:<12} {:<12}'.format(' ',", "likelihood = d.P('B') print('{:^5} {:<12.5f} {:<12.5f} {:<12.5f} {:<12.5f}'.format(d.name, prior, likelihood, prior * likelihood,", ".5 hypo_1 = Distribution(name='1') hypo_1.update({'A': 0, 'B': 0.5, 'C': 0.5}) # 2: the", "in doors: prior = doors.P(d.name) likelihood = d.P('B') print('{:^5} {:<12.5f} {:<12.5f} {:<12.5f} {:<12.5f}'.format(d.name,", "{:<12.5f} {:<12.5f} {:<12.5f} {:<12.5f}'.format(d.name, prior, likelihood, prior * likelihood, prior * likelihood /", "'P(H)', 'P(D|H)', 'P(H)*P(D|H)', 'P(H|D)')) for d in doors: prior = doors.P(d.name) likelihood =", "# p(open A): 0 (we picked A) # p(open B): .5 # p(open", "a car? # D: # Monty opens door B _and_ there is no", "1: the car is behind door A: # p(open A): 0 (we picked", "A. Do you switch to win a car? # D: # Monty opens", "hypo_2 = Distribution(name='2') hypo_2.update({'A': 0, 'B': 0, 'C': 1}) # 3: the car", "p(open A): 0 # p(open B): 1 # p(open C): 0 hypo_3 =", "doors = DistGroup([hypo_1, hypo_2, hypo_3]) print('{:^5} {:<12} {:<12} {:<12} {:<12}'.format(' ', 'P(H)', 'P(D|H)',", "doors: prior = doors.P(d.name) likelihood = d.P('B') print('{:^5} {:<12.5f} {:<12.5f} {:<12.5f} {:<12.5f}'.format(d.name, prior,", "problem # you have chosen door A. Do you switch to win a", "1 # p(open C): 0 hypo_3 = Distribution(name='3') hypo_3.update({'A': 0, 'B': 1, 'C':", "behind door A: # p(open A): 0 (we picked A) # p(open B):", "A): 0 (we picked A) # p(open B): .5 # p(open C): .5", "p(open C): .5 hypo_1 = Distribution(name='1') hypo_1.update({'A': 0, 'B': 0.5, 'C': 0.5}) #", "', 'P(H)', 'P(D|H)', 'P(H)*P(D|H)', 'P(H|D)')) for d in doors: prior = doors.P(d.name) likelihood", "chosen door A. Do you switch to win a car? # D: #", "d in doors: prior = doors.P(d.name) likelihood = d.P('B') print('{:^5} {:<12.5f} {:<12.5f} {:<12.5f}", "B): 1 # p(open C): 0 hypo_3 = Distribution(name='3') hypo_3.update({'A': 0, 'B': 1,", "{:<12}'.format(' ', 'P(H)', 'P(D|H)', 'P(H)*P(D|H)', 'P(H|D)')) for d in doors: prior = doors.P(d.name)", "Distribution(name='2') hypo_2.update({'A': 0, 'B': 0, 'C': 1}) # 3: the car is behind", "# p(open C): .5 hypo_1 = Distribution(name='1') hypo_1.update({'A': 0, 'B': 0.5, 'C': 0.5})", "car is behind door B: # p(open A): 0 # p(open B): 0", "{:<12} {:<12} {:<12}'.format(' ', 'P(H)', 'P(D|H)', 'P(H)*P(D|H)', 'P(H|D)')) for d in doors: prior", "Distribution(name='1') hypo_1.update({'A': 0, 'B': 0.5, 'C': 0.5}) # 2: the car is behind", "= Distribution(name='2') hypo_2.update({'A': 0, 'B': 0, 'C': 1}) # 3: the car is", "# p(open B): .5 # p(open C): .5 hypo_1 = Distribution(name='1') hypo_1.update({'A': 0,", "# p(open C): 1 hypo_2 = Distribution(name='2') hypo_2.update({'A': 0, 'B': 0, 'C': 1})", "A: # p(open A): 0 (we picked A) # p(open B): .5 #", "picked A) # p(open B): .5 # p(open C): .5 hypo_1 = Distribution(name='1')", "A) # p(open B): .5 # p(open C): .5 hypo_1 = Distribution(name='1') hypo_1.update({'A':", "print('{:^5} {:<12} {:<12} {:<12} {:<12}'.format(' ', 'P(H)', 'P(D|H)', 'P(H)*P(D|H)', 'P(H|D)')) for d in", "'P(D|H)', 'P(H)*P(D|H)', 'P(H|D)')) for d in doors: prior = doors.P(d.name) likelihood = d.P('B')", "# p(open B): 1 # p(open C): 0 hypo_3 = Distribution(name='3') hypo_3.update({'A': 0,", "# you have chosen door A. Do you switch to win a car?", "'B': 0.5, 'C': 0.5}) # 2: the car is behind door B: #", "# D: # Monty opens door B _and_ there is no car there", "0, 'C': 1}) # 3: the car is behind door C: # p(open", "(we picked A) # p(open B): .5 # p(open C): .5 hypo_1 =", "0 # p(open C): 1 hypo_2 = Distribution(name='2') hypo_2.update({'A': 0, 'B': 0, 'C':", "p(open C): 0 hypo_3 = Distribution(name='3') hypo_3.update({'A': 0, 'B': 1, 'C': 0}) #", "print('{:^5} {:<12.5f} {:<12.5f} {:<12.5f} {:<12.5f}'.format(d.name, prior, likelihood, prior * likelihood, prior * likelihood", "= Distribution(name='3') hypo_3.update({'A': 0, 'B': 1, 'C': 0}) # Priors doors = DistGroup([hypo_1,", "hypo_2, hypo_3]) print('{:^5} {:<12} {:<12} {:<12} {:<12}'.format(' ', 'P(H)', 'P(D|H)', 'P(H)*P(D|H)', 'P(H|D)')) for", "for d in doors: prior = doors.P(d.name) likelihood = d.P('B') print('{:^5} {:<12.5f} {:<12.5f}", "2: the car is behind door B: # p(open A): 0 # p(open", "hypo_1 = Distribution(name='1') hypo_1.update({'A': 0, 'B': 0.5, 'C': 0.5}) # 2: the car", "the car is behind door B: # p(open A): 0 # p(open B):", "0.5, 'C': 0.5}) # 2: the car is behind door B: # p(open", "hall problem # you have chosen door A. Do you switch to win", "is no car there # H: # 1: the car is behind door", "0.5}) # 2: the car is behind door B: # p(open A): 0", "H: # 1: the car is behind door A: # p(open A): 0", "C): 0 hypo_3 = Distribution(name='3') hypo_3.update({'A': 0, 'B': 1, 'C': 0}) # Priors", "0}) # Priors doors = DistGroup([hypo_1, hypo_2, hypo_3]) print('{:^5} {:<12} {:<12} {:<12} {:<12}'.format('", "Do you switch to win a car? # D: # Monty opens door", "car is behind door C: # p(open A): 0 # p(open B): 1", "# p(open A): 0 # p(open B): 1 # p(open C): 0 hypo_3", "win a car? # D: # Monty opens door B _and_ there is", "hypo_3.update({'A': 0, 'B': 1, 'C': 0}) # Priors doors = DistGroup([hypo_1, hypo_2, hypo_3])", "prior = doors.P(d.name) likelihood = d.P('B') print('{:^5} {:<12.5f} {:<12.5f} {:<12.5f} {:<12.5f}'.format(d.name, prior, likelihood,", "distribution import Distribution, DistGroup # Monty hall problem # you have chosen door", "car there # H: # 1: the car is behind door A: #", "= doors.P(d.name) likelihood = d.P('B') print('{:^5} {:<12.5f} {:<12.5f} {:<12.5f} {:<12.5f}'.format(d.name, prior, likelihood, prior", "{:<12.5f} {:<12.5f} {:<12.5f}'.format(d.name, prior, likelihood, prior * likelihood, prior * likelihood / doors.normalizer('B')))", "p(open A): 0 (we picked A) # p(open B): .5 # p(open C):", "C: # p(open A): 0 # p(open B): 1 # p(open C): 0", "B): 0 # p(open C): 1 hypo_2 = Distribution(name='2') hypo_2.update({'A': 0, 'B': 0,", "Distribution(name='3') hypo_3.update({'A': 0, 'B': 1, 'C': 0}) # Priors doors = DistGroup([hypo_1, hypo_2,", "C): 1 hypo_2 = Distribution(name='2') hypo_2.update({'A': 0, 'B': 0, 'C': 1}) # 3:", "'B': 1, 'C': 0}) # Priors doors = DistGroup([hypo_1, hypo_2, hypo_3]) print('{:^5} {:<12}", "switch to win a car? # D: # Monty opens door B _and_", "Monty opens door B _and_ there is no car there # H: #", "1}) # 3: the car is behind door C: # p(open A): 0", "B): .5 # p(open C): .5 hypo_1 = Distribution(name='1') hypo_1.update({'A': 0, 'B': 0.5,", "Priors doors = DistGroup([hypo_1, hypo_2, hypo_3]) print('{:^5} {:<12} {:<12} {:<12} {:<12}'.format(' ', 'P(H)',", "= d.P('B') print('{:^5} {:<12.5f} {:<12.5f} {:<12.5f} {:<12.5f}'.format(d.name, prior, likelihood, prior * likelihood, prior", "p(open C): 1 hypo_2 = Distribution(name='2') hypo_2.update({'A': 0, 'B': 0, 'C': 1}) #", "# Monty hall problem # you have chosen door A. Do you switch", "door A: # p(open A): 0 (we picked A) # p(open B): .5", "hypo_3]) print('{:^5} {:<12} {:<12} {:<12} {:<12}'.format(' ', 'P(H)', 'P(D|H)', 'P(H)*P(D|H)', 'P(H|D)')) for d", "door C: # p(open A): 0 # p(open B): 1 # p(open C):", "'P(H|D)')) for d in doors: prior = doors.P(d.name) likelihood = d.P('B') print('{:^5} {:<12.5f}", "there # H: # 1: the car is behind door A: # p(open", "# 1: the car is behind door A: # p(open A): 0 (we", "the car is behind door A: # p(open A): 0 (we picked A)", "is behind door A: # p(open A): 0 (we picked A) # p(open", "you have chosen door A. Do you switch to win a car? #", "car is behind door A: # p(open A): 0 (we picked A) #", "have chosen door A. Do you switch to win a car? # D:", "door B _and_ there is no car there # H: # 1: the", "0 hypo_3 = Distribution(name='3') hypo_3.update({'A': 0, 'B': 1, 'C': 0}) # Priors doors", "from distribution import Distribution, DistGroup # Monty hall problem # you have chosen", "hypo_2.update({'A': 0, 'B': 0, 'C': 1}) # 3: the car is behind door", "1, 'C': 0}) # Priors doors = DistGroup([hypo_1, hypo_2, hypo_3]) print('{:^5} {:<12} {:<12}", "# 2: the car is behind door B: # p(open A): 0 #", "no car there # H: # 1: the car is behind door A:", "D: # Monty opens door B _and_ there is no car there #", "# H: # 1: the car is behind door A: # p(open A):", "there is no car there # H: # 1: the car is behind", "hypo_1.update({'A': 0, 'B': 0.5, 'C': 0.5}) # 2: the car is behind door", "# p(open C): 0 hypo_3 = Distribution(name='3') hypo_3.update({'A': 0, 'B': 1, 'C': 0})", "car? # D: # Monty opens door B _and_ there is no car", "door B: # p(open A): 0 # p(open B): 0 # p(open C):", "0, 'B': 1, 'C': 0}) # Priors doors = DistGroup([hypo_1, hypo_2, hypo_3]) print('{:^5}", "'C': 1}) # 3: the car is behind door C: # p(open A):", "is behind door C: # p(open A): 0 # p(open B): 1 #", "p(open B): .5 # p(open C): .5 hypo_1 = Distribution(name='1') hypo_1.update({'A': 0, 'B':", "'C': 0.5}) # 2: the car is behind door B: # p(open A):", "p(open B): 1 # p(open C): 0 hypo_3 = Distribution(name='3') hypo_3.update({'A': 0, 'B':", "# Monty opens door B _and_ there is no car there # H:", "hypo_3 = Distribution(name='3') hypo_3.update({'A': 0, 'B': 1, 'C': 0}) # Priors doors =" ]
[ "self.access_key = env('ia_access_key_id') self.secret_key = env('ia_secret_access_key') @property def bucket(self): if not hasattr(self, '_bucket'):", "is not None: key_name = os.path.join(self.prefix, key_name) log.info(\"Uploading [%s]: %s\", self.item, key_name) key", "archive on the internet archive. This is called when a scraper has generated", "is not None config = config and self.access_key is not None config =", "{} class InternetArchive(object): \"\"\"A scraper archive on the internet archive. This is called", "key is None: key = self.bucket.new_key(key_name) key.content_type = mime_type key.set_contents_from_filename(source_path, policy='public-read') return key.generate_url(84600,", "internet archive. This is called when a scraper has generated a file which", "datetime import datetime from morphium.util import env, TAG_LATEST log = logging.getLogger(__name__) config =", "self.prefix = prefix self.access_key = env('ia_access_key_id') self.secret_key = env('ia_secret_access_key') @property def bucket(self): if", "config and self.access_key is not None config = config and self.secret_key is not", "self.access_key is not None config = config and self.secret_key is not None if", "self._bucket def upload_file(self, source_path, file_name=None, mime_type=None): \"\"\"Upload a file to the given bucket.\"\"\"", "log.info(\"Uploading [%s]: %s\", self.item, key_name) key = self.bucket.get_key(key_name) if key is None: key", "config = config and self.secret_key is not None if not config: log.warning(\"No Internet", "logging.getLogger(__name__) config = {} class InternetArchive(object): \"\"\"A scraper archive on the internet archive.", "Archive config, skipping upload.\") self._client = None return None conn = boto.connect_s3(self.access_key, self.secret_key,", "None config = config and self.secret_key is not None if not config: log.warning(\"No", "def upload_file(self, source_path, file_name=None, mime_type=None): \"\"\"Upload a file to the given bucket.\"\"\" if", "which needs to be backed up to a bucket.\"\"\" def __init__(self, item=None, prefix=None):", "self.bucket.get_key(key_name) if key is None: key = self.bucket.new_key(key_name) key.content_type = mime_type key.set_contents_from_filename(source_path, policy='public-read')", "a scraper has generated a file which needs to be backed up to", "Internet Archive config, skipping upload.\") self._client = None return None conn = boto.connect_s3(self.access_key,", "import OrdinaryCallingFormat import mimetypes from datetime import datetime from morphium.util import env, TAG_LATEST", "in (date_name, copy_name): if self.prefix is not None: key_name = os.path.join(self.prefix, key_name) log.info(\"Uploading", "return if file_name is None: file_name = os.path.basename(source_path) if mime_type is None: mime_type,", "is not None config = config and self.secret_key is not None if not", "not hasattr(self, '_bucket'): config = self.item is not None config = config and", "conn = boto.connect_s3(self.access_key, self.secret_key, host='s3.us.archive.org', is_secure=False, calling_format=OrdinaryCallingFormat()) if not conn.lookup(self.item, validate=False): conn.create_bucket(self.item) self._bucket", "= conn.get_bucket(self.item) return self._bucket def upload_file(self, source_path, file_name=None, mime_type=None): \"\"\"Upload a file to", "calling_format=OrdinaryCallingFormat()) if not conn.lookup(self.item, validate=False): conn.create_bucket(self.item) self._bucket = conn.get_bucket(self.item) return self._bucket def upload_file(self,", "is None: file_name = os.path.basename(source_path) if mime_type is None: mime_type, _ = mimetypes.guess_type(file_name)", "= mimetypes.guess_type(file_name) mime_type = mime_type or 'application/octet-stream' date_name = os.path.join(self.tag, file_name) copy_name =", "import os import logging import boto from boto.s3.connection import OrdinaryCallingFormat import mimetypes from", "hasattr(self, '_bucket'): config = self.item is not None config = config and self.access_key", "not conn.lookup(self.item, validate=False): conn.create_bucket(self.item) self._bucket = conn.get_bucket(self.item) return self._bucket def upload_file(self, source_path, file_name=None,", "file_name = os.path.basename(source_path) if mime_type is None: mime_type, _ = mimetypes.guess_type(file_name) mime_type =", "is None: mime_type, _ = mimetypes.guess_type(file_name) mime_type = mime_type or 'application/octet-stream' date_name =", "import boto from boto.s3.connection import OrdinaryCallingFormat import mimetypes from datetime import datetime from", "scraper has generated a file which needs to be backed up to a", "This is called when a scraper has generated a file which needs to", "None return None conn = boto.connect_s3(self.access_key, self.secret_key, host='s3.us.archive.org', is_secure=False, calling_format=OrdinaryCallingFormat()) if not conn.lookup(self.item,", "a file which needs to be backed up to a bucket.\"\"\" def __init__(self,", "not None config = config and self.access_key is not None config = config", "log.warning(\"No Internet Archive config, skipping upload.\") self._client = None return None conn =", "datetime from morphium.util import env, TAG_LATEST log = logging.getLogger(__name__) config = {} class", "item or env('ia_item') self.prefix = prefix self.access_key = env('ia_access_key_id') self.secret_key = env('ia_secret_access_key') @property", "up to a bucket.\"\"\" def __init__(self, item=None, prefix=None): self.tag = datetime.utcnow().date().isoformat() self.item =", "prefix=None): self.tag = datetime.utcnow().date().isoformat() self.item = item or env('ia_item') self.prefix = prefix self.access_key", "= mime_type or 'application/octet-stream' date_name = os.path.join(self.tag, file_name) copy_name = os.path.join(TAG_LATEST, file_name) for", "if self.bucket is None: return if file_name is None: file_name = os.path.basename(source_path) if", "when a scraper has generated a file which needs to be backed up", "if not config: log.warning(\"No Internet Archive config, skipping upload.\") self._client = None return", "import logging import boto from boto.s3.connection import OrdinaryCallingFormat import mimetypes from datetime import", "return None conn = boto.connect_s3(self.access_key, self.secret_key, host='s3.us.archive.org', is_secure=False, calling_format=OrdinaryCallingFormat()) if not conn.lookup(self.item, validate=False):", "validate=False): conn.create_bucket(self.item) self._bucket = conn.get_bucket(self.item) return self._bucket def upload_file(self, source_path, file_name=None, mime_type=None): \"\"\"Upload", "or env('ia_item') self.prefix = prefix self.access_key = env('ia_access_key_id') self.secret_key = env('ia_secret_access_key') @property def", "config: log.warning(\"No Internet Archive config, skipping upload.\") self._client = None return None conn", "None: return if file_name is None: file_name = os.path.basename(source_path) if mime_type is None:", "skipping upload.\") self._client = None return None conn = boto.connect_s3(self.access_key, self.secret_key, host='s3.us.archive.org', is_secure=False,", "key = self.bucket.get_key(key_name) if key is None: key = self.bucket.new_key(key_name) key.content_type = mime_type", "os.path.join(self.tag, file_name) copy_name = os.path.join(TAG_LATEST, file_name) for key_name in (date_name, copy_name): if self.prefix", "if not conn.lookup(self.item, validate=False): conn.create_bucket(self.item) self._bucket = conn.get_bucket(self.item) return self._bucket def upload_file(self, source_path,", "log = logging.getLogger(__name__) config = {} class InternetArchive(object): \"\"\"A scraper archive on the", "[%s]: %s\", self.item, key_name) key = self.bucket.get_key(key_name) if key is None: key =", "self._client = None return None conn = boto.connect_s3(self.access_key, self.secret_key, host='s3.us.archive.org', is_secure=False, calling_format=OrdinaryCallingFormat()) if", "def bucket(self): if not hasattr(self, '_bucket'): config = self.item is not None config", "self.secret_key is not None if not config: log.warning(\"No Internet Archive config, skipping upload.\")", "config, skipping upload.\") self._client = None return None conn = boto.connect_s3(self.access_key, self.secret_key, host='s3.us.archive.org',", "mime_type or 'application/octet-stream' date_name = os.path.join(self.tag, file_name) copy_name = os.path.join(TAG_LATEST, file_name) for key_name", "is None: key = self.bucket.new_key(key_name) key.content_type = mime_type key.set_contents_from_filename(source_path, policy='public-read') return key.generate_url(84600, query_auth=False)", "backed up to a bucket.\"\"\" def __init__(self, item=None, prefix=None): self.tag = datetime.utcnow().date().isoformat() self.item", "conn.get_bucket(self.item) return self._bucket def upload_file(self, source_path, file_name=None, mime_type=None): \"\"\"Upload a file to the", "_ = mimetypes.guess_type(file_name) mime_type = mime_type or 'application/octet-stream' date_name = os.path.join(self.tag, file_name) copy_name", "upload_file(self, source_path, file_name=None, mime_type=None): \"\"\"Upload a file to the given bucket.\"\"\" if self.bucket", "config and self.secret_key is not None if not config: log.warning(\"No Internet Archive config,", "the internet archive. This is called when a scraper has generated a file", "config = config and self.access_key is not None config = config and self.secret_key", "self.item, key_name) key = self.bucket.get_key(key_name) if key is None: key = self.bucket.new_key(key_name) key.content_type", "(date_name, copy_name): if self.prefix is not None: key_name = os.path.join(self.prefix, key_name) log.info(\"Uploading [%s]:", "None: mime_type, _ = mimetypes.guess_type(file_name) mime_type = mime_type or 'application/octet-stream' date_name = os.path.join(self.tag,", "return self._bucket def upload_file(self, source_path, file_name=None, mime_type=None): \"\"\"Upload a file to the given", "= item or env('ia_item') self.prefix = prefix self.access_key = env('ia_access_key_id') self.secret_key = env('ia_secret_access_key')", "key_name = os.path.join(self.prefix, key_name) log.info(\"Uploading [%s]: %s\", self.item, key_name) key = self.bucket.get_key(key_name) if", "file_name=None, mime_type=None): \"\"\"Upload a file to the given bucket.\"\"\" if self.bucket is None:", "boto from boto.s3.connection import OrdinaryCallingFormat import mimetypes from datetime import datetime from morphium.util", "bucket.\"\"\" if self.bucket is None: return if file_name is None: file_name = os.path.basename(source_path)", "scraper archive on the internet archive. This is called when a scraper has", "<reponame>pudo/morphium import os import logging import boto from boto.s3.connection import OrdinaryCallingFormat import mimetypes", "= env('ia_secret_access_key') @property def bucket(self): if not hasattr(self, '_bucket'): config = self.item is", "= datetime.utcnow().date().isoformat() self.item = item or env('ia_item') self.prefix = prefix self.access_key = env('ia_access_key_id')", "self._bucket = conn.get_bucket(self.item) return self._bucket def upload_file(self, source_path, file_name=None, mime_type=None): \"\"\"Upload a file", "None conn = boto.connect_s3(self.access_key, self.secret_key, host='s3.us.archive.org', is_secure=False, calling_format=OrdinaryCallingFormat()) if not conn.lookup(self.item, validate=False): conn.create_bucket(self.item)", "datetime.utcnow().date().isoformat() self.item = item or env('ia_item') self.prefix = prefix self.access_key = env('ia_access_key_id') self.secret_key", "not None config = config and self.secret_key is not None if not config:", "None if not config: log.warning(\"No Internet Archive config, skipping upload.\") self._client = None", "file to the given bucket.\"\"\" if self.bucket is None: return if file_name is", "self.prefix is not None: key_name = os.path.join(self.prefix, key_name) log.info(\"Uploading [%s]: %s\", self.item, key_name)", "not None: key_name = os.path.join(self.prefix, key_name) log.info(\"Uploading [%s]: %s\", self.item, key_name) key =", "os import logging import boto from boto.s3.connection import OrdinaryCallingFormat import mimetypes from datetime", "if self.prefix is not None: key_name = os.path.join(self.prefix, key_name) log.info(\"Uploading [%s]: %s\", self.item,", "TAG_LATEST log = logging.getLogger(__name__) config = {} class InternetArchive(object): \"\"\"A scraper archive on", "= env('ia_access_key_id') self.secret_key = env('ia_secret_access_key') @property def bucket(self): if not hasattr(self, '_bucket'): config", "be backed up to a bucket.\"\"\" def __init__(self, item=None, prefix=None): self.tag = datetime.utcnow().date().isoformat()", "@property def bucket(self): if not hasattr(self, '_bucket'): config = self.item is not None", "def __init__(self, item=None, prefix=None): self.tag = datetime.utcnow().date().isoformat() self.item = item or env('ia_item') self.prefix", "__init__(self, item=None, prefix=None): self.tag = datetime.utcnow().date().isoformat() self.item = item or env('ia_item') self.prefix =", "bucket.\"\"\" def __init__(self, item=None, prefix=None): self.tag = datetime.utcnow().date().isoformat() self.item = item or env('ia_item')", "= config and self.access_key is not None config = config and self.secret_key is", "env, TAG_LATEST log = logging.getLogger(__name__) config = {} class InternetArchive(object): \"\"\"A scraper archive", "a file to the given bucket.\"\"\" if self.bucket is None: return if file_name", "None: file_name = os.path.basename(source_path) if mime_type is None: mime_type, _ = mimetypes.guess_type(file_name) mime_type", "if key is None: key = self.bucket.new_key(key_name) key.content_type = mime_type key.set_contents_from_filename(source_path, policy='public-read') return", "import datetime from morphium.util import env, TAG_LATEST log = logging.getLogger(__name__) config = {}", "needs to be backed up to a bucket.\"\"\" def __init__(self, item=None, prefix=None): self.tag", "= None return None conn = boto.connect_s3(self.access_key, self.secret_key, host='s3.us.archive.org', is_secure=False, calling_format=OrdinaryCallingFormat()) if not", "OrdinaryCallingFormat import mimetypes from datetime import datetime from morphium.util import env, TAG_LATEST log", "the given bucket.\"\"\" if self.bucket is None: return if file_name is None: file_name", "= os.path.join(TAG_LATEST, file_name) for key_name in (date_name, copy_name): if self.prefix is not None:", "if not hasattr(self, '_bucket'): config = self.item is not None config = config", "to the given bucket.\"\"\" if self.bucket is None: return if file_name is None:", "archive. This is called when a scraper has generated a file which needs", "env('ia_item') self.prefix = prefix self.access_key = env('ia_access_key_id') self.secret_key = env('ia_secret_access_key') @property def bucket(self):", "copy_name = os.path.join(TAG_LATEST, file_name) for key_name in (date_name, copy_name): if self.prefix is not", "env('ia_secret_access_key') @property def bucket(self): if not hasattr(self, '_bucket'): config = self.item is not", "import mimetypes from datetime import datetime from morphium.util import env, TAG_LATEST log =", "or 'application/octet-stream' date_name = os.path.join(self.tag, file_name) copy_name = os.path.join(TAG_LATEST, file_name) for key_name in", "file_name) for key_name in (date_name, copy_name): if self.prefix is not None: key_name =", "file which needs to be backed up to a bucket.\"\"\" def __init__(self, item=None,", "class InternetArchive(object): \"\"\"A scraper archive on the internet archive. This is called when", "and self.access_key is not None config = config and self.secret_key is not None", "self.tag = datetime.utcnow().date().isoformat() self.item = item or env('ia_item') self.prefix = prefix self.access_key =", "and self.secret_key is not None if not config: log.warning(\"No Internet Archive config, skipping", "from morphium.util import env, TAG_LATEST log = logging.getLogger(__name__) config = {} class InternetArchive(object):", "env('ia_access_key_id') self.secret_key = env('ia_secret_access_key') @property def bucket(self): if not hasattr(self, '_bucket'): config =", "%s\", self.item, key_name) key = self.bucket.get_key(key_name) if key is None: key = self.bucket.new_key(key_name)", "file_name is None: file_name = os.path.basename(source_path) if mime_type is None: mime_type, _ =", "= {} class InternetArchive(object): \"\"\"A scraper archive on the internet archive. This is", "item=None, prefix=None): self.tag = datetime.utcnow().date().isoformat() self.item = item or env('ia_item') self.prefix = prefix", "self.item = item or env('ia_item') self.prefix = prefix self.access_key = env('ia_access_key_id') self.secret_key =", "config = {} class InternetArchive(object): \"\"\"A scraper archive on the internet archive. This", "'_bucket'): config = self.item is not None config = config and self.access_key is", "conn.lookup(self.item, validate=False): conn.create_bucket(self.item) self._bucket = conn.get_bucket(self.item) return self._bucket def upload_file(self, source_path, file_name=None, mime_type=None):", "mime_type=None): \"\"\"Upload a file to the given bucket.\"\"\" if self.bucket is None: return", "boto.connect_s3(self.access_key, self.secret_key, host='s3.us.archive.org', is_secure=False, calling_format=OrdinaryCallingFormat()) if not conn.lookup(self.item, validate=False): conn.create_bucket(self.item) self._bucket = conn.get_bucket(self.item)", "upload.\") self._client = None return None conn = boto.connect_s3(self.access_key, self.secret_key, host='s3.us.archive.org', is_secure=False, calling_format=OrdinaryCallingFormat())", "copy_name): if self.prefix is not None: key_name = os.path.join(self.prefix, key_name) log.info(\"Uploading [%s]: %s\",", "generated a file which needs to be backed up to a bucket.\"\"\" def", "= os.path.join(self.prefix, key_name) log.info(\"Uploading [%s]: %s\", self.item, key_name) key = self.bucket.get_key(key_name) if key", "self.secret_key, host='s3.us.archive.org', is_secure=False, calling_format=OrdinaryCallingFormat()) if not conn.lookup(self.item, validate=False): conn.create_bucket(self.item) self._bucket = conn.get_bucket(self.item) return", "= config and self.secret_key is not None if not config: log.warning(\"No Internet Archive", "import env, TAG_LATEST log = logging.getLogger(__name__) config = {} class InternetArchive(object): \"\"\"A scraper", "= self.item is not None config = config and self.access_key is not None", "if file_name is None: file_name = os.path.basename(source_path) if mime_type is None: mime_type, _", "boto.s3.connection import OrdinaryCallingFormat import mimetypes from datetime import datetime from morphium.util import env,", "None config = config and self.access_key is not None config = config and", "given bucket.\"\"\" if self.bucket is None: return if file_name is None: file_name =", "os.path.join(TAG_LATEST, file_name) for key_name in (date_name, copy_name): if self.prefix is not None: key_name", "= boto.connect_s3(self.access_key, self.secret_key, host='s3.us.archive.org', is_secure=False, calling_format=OrdinaryCallingFormat()) if not conn.lookup(self.item, validate=False): conn.create_bucket(self.item) self._bucket =", "self.bucket is None: return if file_name is None: file_name = os.path.basename(source_path) if mime_type", "os.path.basename(source_path) if mime_type is None: mime_type, _ = mimetypes.guess_type(file_name) mime_type = mime_type or", "not config: log.warning(\"No Internet Archive config, skipping upload.\") self._client = None return None", "to a bucket.\"\"\" def __init__(self, item=None, prefix=None): self.tag = datetime.utcnow().date().isoformat() self.item = item", "conn.create_bucket(self.item) self._bucket = conn.get_bucket(self.item) return self._bucket def upload_file(self, source_path, file_name=None, mime_type=None): \"\"\"Upload a", "is_secure=False, calling_format=OrdinaryCallingFormat()) if not conn.lookup(self.item, validate=False): conn.create_bucket(self.item) self._bucket = conn.get_bucket(self.item) return self._bucket def", "is None: return if file_name is None: file_name = os.path.basename(source_path) if mime_type is", "= os.path.join(self.tag, file_name) copy_name = os.path.join(TAG_LATEST, file_name) for key_name in (date_name, copy_name): if", "is called when a scraper has generated a file which needs to be", "mime_type, _ = mimetypes.guess_type(file_name) mime_type = mime_type or 'application/octet-stream' date_name = os.path.join(self.tag, file_name)", "host='s3.us.archive.org', is_secure=False, calling_format=OrdinaryCallingFormat()) if not conn.lookup(self.item, validate=False): conn.create_bucket(self.item) self._bucket = conn.get_bucket(self.item) return self._bucket", "None: key_name = os.path.join(self.prefix, key_name) log.info(\"Uploading [%s]: %s\", self.item, key_name) key = self.bucket.get_key(key_name)", "= logging.getLogger(__name__) config = {} class InternetArchive(object): \"\"\"A scraper archive on the internet", "for key_name in (date_name, copy_name): if self.prefix is not None: key_name = os.path.join(self.prefix,", "not None if not config: log.warning(\"No Internet Archive config, skipping upload.\") self._client =", "os.path.join(self.prefix, key_name) log.info(\"Uploading [%s]: %s\", self.item, key_name) key = self.bucket.get_key(key_name) if key is", "self.item is not None config = config and self.access_key is not None config", "date_name = os.path.join(self.tag, file_name) copy_name = os.path.join(TAG_LATEST, file_name) for key_name in (date_name, copy_name):", "on the internet archive. This is called when a scraper has generated a", "'application/octet-stream' date_name = os.path.join(self.tag, file_name) copy_name = os.path.join(TAG_LATEST, file_name) for key_name in (date_name,", "self.secret_key = env('ia_secret_access_key') @property def bucket(self): if not hasattr(self, '_bucket'): config = self.item", "prefix self.access_key = env('ia_access_key_id') self.secret_key = env('ia_secret_access_key') @property def bucket(self): if not hasattr(self,", "= os.path.basename(source_path) if mime_type is None: mime_type, _ = mimetypes.guess_type(file_name) mime_type = mime_type", "morphium.util import env, TAG_LATEST log = logging.getLogger(__name__) config = {} class InternetArchive(object): \"\"\"A", "is not None if not config: log.warning(\"No Internet Archive config, skipping upload.\") self._client", "a bucket.\"\"\" def __init__(self, item=None, prefix=None): self.tag = datetime.utcnow().date().isoformat() self.item = item or", "bucket(self): if not hasattr(self, '_bucket'): config = self.item is not None config =", "from datetime import datetime from morphium.util import env, TAG_LATEST log = logging.getLogger(__name__) config", "has generated a file which needs to be backed up to a bucket.\"\"\"", "config = self.item is not None config = config and self.access_key is not", "mime_type is None: mime_type, _ = mimetypes.guess_type(file_name) mime_type = mime_type or 'application/octet-stream' date_name", "file_name) copy_name = os.path.join(TAG_LATEST, file_name) for key_name in (date_name, copy_name): if self.prefix is", "if mime_type is None: mime_type, _ = mimetypes.guess_type(file_name) mime_type = mime_type or 'application/octet-stream'", "to be backed up to a bucket.\"\"\" def __init__(self, item=None, prefix=None): self.tag =", "key_name in (date_name, copy_name): if self.prefix is not None: key_name = os.path.join(self.prefix, key_name)", "key_name) key = self.bucket.get_key(key_name) if key is None: key = self.bucket.new_key(key_name) key.content_type =", "source_path, file_name=None, mime_type=None): \"\"\"Upload a file to the given bucket.\"\"\" if self.bucket is", "= prefix self.access_key = env('ia_access_key_id') self.secret_key = env('ia_secret_access_key') @property def bucket(self): if not", "logging import boto from boto.s3.connection import OrdinaryCallingFormat import mimetypes from datetime import datetime", "from boto.s3.connection import OrdinaryCallingFormat import mimetypes from datetime import datetime from morphium.util import", "mime_type = mime_type or 'application/octet-stream' date_name = os.path.join(self.tag, file_name) copy_name = os.path.join(TAG_LATEST, file_name)", "= self.bucket.get_key(key_name) if key is None: key = self.bucket.new_key(key_name) key.content_type = mime_type key.set_contents_from_filename(source_path,", "mimetypes.guess_type(file_name) mime_type = mime_type or 'application/octet-stream' date_name = os.path.join(self.tag, file_name) copy_name = os.path.join(TAG_LATEST,", "called when a scraper has generated a file which needs to be backed", "InternetArchive(object): \"\"\"A scraper archive on the internet archive. This is called when a", "key_name) log.info(\"Uploading [%s]: %s\", self.item, key_name) key = self.bucket.get_key(key_name) if key is None:", "\"\"\"Upload a file to the given bucket.\"\"\" if self.bucket is None: return if", "mimetypes from datetime import datetime from morphium.util import env, TAG_LATEST log = logging.getLogger(__name__)", "\"\"\"A scraper archive on the internet archive. This is called when a scraper" ]
[ "saves the relevant daily # volume and adjusted closing prices from Yahoo Finance.", "please note that yahoo will return a different payload than expected if #", "re import csv import os from collections import defaultdict # read a csv", "items.append(items[0]) items.reverse() items.pop() # rename the header fields items[0] = re.sub(\"Date\", \"date\", items[0])", "payload = re.split(\"\\n\", read_decode(httpObj)) if payload: if payload[-1] == \"\": payload.pop() # workaround", "the results of a web request def req(url): try: return urllib.request.urlopen(url) except urllib.request.URLError", "from Yahoo Finance. # a logfile is also created to summarise the outcome", "created to summarise the outcome in terms of available data # please note", "try: fileObj.write(\"%s\\n\" % text) return True except: print(\"File error: could not write [%s]", "elements for i in range(len(items)): items[i] = re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\", \"\", items[i]) if reformDate: items[i]", "Close\", \"p\", items[0]) # determine if the date format requires reformatting reformDate =", "type=str, help=(\"The path to a machine-readable logfile.\")) argparser.add_argument(\"-s\", \"--startDate\", type=str, help=(\"Initial date sought", "a csv file and return dictionary objects def get_csv_dict(path): dictObjs = [] with", "return False else: try: os.makedirs(path) return True except FileExistsError as e: print(\"File Error", "s: d[k].append(v) return d # main section ========================================================= # start with parsing the", "symbol)), items=rPayload, mode=\"wt\") # get position of each tradingDate and write it to", "+ \"&ignore=.csv\") return url # cleanly return the results of a web request", "range(len(items)): items[i] = re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\", \"\", items[i]) if reformDate: items[i] = (\"%s-%s-%s%s\" % (items[i][6:10],", "url = (\"http://real-chart.finance.yahoo.com/table.csv\" + \"?s=\" + symbol + endDForm + \"&g=\" + frequency", "the start or end dates requested do not match global calendar dates, #", "split by comma, extract only the desired elements for i in range(len(items)): items[i]", "v in s: d[k].append(v) return d # main section ========================================================= # start with", "stock \" + \"price files are saved.\")) argparser.add_argument(\"log\", type=str, help=(\"The path to a", "= re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\", \"\", items[i]) if reformDate: items[i] = (\"%s-%s-%s%s\" % (items[i][6:10], items[i][3:5], items[i][0:2],", "dateInts = [int(d) for d in re.split(\"-\", end)] dateInts[1] -= 1 endDForm =", "and write it to logfile for tradingDate in rItems[symbol]: position = \"\" if", "for tradingDate in rItems[symbol]: position = \"\" if rPayload: pattern = re.compile(tradingDate) for", "read_decode(httpObj): body = httpObj.read() httpObj.close() try: return body.decode('utf-8') # required, but a bottleneck", "for legibility and remove irrelevant variables def reform_payload(items): # reversing the headed list", "start and end dates for range and saves the relevant daily # volume", "+ \"time series data, YYYY-MM-DD format\")) argparser.add_argument(\"-e\", \"--endDate\", type=str, help=(\"Final date sought for", "http object contents in usable format def read_decode(httpObj): body = httpObj.read() httpObj.close() try:", "of stock symbols # with optional start and end dates for range and", "of text to a file def writeln(path, text, mode=\"at\"): with open(path, mode) as", "fieldnames=header): dictObjs.append(line) return dictObjs # why not convert to a list of objects", "\\n on split nData = len(payload) - 1 # write the reformed payload", "rPayload = reform_payload(payload) write_items(path=(\"%s/%s.csv\" % (args.folder, symbol)), items=rPayload, mode=\"wt\") # get position of", "return True except FileExistsError as e: print(\"File Error [%s] with [%s]\" % (e,", "# please note that yahoo will return a different payload than expected if", "# main section ========================================================= # start with parsing the arguments argparser = argparse.ArgumentParser()", "list of stock symbols # with optional start and end dates for range", "for i in items: s.append((i['symbol'], i['tradingDate'])) d = defaultdict(list) for k, v in", "of interest, YYYY-MM-DD format\")) argparser.add_argument(\"folder\", type=str, help=(\"The path to a folder to which", "items en masse to a file def write_items(path, items, mode=\"at\"): with open(path, mode)", "urllib.request.URLError as e: print(\"HTTP Error [%s] with [%s]\" % (e.code, url)) # return", "type=str, help=(\"Initial date sought for the range of \" + \"time series data,", "re.split(\"-\", start)] dateInts[1] -= 1 startDForm = \"&c=%d&a=%d&b=%d\" % tuple(dateInts) else: startDForm =", "2015-06-31 # I leave it to the user to check for this. #", "payload httpObj = req(form_url(symbol=symbol, start=startDate, end=endDate)) if httpObj: # transform it to list", "httpObj: # transform it to list items and check the number of rows", "UnicodeDecodeError as e: print(\"Decode Error [%s]\" % e) # reform provided payload items", "# such as 2015-06-31 # I leave it to the user to check", "for d in re.split(\"-\", end)] dateInts[1] -= 1 endDForm = \"&f=%d&d=%d&e=%d\" % tuple(dateInts)", "the header fields items[0] = re.sub(\"Date\", \"date\", items[0]) items[0] = re.sub(\"Volume\", \"v\", items[0])", "re.split(\"\\n\", read_decode(httpObj)) if payload: if payload[-1] == \"\": payload.pop() # workaround for final", "0 payload = re.split(\"\\n\", read_decode(httpObj)) if payload: if payload[-1] == \"\": payload.pop() #", "format def read_decode(httpObj): body = httpObj.read() httpObj.close() try: return body.decode('utf-8') # required, but", "items=rPayload, mode=\"wt\") # get position of each tradingDate and write it to logfile", "argparse.ArgumentParser() argparser.add_argument(\"items\", type=str, help=(\"CSV format items of stock symbols \" + \"and dates", "line of text to a file def writeln(path, text, mode=\"at\"): with open(path, mode)", "[%s] will not be overwritten\" % path) return False else: try: os.makedirs(path) return", "start with parsing the arguments argparser = argparse.ArgumentParser() argparser.add_argument(\"items\", type=str, help=(\"CSV format items", "volume and adjusted closing prices from Yahoo Finance. # a logfile is also", "endDForm = \"&f=%d&d=%d&e=%d\" % tuple(dateInts) else: endDForm = \"\" url = (\"http://real-chart.finance.yahoo.com/table.csv\" +", "return body.decode('utf-8') # required, but a bottleneck except UnicodeDecodeError as e: print(\"Decode Error", "return dictionary objects def get_csv_dict(path): dictObjs = [] with open(path) as fileObj: #", "if pattern.match(rPayload[pos]): position = str(pos) # perhaps it might be quicker to make", "req(form_url(symbol=symbol, start=startDate, end=endDate)) if httpObj: # transform it to list items and check", "in re.split(\"-\", start)] dateInts[1] -= 1 startDForm = \"&c=%d&a=%d&b=%d\" % tuple(dateInts) else: startDForm", "quicker to make a list of the results # and use write_items instead?", "csv.reader(fileObj, delimiter=\",\", quotechar='\"').__next__() for line in csv.DictReader(fileObj, fieldnames=header): dictObjs.append(line) return dictObjs # why", "fileObj.close() # find unique items and preserve order. By <NAME> def unique(seq): seen", "# required, but a bottleneck except UnicodeDecodeError as e: print(\"Decode Error [%s]\" %", "write list items en masse to a file def write_items(path, items, mode=\"at\"): with", "append? # if it does not exist, it must be created def init_folder(path):", "= [] for i in items: s.append((i['symbol'], i['tradingDate'])) d = defaultdict(list) for k,", "section ========================================================= # start with parsing the arguments argparser = argparse.ArgumentParser() argparser.add_argument(\"items\", type=str,", "it must be created def init_folder(path): if os.path.exists(path): if os.path.isdir(path): return True else:", "remove irrelevant variables def reform_payload(items): # reversing the headed list into continual order", "# return the http object contents in usable format def read_decode(httpObj): body =", "= str(pos) # perhaps it might be quicker to make a list of", "%s\" % symbol) # get the raw payload httpObj = req(form_url(symbol=symbol, start=startDate, end=endDate))", "False else: try: os.makedirs(path) return True except FileExistsError as e: print(\"File Error [%s]", "and saves the relevant daily # volume and adjusted closing prices from Yahoo", "return [x for x in seq if x not in seen and not", "DESCRIPTION # An efficient python script that reads a line separated list of", "that yahoo will return a different payload than expected if # the start", "nested dictionary into (unique key), (value) pairs def reform_items(items): s = [] for", "+ \"price files are saved.\")) argparser.add_argument(\"log\", type=str, help=(\"The path to a machine-readable logfile.\"))", "stock symbols # with optional start and end dates for range and saves", "help=(\"CSV format items of stock symbols \" + \"and dates of interest, YYYY-MM-DD", "folder to which stock \" + \"price files are saved.\")) argparser.add_argument(\"log\", type=str, help=(\"The", "mode) as fileObj: try: fileObj.write(\"%s\\n\" % text) return True except: print(\"File error: could", "items = get_csv_dict(args.items) initFolderSuccess = init_folder(args.folder) initLogSuccess = writeln(path=args.log, mode=\"wt\", text=\"symbol,tradingDate,position,datapoints\") startDate =", "collections import defaultdict # read a csv file and return dictionary objects def", "d[k].append(v) return d # main section ========================================================= # start with parsing the arguments", "uniqueSymbols = unique(list(i['symbol'] for i in items)) rItems = reform_items(items) for symbol in", "- 1 # write the reformed payload rPayload = reform_payload(payload) write_items(path=(\"%s/%s.csv\" % (args.folder,", "write [%s] to [%s]\" % (text, path)) return False finally: fileObj.close() # find", "en masse to a file def write_items(path, items, mode=\"at\"): with open(path, mode) as", "determine if the date format requires reformatting reformDate = True if (re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\", items[1]))", "for final \\n on split nData = len(payload) - 1 # write the", "user to check for this. # for usage, use -h import argparse import", "return True else: print(\"File [%s] will not be overwritten\" % path) return False", "extract only the desired elements for i in range(len(items)): items[i] = re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\", \"\",", "assuming the first line is a header header = csv.reader(fileObj, delimiter=\",\", quotechar='\"').__next__() for", "exist, it must be created def init_folder(path): if os.path.exists(path): if os.path.isdir(path): return True", "with open(path) as fileObj: # assuming the first line is a header header", "urllib.request import re import csv import os from collections import defaultdict # read", "with [%s]\" % (e.code, url)) # return the http object contents in usable", "writeln(path=args.log, mode=\"wt\", text=\"symbol,tradingDate,position,datapoints\") startDate = str(args.startDate) if args.startDate else \"\" endDate = str(args.endDate)", "each tradingDate and write it to logfile for tradingDate in rItems[symbol]: position =", "requested do not match global calendar dates, # such as 2015-06-31 # I", "not exist, it must be created def init_folder(path): if os.path.exists(path): if os.path.isdir(path): return", "try: os.makedirs(path) return True except FileExistsError as e: print(\"File Error [%s] with [%s]\"", "if payload: if payload[-1] == \"\": payload.pop() # workaround for final \\n on", "httpObj.close() try: return body.decode('utf-8') # required, but a bottleneck except UnicodeDecodeError as e:", "+ \"and dates of interest, YYYY-MM-DD format\")) argparser.add_argument(\"folder\", type=str, help=(\"The path to a", "for i in items: fileObj.write(\"%s\\n\" % i) finally: fileObj.close() # write a line", "be quicker to make a list of the results # and use write_items", "\"\", items[i]) if reformDate: items[i] = (\"%s-%s-%s%s\" % (items[i][6:10], items[i][3:5], items[i][0:2], items[i][10:])) return", "= len(payload) - 1 # write the reformed payload rPayload = reform_payload(payload) write_items(path=(\"%s/%s.csv\"", "% (e.code, url)) # return the http object contents in usable format def", "not be overwritten\" % path) return False else: try: os.makedirs(path) return True except", "to check for this. # for usage, use -h import argparse import urllib.request", "be overwritten\" % path) return False else: try: os.makedirs(path) return True except FileExistsError", "return the results of a web request def req(url): try: return urllib.request.urlopen(url) except", "than expected if # the start or end dates requested do not match", "[%s] with [%s]\" % (e.code, url)) # return the http object contents in", "for usage, use -h import argparse import urllib.request import re import csv import", "endDForm = \"\" url = (\"http://real-chart.finance.yahoo.com/table.csv\" + \"?s=\" + symbol + endDForm +", "range and saves the relevant daily # volume and adjusted closing prices from", "will return a different payload than expected if # the start or end", "return dictObjs # why not convert to a list of objects than create", "return urllib.request.urlopen(url) except urllib.request.URLError as e: print(\"HTTP Error [%s] with [%s]\" % (e.code,", "= (\"http://real-chart.finance.yahoo.com/table.csv\" + \"?s=\" + symbol + endDForm + \"&g=\" + frequency +", "startDForm = \"\" if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", end): dateInts = [int(d) for d in re.split(\"-\",", "re.sub(\"Adj Close\", \"p\", items[0]) # determine if the date format requires reformatting reformDate", "writeln(path, text, mode=\"at\"): with open(path, mode) as fileObj: try: fileObj.write(\"%s\\n\" % text) return", "Error [%s] with [%s]\" % (e, path)) return False # forming urls specifically", "with parsing the arguments argparser = argparse.ArgumentParser() argparser.add_argument(\"items\", type=str, help=(\"CSV format items of", "date format requires reformatting reformDate = True if (re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\", items[1])) else False #", "-= 1 startDForm = \"&c=%d&a=%d&b=%d\" % tuple(dateInts) else: startDForm = \"\" if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\",", "= re.sub(\"Date\", \"date\", items[0]) items[0] = re.sub(\"Volume\", \"v\", items[0]) items[0] = re.sub(\"Adj Close\",", "a list of the results # and use write_items instead? writeln(path=args.log, mode=\"at\", text=(\"%s,%s,%s,%s\"", "# write a line of text to a file def writeln(path, text, mode=\"at\"):", "By <NAME> def unique(seq): seen = set() return [x for x in seq", "provided payload items for legibility and remove irrelevant variables def reform_payload(items): # reversing", "= re.compile(tradingDate) for pos in range(len(rPayload)): if not position: if pattern.match(rPayload[pos]): position =", "mode) as fileObj: try: for i in items: fileObj.write(\"%s\\n\" % i) finally: fileObj.close()", "not seen.add(x)] # transform a nested dictionary into (unique key), (value) pairs def", "objects than create and append? # if it does not exist, it must", "of each tradingDate and write it to logfile for tradingDate in rItems[symbol]: position", "items # write list items en masse to a file def write_items(path, items,", "rItems[symbol]: position = \"\" if rPayload: pattern = re.compile(tradingDate) for pos in range(len(rPayload)):", "interest, YYYY-MM-DD format\")) argparser.add_argument(\"folder\", type=str, help=(\"The path to a folder to which stock", "date sought for the range of time \" + \"series data, YYYY-MM-DD format\"))", "leave blank if does not conform if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", start): dateInts = [int(d) for", "as e: print(\"Decode Error [%s]\" % e) # reform provided payload items for", "# determine if the date format requires reformatting reformDate = True if (re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\",", "if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", start): dateInts = [int(d) for d in re.split(\"-\", start)] dateInts[1] -=", "1 endDForm = \"&f=%d&d=%d&e=%d\" % tuple(dateInts) else: endDForm = \"\" url = (\"http://real-chart.finance.yahoo.com/table.csv\"", "seen = set() return [x for x in seq if x not in", "try: return body.decode('utf-8') # required, but a bottleneck except UnicodeDecodeError as e: print(\"Decode", "for symbol in uniqueSymbols: print(\"Accessing %s\" % symbol) # get the raw payload", "start=startDate, end=endDate)) if httpObj: # transform it to list items and check the", "format\")) args = argparser.parse_args() items = get_csv_dict(args.items) initFolderSuccess = init_folder(args.folder) initLogSuccess = writeln(path=args.log,", "= get_csv_dict(args.items) initFolderSuccess = init_folder(args.folder) initLogSuccess = writeln(path=args.log, mode=\"wt\", text=\"symbol,tradingDate,position,datapoints\") startDate = str(args.startDate)", "saved.\")) argparser.add_argument(\"log\", type=str, help=(\"The path to a machine-readable logfile.\")) argparser.add_argument(\"-s\", \"--startDate\", type=str, help=(\"Initial", "tuple(dateInts) else: endDForm = \"\" url = (\"http://real-chart.finance.yahoo.com/table.csv\" + \"?s=\" + symbol +", "perhaps it might be quicker to make a list of the results #", "end dates for range and saves the relevant daily # volume and adjusted", "i in items: fileObj.write(\"%s\\n\" % i) finally: fileObj.close() # write a line of", "path)) return False finally: fileObj.close() # find unique items and preserve order. By", "def unique(seq): seen = set() return [x for x in seq if x", "than create and append? # if it does not exist, it must be", "to a folder to which stock \" + \"price files are saved.\")) argparser.add_argument(\"log\",", "data, YYYY-MM-DD format\")) args = argparser.parse_args() items = get_csv_dict(args.items) initFolderSuccess = init_folder(args.folder) initLogSuccess", "= str(args.endDate) if args.endDate else \"\" if items and initFolderSuccess and initLogSuccess: uniqueSymbols", "if args.endDate else \"\" if items and initFolderSuccess and initLogSuccess: uniqueSymbols = unique(list(i['symbol']", "return the http object contents in usable format def read_decode(httpObj): body = httpObj.read()", "if not position: if pattern.match(rPayload[pos]): position = str(pos) # perhaps it might be", "format to string # or leave blank if does not conform if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\",", "= unique(list(i['symbol'] for i in items)) rItems = reform_items(items) for symbol in uniqueSymbols:", "create and append? # if it does not exist, it must be created", "except: print(\"File error: could not write [%s] to [%s]\" % (text, path)) return", "of available data # please note that yahoo will return a different payload", "as fileObj: try: for i in items: fileObj.write(\"%s\\n\" % i) finally: fileObj.close() #", "items[0]) # determine if the date format requires reformatting reformDate = True if", "# with optional start and end dates for range and saves the relevant", "\"&f=%d&d=%d&e=%d\" % tuple(dateInts) else: endDForm = \"\" url = (\"http://real-chart.finance.yahoo.com/table.csv\" + \"?s=\" +", "dateInts = [int(d) for d in re.split(\"-\", start)] dateInts[1] -= 1 startDForm =", "items and preserve order. By <NAME> def unique(seq): seen = set() return [x", "mode=\"wt\") # get position of each tradingDate and write it to logfile for", "# I leave it to the user to check for this. # for", "to a list of objects than create and append? # if it does", "for d in re.split(\"-\", start)] dateInts[1] -= 1 startDForm = \"&c=%d&a=%d&b=%d\" % tuple(dateInts)", "reformDate = True if (re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\", items[1])) else False # for each line, split", "not conform if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", start): dateInts = [int(d) for d in re.split(\"-\", start)]", "header fields items[0] = re.sub(\"Date\", \"date\", items[0]) items[0] = re.sub(\"Volume\", \"v\", items[0]) items[0]", "fileObj.write(\"%s\\n\" % i) finally: fileObj.close() # write a line of text to a", "reformed payload rPayload = reform_payload(payload) write_items(path=(\"%s/%s.csv\" % (args.folder, symbol)), items=rPayload, mode=\"wt\") # get", "header header = csv.reader(fileObj, delimiter=\",\", quotechar='\"').__next__() for line in csv.DictReader(fileObj, fieldnames=header): dictObjs.append(line) return", "import argparse import urllib.request import re import csv import os from collections import", "quotechar='\"').__next__() for line in csv.DictReader(fileObj, fieldnames=header): dictObjs.append(line) return dictObjs # why not convert", "\"&c=%d&a=%d&b=%d\" % tuple(dateInts) else: startDForm = \"\" if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", end): dateInts = [int(d)", "frequency=\"d\"): # check format, adjust month number, format to string # or leave", "a web request def req(url): try: return urllib.request.urlopen(url) except urllib.request.URLError as e: print(\"HTTP", "number, format to string # or leave blank if does not conform if", "does not exist, it must be created def init_folder(path): if os.path.exists(path): if os.path.isdir(path):", "os.path.isdir(path): return True else: print(\"File [%s] will not be overwritten\" % path) return", "endDate = str(args.endDate) if args.endDate else \"\" if items and initFolderSuccess and initLogSuccess:", "list of the results # and use write_items instead? writeln(path=args.log, mode=\"at\", text=(\"%s,%s,%s,%s\" %", "[int(d) for d in re.split(\"-\", start)] dateInts[1] -= 1 startDForm = \"&c=%d&a=%d&b=%d\" %", "preserve order. By <NAME> def unique(seq): seen = set() return [x for x", "headed list into continual order items.append(items[0]) items.reverse() items.pop() # rename the header fields", "\"&ignore=.csv\") return url # cleanly return the results of a web request def", "overwritten\" % path) return False else: try: os.makedirs(path) return True except FileExistsError as", "s.append((i['symbol'], i['tradingDate'])) d = defaultdict(list) for k, v in s: d[k].append(v) return d", "url # cleanly return the results of a web request def req(url): try:", "only the desired elements for i in range(len(items)): items[i] = re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\", \"\", items[i])", "[] for i in items: s.append((i['symbol'], i['tradingDate'])) d = defaultdict(list) for k, v", "service def form_url(symbol, start=\"\", end=\"\", frequency=\"d\"): # check format, adjust month number, format", "csv file and return dictionary objects def get_csv_dict(path): dictObjs = [] with open(path)", "contents in usable format def read_decode(httpObj): body = httpObj.read() httpObj.close() try: return body.decode('utf-8')", "return False finally: fileObj.close() # find unique items and preserve order. By <NAME>", "else \"\" if items and initFolderSuccess and initLogSuccess: uniqueSymbols = unique(list(i['symbol'] for i", "in usable format def read_decode(httpObj): body = httpObj.read() httpObj.close() try: return body.decode('utf-8') #", "if rPayload: pattern = re.compile(tradingDate) for pos in range(len(rPayload)): if not position: if", "#!/usr/bin/python3 # DESCRIPTION # An efficient python script that reads a line separated", "\"--endDate\", type=str, help=(\"Final date sought for the range of time \" + \"series", "specifically for the yahoo service def form_url(symbol, start=\"\", end=\"\", frequency=\"d\"): # check format,", "x not in seen and not seen.add(x)] # transform a nested dictionary into", "d in re.split(\"-\", end)] dateInts[1] -= 1 endDForm = \"&f=%d&d=%d&e=%d\" % tuple(dateInts) else:", "# DESCRIPTION # An efficient python script that reads a line separated list", "with open(path, mode) as fileObj: try: fileObj.write(\"%s\\n\" % text) return True except: print(\"File", "end=\"\", frequency=\"d\"): # check format, adjust month number, format to string # or", "% e) # reform provided payload items for legibility and remove irrelevant variables", "and check the number of rows nData = 0 payload = re.split(\"\\n\", read_decode(httpObj))", "help=(\"Final date sought for the range of time \" + \"series data, YYYY-MM-DD", "% (items[i][6:10], items[i][3:5], items[i][0:2], items[i][10:])) return items # write list items en masse", "import urllib.request import re import csv import os from collections import defaultdict #", "nData = len(payload) - 1 # write the reformed payload rPayload = reform_payload(payload)", "# An efficient python script that reads a line separated list of stock", "= [int(d) for d in re.split(\"-\", end)] dateInts[1] -= 1 endDForm = \"&f=%d&d=%d&e=%d\"", "in seq if x not in seen and not seen.add(x)] # transform a", "to summarise the outcome in terms of available data # please note that", "+ \"series data, YYYY-MM-DD format\")) args = argparser.parse_args() items = get_csv_dict(args.items) initFolderSuccess =", "items[0]) items[0] = re.sub(\"Volume\", \"v\", items[0]) items[0] = re.sub(\"Adj Close\", \"p\", items[0]) #", "\" + \"and dates of interest, YYYY-MM-DD format\")) argparser.add_argument(\"folder\", type=str, help=(\"The path to", "check for this. # for usage, use -h import argparse import urllib.request import", "a machine-readable logfile.\")) argparser.add_argument(\"-s\", \"--startDate\", type=str, help=(\"Initial date sought for the range of", "machine-readable logfile.\")) argparser.add_argument(\"-s\", \"--startDate\", type=str, help=(\"Initial date sought for the range of \"", "list items en masse to a file def write_items(path, items, mode=\"at\"): with open(path,", "nData = 0 payload = re.split(\"\\n\", read_decode(httpObj)) if payload: if payload[-1] == \"\":", "write a line of text to a file def writeln(path, text, mode=\"at\"): with", "re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\", \"\", items[i]) if reformDate: items[i] = (\"%s-%s-%s%s\" % (items[i][6:10], items[i][3:5], items[i][0:2], items[i][10:]))", "urls specifically for the yahoo service def form_url(symbol, start=\"\", end=\"\", frequency=\"d\"): # check", "init_folder(args.folder) initLogSuccess = writeln(path=args.log, mode=\"wt\", text=\"symbol,tradingDate,position,datapoints\") startDate = str(args.startDate) if args.startDate else \"\"", "the raw payload httpObj = req(form_url(symbol=symbol, start=startDate, end=endDate)) if httpObj: # transform it", "read_decode(httpObj)) if payload: if payload[-1] == \"\": payload.pop() # workaround for final \\n", "\"\": payload.pop() # workaround for final \\n on split nData = len(payload) -", "def writeln(path, text, mode=\"at\"): with open(path, mode) as fileObj: try: fileObj.write(\"%s\\n\" % text)", "def write_items(path, items, mode=\"at\"): with open(path, mode) as fileObj: try: for i in", "def form_url(symbol, start=\"\", end=\"\", frequency=\"d\"): # check format, adjust month number, format to", "def get_csv_dict(path): dictObjs = [] with open(path) as fileObj: # assuming the first", "and adjusted closing prices from Yahoo Finance. # a logfile is also created", "for this. # for usage, use -h import argparse import urllib.request import re", "key), (value) pairs def reform_items(items): s = [] for i in items: s.append((i['symbol'],", "= reform_payload(payload) write_items(path=(\"%s/%s.csv\" % (args.folder, symbol)), items=rPayload, mode=\"wt\") # get position of each", "tuple(dateInts) else: startDForm = \"\" if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", end): dateInts = [int(d) for d", "path to a machine-readable logfile.\")) argparser.add_argument(\"-s\", \"--startDate\", type=str, help=(\"Initial date sought for the", "reads a line separated list of stock symbols # with optional start and", "calendar dates, # such as 2015-06-31 # I leave it to the user", "[%s]\" % (e.code, url)) # return the http object contents in usable format", "args.endDate else \"\" if items and initFolderSuccess and initLogSuccess: uniqueSymbols = unique(list(i['symbol'] for", "mode=\"at\"): with open(path, mode) as fileObj: try: for i in items: fileObj.write(\"%s\\n\" %", "# write the reformed payload rPayload = reform_payload(payload) write_items(path=(\"%s/%s.csv\" % (args.folder, symbol)), items=rPayload,", "YYYY-MM-DD format\")) argparser.add_argument(\"-e\", \"--endDate\", type=str, help=(\"Final date sought for the range of time", "= str(args.startDate) if args.startDate else \"\" endDate = str(args.endDate) if args.endDate else \"\"", "initLogSuccess: uniqueSymbols = unique(list(i['symbol'] for i in items)) rItems = reform_items(items) for symbol", "items, mode=\"at\"): with open(path, mode) as fileObj: try: for i in items: fileObj.write(\"%s\\n\"", "== \"\": payload.pop() # workaround for final \\n on split nData = len(payload)", "items[1])) else False # for each line, split by comma, extract only the", "except UnicodeDecodeError as e: print(\"Decode Error [%s]\" % e) # reform provided payload", "time \" + \"series data, YYYY-MM-DD format\")) args = argparser.parse_args() items = get_csv_dict(args.items)", "note that yahoo will return a different payload than expected if # the", "= \"&f=%d&d=%d&e=%d\" % tuple(dateInts) else: endDForm = \"\" url = (\"http://real-chart.finance.yahoo.com/table.csv\" + \"?s=\"", "+ symbol + endDForm + \"&g=\" + frequency + startDForm + \"&ignore=.csv\") return", "# get position of each tradingDate and write it to logfile for tradingDate", "True except: print(\"File error: could not write [%s] to [%s]\" % (text, path))", "= re.sub(\"Adj Close\", \"p\", items[0]) # determine if the date format requires reformatting", "args = argparser.parse_args() items = get_csv_dict(args.items) initFolderSuccess = init_folder(args.folder) initLogSuccess = writeln(path=args.log, mode=\"wt\",", "created def init_folder(path): if os.path.exists(path): if os.path.isdir(path): return True else: print(\"File [%s] will", "masse to a file def write_items(path, items, mode=\"at\"): with open(path, mode) as fileObj:", "req(url): try: return urllib.request.urlopen(url) except urllib.request.URLError as e: print(\"HTTP Error [%s] with [%s]\"", "items[0] = re.sub(\"Date\", \"date\", items[0]) items[0] = re.sub(\"Volume\", \"v\", items[0]) items[0] = re.sub(\"Adj", "check the number of rows nData = 0 payload = re.split(\"\\n\", read_decode(httpObj)) if", "# start with parsing the arguments argparser = argparse.ArgumentParser() argparser.add_argument(\"items\", type=str, help=(\"CSV format", "\"--startDate\", type=str, help=(\"Initial date sought for the range of \" + \"time series", "open(path, mode) as fileObj: try: for i in items: fileObj.write(\"%s\\n\" % i) finally:", "if reformDate: items[i] = (\"%s-%s-%s%s\" % (items[i][6:10], items[i][3:5], items[i][0:2], items[i][10:])) return items #", "= argparser.parse_args() items = get_csv_dict(args.items) initFolderSuccess = init_folder(args.folder) initLogSuccess = writeln(path=args.log, mode=\"wt\", text=\"symbol,tradingDate,position,datapoints\")", "# get the raw payload httpObj = req(form_url(symbol=symbol, start=startDate, end=endDate)) if httpObj: #", "= True if (re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\", items[1])) else False # for each line, split by", "and append? # if it does not exist, it must be created def", "if os.path.isdir(path): return True else: print(\"File [%s] will not be overwritten\" % path)", "order items.append(items[0]) items.reverse() items.pop() # rename the header fields items[0] = re.sub(\"Date\", \"date\",", "dictionary into (unique key), (value) pairs def reform_items(items): s = [] for i", "argparser.add_argument(\"-e\", \"--endDate\", type=str, help=(\"Final date sought for the range of time \" +", "not position: if pattern.match(rPayload[pos]): position = str(pos) # perhaps it might be quicker", "fileObj: try: for i in items: fileObj.write(\"%s\\n\" % i) finally: fileObj.close() # write", "else: print(\"File [%s] will not be overwritten\" % path) return False else: try:", "True except FileExistsError as e: print(\"File Error [%s] with [%s]\" % (e, path))", "[%s] to [%s]\" % (text, path)) return False finally: fileObj.close() # find unique", "items for legibility and remove irrelevant variables def reform_payload(items): # reversing the headed", "argparser.add_argument(\"items\", type=str, help=(\"CSV format items of stock symbols \" + \"and dates of", "the reformed payload rPayload = reform_payload(payload) write_items(path=(\"%s/%s.csv\" % (args.folder, symbol)), items=rPayload, mode=\"wt\") #", "path) return False else: try: os.makedirs(path) return True except FileExistsError as e: print(\"File", "the results # and use write_items instead? writeln(path=args.log, mode=\"at\", text=(\"%s,%s,%s,%s\" % (symbol, tradingDate,", "summarise the outcome in terms of available data # please note that yahoo", "irrelevant variables def reform_payload(items): # reversing the headed list into continual order items.append(items[0])", "format, adjust month number, format to string # or leave blank if does", "format items of stock symbols \" + \"and dates of interest, YYYY-MM-DD format\"))", "results # and use write_items instead? writeln(path=args.log, mode=\"at\", text=(\"%s,%s,%s,%s\" % (symbol, tradingDate, position,", "os from collections import defaultdict # read a csv file and return dictionary", "if # the start or end dates requested do not match global calendar", "# transform a nested dictionary into (unique key), (value) pairs def reform_items(items): s", "symbol) # get the raw payload httpObj = req(form_url(symbol=symbol, start=startDate, end=endDate)) if httpObj:", "to list items and check the number of rows nData = 0 payload", "\"\" endDate = str(args.endDate) if args.endDate else \"\" if items and initFolderSuccess and", "str(pos) # perhaps it might be quicker to make a list of the", "request def req(url): try: return urllib.request.urlopen(url) except urllib.request.URLError as e: print(\"HTTP Error [%s]", "if items and initFolderSuccess and initLogSuccess: uniqueSymbols = unique(list(i['symbol'] for i in items))", "\"and dates of interest, YYYY-MM-DD format\")) argparser.add_argument(\"folder\", type=str, help=(\"The path to a folder", "a file def writeln(path, text, mode=\"at\"): with open(path, mode) as fileObj: try: fileObj.write(\"%s\\n\"", "the arguments argparser = argparse.ArgumentParser() argparser.add_argument(\"items\", type=str, help=(\"CSV format items of stock symbols", "# read a csv file and return dictionary objects def get_csv_dict(path): dictObjs =", "header = csv.reader(fileObj, delimiter=\",\", quotechar='\"').__next__() for line in csv.DictReader(fileObj, fieldnames=header): dictObjs.append(line) return dictObjs", "print(\"File [%s] will not be overwritten\" % path) return False else: try: os.makedirs(path)", "not in seen and not seen.add(x)] # transform a nested dictionary into (unique", "start): dateInts = [int(d) for d in re.split(\"-\", start)] dateInts[1] -= 1 startDForm", "raw payload httpObj = req(form_url(symbol=symbol, start=startDate, end=endDate)) if httpObj: # transform it to", "will not be overwritten\" % path) return False else: try: os.makedirs(path) return True", "dateInts[1] -= 1 startDForm = \"&c=%d&a=%d&b=%d\" % tuple(dateInts) else: startDForm = \"\" if", "True if (re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\", items[1])) else False # for each line, split by comma,", "# transform it to list items and check the number of rows nData", "payload items for legibility and remove irrelevant variables def reform_payload(items): # reversing the", "order. By <NAME> def unique(seq): seen = set() return [x for x in", "dates requested do not match global calendar dates, # such as 2015-06-31 #", "stock symbols \" + \"and dates of interest, YYYY-MM-DD format\")) argparser.add_argument(\"folder\", type=str, help=(\"The", "items.pop() # rename the header fields items[0] = re.sub(\"Date\", \"date\", items[0]) items[0] =", "help=(\"The path to a folder to which stock \" + \"price files are", "into continual order items.append(items[0]) items.reverse() items.pop() # rename the header fields items[0] =", "as e: print(\"HTTP Error [%s] with [%s]\" % (e.code, url)) # return the", "a line separated list of stock symbols # with optional start and end", "= argparse.ArgumentParser() argparser.add_argument(\"items\", type=str, help=(\"CSV format items of stock symbols \" + \"and", "dates of interest, YYYY-MM-DD format\")) argparser.add_argument(\"folder\", type=str, help=(\"The path to a folder to", "type=str, help=(\"The path to a folder to which stock \" + \"price files", "logfile.\")) argparser.add_argument(\"-s\", \"--startDate\", type=str, help=(\"Initial date sought for the range of \" +", "= init_folder(args.folder) initLogSuccess = writeln(path=args.log, mode=\"wt\", text=\"symbol,tradingDate,position,datapoints\") startDate = str(args.startDate) if args.startDate else", "dictObjs.append(line) return dictObjs # why not convert to a list of objects than", "items and initFolderSuccess and initLogSuccess: uniqueSymbols = unique(list(i['symbol'] for i in items)) rItems", "available data # please note that yahoo will return a different payload than", "of a web request def req(url): try: return urllib.request.urlopen(url) except urllib.request.URLError as e:", "========================================================= # start with parsing the arguments argparser = argparse.ArgumentParser() argparser.add_argument(\"items\", type=str, help=(\"CSV", "for i in items)) rItems = reform_items(items) for symbol in uniqueSymbols: print(\"Accessing %s\"", "print(\"File Error [%s] with [%s]\" % (e, path)) return False # forming urls", "seen.add(x)] # transform a nested dictionary into (unique key), (value) pairs def reform_items(items):", "re.sub(\"Date\", \"date\", items[0]) items[0] = re.sub(\"Volume\", \"v\", items[0]) items[0] = re.sub(\"Adj Close\", \"p\",", "seen and not seen.add(x)] # transform a nested dictionary into (unique key), (value)", "each line, split by comma, extract only the desired elements for i in", "= httpObj.read() httpObj.close() try: return body.decode('utf-8') # required, but a bottleneck except UnicodeDecodeError", "write_items(path=(\"%s/%s.csv\" % (args.folder, symbol)), items=rPayload, mode=\"wt\") # get position of each tradingDate and", "re.compile(tradingDate) for pos in range(len(rPayload)): if not position: if pattern.match(rPayload[pos]): position = str(pos)", "for the range of time \" + \"series data, YYYY-MM-DD format\")) args =", "args.startDate else \"\" endDate = str(args.endDate) if args.endDate else \"\" if items and", "else \"\" endDate = str(args.endDate) if args.endDate else \"\" if items and initFolderSuccess", "sought for the range of \" + \"time series data, YYYY-MM-DD format\")) argparser.add_argument(\"-e\",", "# the start or end dates requested do not match global calendar dates,", "# perhaps it might be quicker to make a list of the results", "\"&g=\" + frequency + startDForm + \"&ignore=.csv\") return url # cleanly return the", "payload[-1] == \"\": payload.pop() # workaround for final \\n on split nData =", "unique items and preserve order. By <NAME> def unique(seq): seen = set() return", "# forming urls specifically for the yahoo service def form_url(symbol, start=\"\", end=\"\", frequency=\"d\"):", "and end dates for range and saves the relevant daily # volume and", "# cleanly return the results of a web request def req(url): try: return", "# if it does not exist, it must be created def init_folder(path): if", "% text) return True except: print(\"File error: could not write [%s] to [%s]\"", "i) finally: fileObj.close() # write a line of text to a file def", "YYYY-MM-DD format\")) args = argparser.parse_args() items = get_csv_dict(args.items) initFolderSuccess = init_folder(args.folder) initLogSuccess =", "if does not conform if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", start): dateInts = [int(d) for d in", "to which stock \" + \"price files are saved.\")) argparser.add_argument(\"log\", type=str, help=(\"The path", "d # main section ========================================================= # start with parsing the arguments argparser =", "that reads a line separated list of stock symbols # with optional start", "text=\"symbol,tradingDate,position,datapoints\") startDate = str(args.startDate) if args.startDate else \"\" endDate = str(args.endDate) if args.endDate", "i in range(len(items)): items[i] = re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\", \"\", items[i]) if reformDate: items[i] = (\"%s-%s-%s%s\"", "if httpObj: # transform it to list items and check the number of", "in range(len(rPayload)): if not position: if pattern.match(rPayload[pos]): position = str(pos) # perhaps it", "mode=\"wt\", text=\"symbol,tradingDate,position,datapoints\") startDate = str(args.startDate) if args.startDate else \"\" endDate = str(args.endDate) if", "if payload[-1] == \"\": payload.pop() # workaround for final \\n on split nData", "could not write [%s] to [%s]\" % (text, path)) return False finally: fileObj.close()", "initFolderSuccess and initLogSuccess: uniqueSymbols = unique(list(i['symbol'] for i in items)) rItems = reform_items(items)", "text, mode=\"at\"): with open(path, mode) as fileObj: try: fileObj.write(\"%s\\n\" % text) return True", "return url # cleanly return the results of a web request def req(url):", "print(\"File error: could not write [%s] to [%s]\" % (text, path)) return False", "% (args.folder, symbol)), items=rPayload, mode=\"wt\") # get position of each tradingDate and write", "bottleneck except UnicodeDecodeError as e: print(\"Decode Error [%s]\" % e) # reform provided", "of the results # and use write_items instead? writeln(path=args.log, mode=\"at\", text=(\"%s,%s,%s,%s\" % (symbol,", "payload rPayload = reform_payload(payload) write_items(path=(\"%s/%s.csv\" % (args.folder, symbol)), items=rPayload, mode=\"wt\") # get position", "the outcome in terms of available data # please note that yahoo will", "why not convert to a list of objects than create and append? #", "get position of each tradingDate and write it to logfile for tradingDate in", "pos in range(len(rPayload)): if not position: if pattern.match(rPayload[pos]): position = str(pos) # perhaps", "error: could not write [%s] to [%s]\" % (text, path)) return False finally:", "False # forming urls specifically for the yahoo service def form_url(symbol, start=\"\", end=\"\",", "i in items: s.append((i['symbol'], i['tradingDate'])) d = defaultdict(list) for k, v in s:", "reform_payload(payload) write_items(path=(\"%s/%s.csv\" % (args.folder, symbol)), items=rPayload, mode=\"wt\") # get position of each tradingDate", "\"\" if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", end): dateInts = [int(d) for d in re.split(\"-\", end)] dateInts[1]", "items and check the number of rows nData = 0 payload = re.split(\"\\n\",", "body.decode('utf-8') # required, but a bottleneck except UnicodeDecodeError as e: print(\"Decode Error [%s]\"", "be created def init_folder(path): if os.path.exists(path): if os.path.isdir(path): return True else: print(\"File [%s]", "workaround for final \\n on split nData = len(payload) - 1 # write", "print(\"Decode Error [%s]\" % e) # reform provided payload items for legibility and", "format requires reformatting reformDate = True if (re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\", items[1])) else False # for", "argparse import urllib.request import re import csv import os from collections import defaultdict", "% tuple(dateInts) else: startDForm = \"\" if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", end): dateInts = [int(d) for", "return items # write list items en masse to a file def write_items(path,", "logfile is also created to summarise the outcome in terms of available data", "[%s]\" % (text, path)) return False finally: fileObj.close() # find unique items and", "of time \" + \"series data, YYYY-MM-DD format\")) args = argparser.parse_args() items =", "a header header = csv.reader(fileObj, delimiter=\",\", quotechar='\"').__next__() for line in csv.DictReader(fileObj, fieldnames=header): dictObjs.append(line)", "date sought for the range of \" + \"time series data, YYYY-MM-DD format\"))", "the relevant daily # volume and adjusted closing prices from Yahoo Finance. #", "to a file def write_items(path, items, mode=\"at\"): with open(path, mode) as fileObj: try:", "True else: print(\"File [%s] will not be overwritten\" % path) return False else:", "write_items(path, items, mode=\"at\"): with open(path, mode) as fileObj: try: for i in items:", "end=endDate)) if httpObj: # transform it to list items and check the number", "in re.split(\"-\", end)] dateInts[1] -= 1 endDForm = \"&f=%d&d=%d&e=%d\" % tuple(dateInts) else: endDForm", "# assuming the first line is a header header = csv.reader(fileObj, delimiter=\",\", quotechar='\"').__next__()", "script that reads a line separated list of stock symbols # with optional", "the yahoo service def form_url(symbol, start=\"\", end=\"\", frequency=\"d\"): # check format, adjust month", "forming urls specifically for the yahoo service def form_url(symbol, start=\"\", end=\"\", frequency=\"d\"): #", "return True except: print(\"File error: could not write [%s] to [%s]\" % (text,", "def reform_payload(items): # reversing the headed list into continual order items.append(items[0]) items.reverse() items.pop()", "yahoo service def form_url(symbol, start=\"\", end=\"\", frequency=\"d\"): # check format, adjust month number,", "the range of time \" + \"series data, YYYY-MM-DD format\")) args = argparser.parse_args()", "data, YYYY-MM-DD format\")) argparser.add_argument(\"-e\", \"--endDate\", type=str, help=(\"Final date sought for the range of", "re.split(\"-\", end)] dateInts[1] -= 1 endDForm = \"&f=%d&d=%d&e=%d\" % tuple(dateInts) else: endDForm =", "% (e, path)) return False # forming urls specifically for the yahoo service", "% tuple(dateInts) else: endDForm = \"\" url = (\"http://real-chart.finance.yahoo.com/table.csv\" + \"?s=\" + symbol", "to the user to check for this. # for usage, use -h import", "\"v\", items[0]) items[0] = re.sub(\"Adj Close\", \"p\", items[0]) # determine if the date", "[x for x in seq if x not in seen and not seen.add(x)]", "items[0] = re.sub(\"Adj Close\", \"p\", items[0]) # determine if the date format requires", "is also created to summarise the outcome in terms of available data #", "dictObjs # why not convert to a list of objects than create and", "# why not convert to a list of objects than create and append?", "blank if does not conform if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", start): dateInts = [int(d) for d", "reformDate: items[i] = (\"%s-%s-%s%s\" % (items[i][6:10], items[i][3:5], items[i][0:2], items[i][10:])) return items # write", "a nested dictionary into (unique key), (value) pairs def reform_items(items): s = []", "+ startDForm + \"&ignore=.csv\") return url # cleanly return the results of a", "conform if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", start): dateInts = [int(d) for d in re.split(\"-\", start)] dateInts[1]", "the http object contents in usable format def read_decode(httpObj): body = httpObj.read() httpObj.close()", "= \"\" if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", end): dateInts = [int(d) for d in re.split(\"-\", end)]", "else: startDForm = \"\" if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", end): dateInts = [int(d) for d in", "position: if pattern.match(rPayload[pos]): position = str(pos) # perhaps it might be quicker to", "start or end dates requested do not match global calendar dates, # such", "open(path) as fileObj: # assuming the first line is a header header =", "but a bottleneck except UnicodeDecodeError as e: print(\"Decode Error [%s]\" % e) #", "in items: fileObj.write(\"%s\\n\" % i) finally: fileObj.close() # write a line of text", "\"\" url = (\"http://real-chart.finance.yahoo.com/table.csv\" + \"?s=\" + symbol + endDForm + \"&g=\" +", "argparser.add_argument(\"folder\", type=str, help=(\"The path to a folder to which stock \" + \"price", "# find unique items and preserve order. By <NAME> def unique(seq): seen =", "as fileObj: try: fileObj.write(\"%s\\n\" % text) return True except: print(\"File error: could not", "adjusted closing prices from Yahoo Finance. # a logfile is also created to", "startDForm + \"&ignore=.csv\") return url # cleanly return the results of a web", "comma, extract only the desired elements for i in range(len(items)): items[i] = re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\",", "\" + \"price files are saved.\")) argparser.add_argument(\"log\", type=str, help=(\"The path to a machine-readable", "series data, YYYY-MM-DD format\")) argparser.add_argument(\"-e\", \"--endDate\", type=str, help=(\"Final date sought for the range", "\"?s=\" + symbol + endDForm + \"&g=\" + frequency + startDForm + \"&ignore=.csv\")", "# reversing the headed list into continual order items.append(items[0]) items.reverse() items.pop() # rename", "get_csv_dict(args.items) initFolderSuccess = init_folder(args.folder) initLogSuccess = writeln(path=args.log, mode=\"wt\", text=\"symbol,tradingDate,position,datapoints\") startDate = str(args.startDate) if", "unique(list(i['symbol'] for i in items)) rItems = reform_items(items) for symbol in uniqueSymbols: print(\"Accessing", "convert to a list of objects than create and append? # if it", "False finally: fileObj.close() # find unique items and preserve order. By <NAME> def", "fileObj.close() # write a line of text to a file def writeln(path, text,", "it to the user to check for this. # for usage, use -h", "yahoo will return a different payload than expected if # the start or", "\"date\", items[0]) items[0] = re.sub(\"Volume\", \"v\", items[0]) items[0] = re.sub(\"Adj Close\", \"p\", items[0])", "<NAME> def unique(seq): seen = set() return [x for x in seq if", "type=str, help=(\"CSV format items of stock symbols \" + \"and dates of interest,", "try: return urllib.request.urlopen(url) except urllib.request.URLError as e: print(\"HTTP Error [%s] with [%s]\" %", "fileObj: try: fileObj.write(\"%s\\n\" % text) return True except: print(\"File error: could not write", "= \"&c=%d&a=%d&b=%d\" % tuple(dateInts) else: startDForm = \"\" if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", end): dateInts =", "x in seq if x not in seen and not seen.add(x)] # transform", "file and return dictionary objects def get_csv_dict(path): dictObjs = [] with open(path) as", "month number, format to string # or leave blank if does not conform", "open(path, mode) as fileObj: try: fileObj.write(\"%s\\n\" % text) return True except: print(\"File error:", "in uniqueSymbols: print(\"Accessing %s\" % symbol) # get the raw payload httpObj =", "end)] dateInts[1] -= 1 endDForm = \"&f=%d&d=%d&e=%d\" % tuple(dateInts) else: endDForm = \"\"", "symbol + endDForm + \"&g=\" + frequency + startDForm + \"&ignore=.csv\") return url", "return a different payload than expected if # the start or end dates", "daily # volume and adjusted closing prices from Yahoo Finance. # a logfile", "help=(\"The path to a machine-readable logfile.\")) argparser.add_argument(\"-s\", \"--startDate\", type=str, help=(\"Initial date sought for", "a logfile is also created to summarise the outcome in terms of available", "payload.pop() # workaround for final \\n on split nData = len(payload) - 1", "separated list of stock symbols # with optional start and end dates for", "it to logfile for tradingDate in rItems[symbol]: position = \"\" if rPayload: pattern", "if args.startDate else \"\" endDate = str(args.endDate) if args.endDate else \"\" if items", "a list of objects than create and append? # if it does not", "\"\" if items and initFolderSuccess and initLogSuccess: uniqueSymbols = unique(list(i['symbol'] for i in", "s = [] for i in items: s.append((i['symbol'], i['tradingDate'])) d = defaultdict(list) for", "in csv.DictReader(fileObj, fieldnames=header): dictObjs.append(line) return dictObjs # why not convert to a list", "list into continual order items.append(items[0]) items.reverse() items.pop() # rename the header fields items[0]", "get the raw payload httpObj = req(form_url(symbol=symbol, start=startDate, end=endDate)) if httpObj: # transform", "use -h import argparse import urllib.request import re import csv import os from", "d in re.split(\"-\", start)] dateInts[1] -= 1 startDForm = \"&c=%d&a=%d&b=%d\" % tuple(dateInts) else:", "(re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\", items[1])) else False # for each line, split by comma, extract only", "a different payload than expected if # the start or end dates requested", "number of rows nData = 0 payload = re.split(\"\\n\", read_decode(httpObj)) if payload: if", "split nData = len(payload) - 1 # write the reformed payload rPayload =", "fileObj: # assuming the first line is a header header = csv.reader(fileObj, delimiter=\",\",", "to string # or leave blank if does not conform if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", start):", "= reform_items(items) for symbol in uniqueSymbols: print(\"Accessing %s\" % symbol) # get the", "# a logfile is also created to summarise the outcome in terms of", "first line is a header header = csv.reader(fileObj, delimiter=\",\", quotechar='\"').__next__() for line in", "(items[i][6:10], items[i][3:5], items[i][0:2], items[i][10:])) return items # write list items en masse to", "argparser.add_argument(\"log\", type=str, help=(\"The path to a machine-readable logfile.\")) argparser.add_argument(\"-s\", \"--startDate\", type=str, help=(\"Initial date", "usable format def read_decode(httpObj): body = httpObj.read() httpObj.close() try: return body.decode('utf-8') # required,", "file def writeln(path, text, mode=\"at\"): with open(path, mode) as fileObj: try: fileObj.write(\"%s\\n\" %", "to [%s]\" % (text, path)) return False finally: fileObj.close() # find unique items", "the date format requires reformatting reformDate = True if (re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\", items[1])) else False", "+ \"?s=\" + symbol + endDForm + \"&g=\" + frequency + startDForm +", "list of objects than create and append? # if it does not exist,", "line is a header header = csv.reader(fileObj, delimiter=\",\", quotechar='\"').__next__() for line in csv.DictReader(fileObj,", "except urllib.request.URLError as e: print(\"HTTP Error [%s] with [%s]\" % (e.code, url)) #", "data # please note that yahoo will return a different payload than expected", "it to list items and check the number of rows nData = 0", "if the date format requires reformatting reformDate = True if (re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\", items[1])) else", "# workaround for final \\n on split nData = len(payload) - 1 #", "= 0 payload = re.split(\"\\n\", read_decode(httpObj)) if payload: if payload[-1] == \"\": payload.pop()", "defaultdict # read a csv file and return dictionary objects def get_csv_dict(path): dictObjs", "or end dates requested do not match global calendar dates, # such as", "such as 2015-06-31 # I leave it to the user to check for", "if it does not exist, it must be created def init_folder(path): if os.path.exists(path):", "a line of text to a file def writeln(path, text, mode=\"at\"): with open(path,", "variables def reform_payload(items): # reversing the headed list into continual order items.append(items[0]) items.reverse()", "= \"\" url = (\"http://real-chart.finance.yahoo.com/table.csv\" + \"?s=\" + symbol + endDForm + \"&g=\"", "symbols \" + \"and dates of interest, YYYY-MM-DD format\")) argparser.add_argument(\"folder\", type=str, help=(\"The path", "len(payload) - 1 # write the reformed payload rPayload = reform_payload(payload) write_items(path=(\"%s/%s.csv\" %", "sought for the range of time \" + \"series data, YYYY-MM-DD format\")) args", "reform_payload(items): # reversing the headed list into continual order items.append(items[0]) items.reverse() items.pop() #", "for each line, split by comma, extract only the desired elements for i", "= req(form_url(symbol=symbol, start=startDate, end=endDate)) if httpObj: # transform it to list items and", "range of \" + \"time series data, YYYY-MM-DD format\")) argparser.add_argument(\"-e\", \"--endDate\", type=str, help=(\"Final", "in seen and not seen.add(x)] # transform a nested dictionary into (unique key),", "format\")) argparser.add_argument(\"-e\", \"--endDate\", type=str, help=(\"Final date sought for the range of time \"", "try: for i in items: fileObj.write(\"%s\\n\" % i) finally: fileObj.close() # write a", "httpObj = req(form_url(symbol=symbol, start=startDate, end=endDate)) if httpObj: # transform it to list items", "(e.code, url)) # return the http object contents in usable format def read_decode(httpObj):", "YYYY-MM-DD format\")) argparser.add_argument(\"folder\", type=str, help=(\"The path to a folder to which stock \"", "items[i] = (\"%s-%s-%s%s\" % (items[i][6:10], items[i][3:5], items[i][0:2], items[i][10:])) return items # write list", "write it to logfile for tradingDate in rItems[symbol]: position = \"\" if rPayload:", "leave it to the user to check for this. # for usage, use", "else False # for each line, split by comma, extract only the desired", "transform a nested dictionary into (unique key), (value) pairs def reform_items(items): s =", "(\"%s-%s-%s%s\" % (items[i][6:10], items[i][3:5], items[i][0:2], items[i][10:])) return items # write list items en", "the desired elements for i in range(len(items)): items[i] = re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\", \"\", items[i]) if", "usage, use -h import argparse import urllib.request import re import csv import os", "and return dictionary objects def get_csv_dict(path): dictObjs = [] with open(path) as fileObj:", "\"p\", items[0]) # determine if the date format requires reformatting reformDate = True", "of \" + \"time series data, YYYY-MM-DD format\")) argparser.add_argument(\"-e\", \"--endDate\", type=str, help=(\"Final date", "parsing the arguments argparser = argparse.ArgumentParser() argparser.add_argument(\"items\", type=str, help=(\"CSV format items of stock", "with optional start and end dates for range and saves the relevant daily", "help=(\"Initial date sought for the range of \" + \"time series data, YYYY-MM-DD", "match global calendar dates, # such as 2015-06-31 # I leave it to", "= defaultdict(list) for k, v in s: d[k].append(v) return d # main section", "is a header header = csv.reader(fileObj, delimiter=\",\", quotechar='\"').__next__() for line in csv.DictReader(fileObj, fieldnames=header):", "from collections import defaultdict # read a csv file and return dictionary objects", "dates, # such as 2015-06-31 # I leave it to the user to", "-h import argparse import urllib.request import re import csv import os from collections", "object contents in usable format def read_decode(httpObj): body = httpObj.read() httpObj.close() try: return", "e: print(\"File Error [%s] with [%s]\" % (e, path)) return False # forming", "it does not exist, it must be created def init_folder(path): if os.path.exists(path): if", "payload than expected if # the start or end dates requested do not", "else: try: os.makedirs(path) return True except FileExistsError as e: print(\"File Error [%s] with", "text to a file def writeln(path, text, mode=\"at\"): with open(path, mode) as fileObj:", "with [%s]\" % (e, path)) return False # forming urls specifically for the", "start)] dateInts[1] -= 1 startDForm = \"&c=%d&a=%d&b=%d\" % tuple(dateInts) else: startDForm = \"\"", "for x in seq if x not in seen and not seen.add(x)] #", "reform_items(items): s = [] for i in items: s.append((i['symbol'], i['tradingDate'])) d = defaultdict(list)", "defaultdict(list) for k, v in s: d[k].append(v) return d # main section =========================================================", "also created to summarise the outcome in terms of available data # please", "Error [%s]\" % e) # reform provided payload items for legibility and remove", "the user to check for this. # for usage, use -h import argparse", "= csv.reader(fileObj, delimiter=\",\", quotechar='\"').__next__() for line in csv.DictReader(fileObj, fieldnames=header): dictObjs.append(line) return dictObjs #", "position = \"\" if rPayload: pattern = re.compile(tradingDate) for pos in range(len(rPayload)): if", "a bottleneck except UnicodeDecodeError as e: print(\"Decode Error [%s]\" % e) # reform", "# and use write_items instead? writeln(path=args.log, mode=\"at\", text=(\"%s,%s,%s,%s\" % (symbol, tradingDate, position, str(nData))))", "if x not in seen and not seen.add(x)] # transform a nested dictionary", "k, v in s: d[k].append(v) return d # main section ========================================================= # start", "finally: fileObj.close() # find unique items and preserve order. By <NAME> def unique(seq):", "in items)) rItems = reform_items(items) for symbol in uniqueSymbols: print(\"Accessing %s\" % symbol)", "adjust month number, format to string # or leave blank if does not", "[] with open(path) as fileObj: # assuming the first line is a header", "unique(seq): seen = set() return [x for x in seq if x not", "the number of rows nData = 0 payload = re.split(\"\\n\", read_decode(httpObj)) if payload:", "1 # write the reformed payload rPayload = reform_payload(payload) write_items(path=(\"%s/%s.csv\" % (args.folder, symbol)),", "symbols # with optional start and end dates for range and saves the", "if (re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\", items[1])) else False # for each line, split by comma, extract", "find unique items and preserve order. By <NAME> def unique(seq): seen = set()", "% symbol) # get the raw payload httpObj = req(form_url(symbol=symbol, start=startDate, end=endDate)) if", "endDForm + \"&g=\" + frequency + startDForm + \"&ignore=.csv\") return url # cleanly", "os.makedirs(path) return True except FileExistsError as e: print(\"File Error [%s] with [%s]\" %", "httpObj.read() httpObj.close() try: return body.decode('utf-8') # required, but a bottleneck except UnicodeDecodeError as", "re.sub(\"Volume\", \"v\", items[0]) items[0] = re.sub(\"Adj Close\", \"p\", items[0]) # determine if the", "items of stock symbols \" + \"and dates of interest, YYYY-MM-DD format\")) argparser.add_argument(\"folder\",", "argparser.parse_args() items = get_csv_dict(args.items) initFolderSuccess = init_folder(args.folder) initLogSuccess = writeln(path=args.log, mode=\"wt\", text=\"symbol,tradingDate,position,datapoints\") startDate", "fields items[0] = re.sub(\"Date\", \"date\", items[0]) items[0] = re.sub(\"Volume\", \"v\", items[0]) items[0] =", "of stock symbols \" + \"and dates of interest, YYYY-MM-DD format\")) argparser.add_argument(\"folder\", type=str,", "write the reformed payload rPayload = reform_payload(payload) write_items(path=(\"%s/%s.csv\" % (args.folder, symbol)), items=rPayload, mode=\"wt\")", "init_folder(path): if os.path.exists(path): if os.path.isdir(path): return True else: print(\"File [%s] will not be", "# or leave blank if does not conform if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", start): dateInts =", "# for each line, split by comma, extract only the desired elements for", "pattern = re.compile(tradingDate) for pos in range(len(rPayload)): if not position: if pattern.match(rPayload[pos]): position", "reformatting reformDate = True if (re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\", items[1])) else False # for each line,", "terms of available data # please note that yahoo will return a different", "which stock \" + \"price files are saved.\")) argparser.add_argument(\"log\", type=str, help=(\"The path to", "\"\" if rPayload: pattern = re.compile(tradingDate) for pos in range(len(rPayload)): if not position:", "payload: if payload[-1] == \"\": payload.pop() # workaround for final \\n on split", "rename the header fields items[0] = re.sub(\"Date\", \"date\", items[0]) items[0] = re.sub(\"Volume\", \"v\",", "optional start and end dates for range and saves the relevant daily #", "= re.sub(\"Volume\", \"v\", items[0]) items[0] = re.sub(\"Adj Close\", \"p\", items[0]) # determine if", "desired elements for i in range(len(items)): items[i] = re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\", \"\", items[i]) if reformDate:", "items[i][3:5], items[i][0:2], items[i][10:])) return items # write list items en masse to a", "items[0] = re.sub(\"Volume\", \"v\", items[0]) items[0] = re.sub(\"Adj Close\", \"p\", items[0]) # determine", "items[0]) items[0] = re.sub(\"Adj Close\", \"p\", items[0]) # determine if the date format", "to a file def writeln(path, text, mode=\"at\"): with open(path, mode) as fileObj: try:", "i in items)) rItems = reform_items(items) for symbol in uniqueSymbols: print(\"Accessing %s\" %", "csv.DictReader(fileObj, fieldnames=header): dictObjs.append(line) return dictObjs # why not convert to a list of", "[%s] with [%s]\" % (e, path)) return False # forming urls specifically for", "i['tradingDate'])) d = defaultdict(list) for k, v in s: d[k].append(v) return d #", "for i in range(len(items)): items[i] = re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\", \"\", items[i]) if reformDate: items[i] =", "to make a list of the results # and use write_items instead? writeln(path=args.log,", "of objects than create and append? # if it does not exist, it", "initFolderSuccess = init_folder(args.folder) initLogSuccess = writeln(path=args.log, mode=\"wt\", text=\"symbol,tradingDate,position,datapoints\") startDate = str(args.startDate) if args.startDate", "= set() return [x for x in seq if x not in seen", "of rows nData = 0 payload = re.split(\"\\n\", read_decode(httpObj)) if payload: if payload[-1]", "import defaultdict # read a csv file and return dictionary objects def get_csv_dict(path):", "continual order items.append(items[0]) items.reverse() items.pop() # rename the header fields items[0] = re.sub(\"Date\",", "1 startDForm = \"&c=%d&a=%d&b=%d\" % tuple(dateInts) else: startDForm = \"\" if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", end):", "print(\"HTTP Error [%s] with [%s]\" % (e.code, url)) # return the http object", "cleanly return the results of a web request def req(url): try: return urllib.request.urlopen(url)", "closing prices from Yahoo Finance. # a logfile is also created to summarise", "line, split by comma, extract only the desired elements for i in range(len(items)):", "not write [%s] to [%s]\" % (text, path)) return False finally: fileObj.close() #", "re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", end): dateInts = [int(d) for d in re.split(\"-\", end)] dateInts[1] -= 1", "body = httpObj.read() httpObj.close() try: return body.decode('utf-8') # required, but a bottleneck except", "= [int(d) for d in re.split(\"-\", start)] dateInts[1] -= 1 startDForm = \"&c=%d&a=%d&b=%d\"", "dateInts[1] -= 1 endDForm = \"&f=%d&d=%d&e=%d\" % tuple(dateInts) else: endDForm = \"\" url", "items: fileObj.write(\"%s\\n\" % i) finally: fileObj.close() # write a line of text to", "# check format, adjust month number, format to string # or leave blank", "def req(url): try: return urllib.request.urlopen(url) except urllib.request.URLError as e: print(\"HTTP Error [%s] with", "the range of \" + \"time series data, YYYY-MM-DD format\")) argparser.add_argument(\"-e\", \"--endDate\", type=str,", "position = str(pos) # perhaps it might be quicker to make a list", "csv import os from collections import defaultdict # read a csv file and", "path to a folder to which stock \" + \"price files are saved.\"))", "return d # main section ========================================================= # start with parsing the arguments argparser", "line separated list of stock symbols # with optional start and end dates", "FileExistsError as e: print(\"File Error [%s] with [%s]\" % (e, path)) return False", "main section ========================================================= # start with parsing the arguments argparser = argparse.ArgumentParser() argparser.add_argument(\"items\",", "for k, v in s: d[k].append(v) return d # main section ========================================================= #", "final \\n on split nData = len(payload) - 1 # write the reformed", "the first line is a header header = csv.reader(fileObj, delimiter=\",\", quotechar='\"').__next__() for line", "into (unique key), (value) pairs def reform_items(items): s = [] for i in", "set() return [x for x in seq if x not in seen and", "objects def get_csv_dict(path): dictObjs = [] with open(path) as fileObj: # assuming the", "arguments argparser = argparse.ArgumentParser() argparser.add_argument(\"items\", type=str, help=(\"CSV format items of stock symbols \"", "reform_items(items) for symbol in uniqueSymbols: print(\"Accessing %s\" % symbol) # get the raw", "\"price files are saved.\")) argparser.add_argument(\"log\", type=str, help=(\"The path to a machine-readable logfile.\")) argparser.add_argument(\"-s\",", "for range and saves the relevant daily # volume and adjusted closing prices", "dictionary objects def get_csv_dict(path): dictObjs = [] with open(path) as fileObj: # assuming", "line in csv.DictReader(fileObj, fieldnames=header): dictObjs.append(line) return dictObjs # why not convert to a", "delimiter=\",\", quotechar='\"').__next__() for line in csv.DictReader(fileObj, fieldnames=header): dictObjs.append(line) return dictObjs # why not", "symbol in uniqueSymbols: print(\"Accessing %s\" % symbol) # get the raw payload httpObj", "read a csv file and return dictionary objects def get_csv_dict(path): dictObjs = []", "% i) finally: fileObj.close() # write a line of text to a file", "in rItems[symbol]: position = \"\" if rPayload: pattern = re.compile(tradingDate) for pos in", "results of a web request def req(url): try: return urllib.request.urlopen(url) except urllib.request.URLError as", "(\"http://real-chart.finance.yahoo.com/table.csv\" + \"?s=\" + symbol + endDForm + \"&g=\" + frequency + startDForm", "logfile for tradingDate in rItems[symbol]: position = \"\" if rPayload: pattern = re.compile(tradingDate)", "pattern.match(rPayload[pos]): position = str(pos) # perhaps it might be quicker to make a", "requires reformatting reformDate = True if (re.search(\"^[0-9]{2}/[0-9]{2}/[0-9]{4},.*\", items[1])) else False # for each", "are saved.\")) argparser.add_argument(\"log\", type=str, help=(\"The path to a machine-readable logfile.\")) argparser.add_argument(\"-s\", \"--startDate\", type=str,", "False # for each line, split by comma, extract only the desired elements", "not convert to a list of objects than create and append? # if", "return False # forming urls specifically for the yahoo service def form_url(symbol, start=\"\",", "expected if # the start or end dates requested do not match global", "check format, adjust month number, format to string # or leave blank if", "(e, path)) return False # forming urls specifically for the yahoo service def", "in terms of available data # please note that yahoo will return a", "tradingDate and write it to logfile for tradingDate in rItems[symbol]: position = \"\"", "def read_decode(httpObj): body = httpObj.read() httpObj.close() try: return body.decode('utf-8') # required, but a", "% (text, path)) return False finally: fileObj.close() # find unique items and preserve", "on split nData = len(payload) - 1 # write the reformed payload rPayload", "range of time \" + \"series data, YYYY-MM-DD format\")) args = argparser.parse_args() items", "text) return True except: print(\"File error: could not write [%s] to [%s]\" %", "rItems = reform_items(items) for symbol in uniqueSymbols: print(\"Accessing %s\" % symbol) # get", "items[i] = re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\", \"\", items[i]) if reformDate: items[i] = (\"%s-%s-%s%s\" % (items[i][6:10], items[i][3:5],", "re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", start): dateInts = [int(d) for d in re.split(\"-\", start)] dateInts[1] -= 1", "file def write_items(path, items, mode=\"at\"): with open(path, mode) as fileObj: try: for i", "startDate = str(args.startDate) if args.startDate else \"\" endDate = str(args.endDate) if args.endDate else", "as 2015-06-31 # I leave it to the user to check for this.", "this. # for usage, use -h import argparse import urllib.request import re import", "+ frequency + startDForm + \"&ignore=.csv\") return url # cleanly return the results", "do not match global calendar dates, # such as 2015-06-31 # I leave", "Finance. # a logfile is also created to summarise the outcome in terms", "argparser = argparse.ArgumentParser() argparser.add_argument(\"items\", type=str, help=(\"CSV format items of stock symbols \" +", "path)) return False # forming urls specifically for the yahoo service def form_url(symbol,", "efficient python script that reads a line separated list of stock symbols #", "[%s]\" % e) # reform provided payload items for legibility and remove irrelevant", "and remove irrelevant variables def reform_payload(items): # reversing the headed list into continual", "# rename the header fields items[0] = re.sub(\"Date\", \"date\", items[0]) items[0] = re.sub(\"Volume\",", "form_url(symbol, start=\"\", end=\"\", frequency=\"d\"): # check format, adjust month number, format to string", "items[i][10:])) return items # write list items en masse to a file def", "in range(len(items)): items[i] = re.sub(\",[^,]*,[^,]*,[^,]*,[^,]*\", \"\", items[i]) if reformDate: items[i] = (\"%s-%s-%s%s\" %", "-= 1 endDForm = \"&f=%d&d=%d&e=%d\" % tuple(dateInts) else: endDForm = \"\" url =", "argparser.add_argument(\"-s\", \"--startDate\", type=str, help=(\"Initial date sought for the range of \" + \"time", "e) # reform provided payload items for legibility and remove irrelevant variables def", "items[i]) if reformDate: items[i] = (\"%s-%s-%s%s\" % (items[i][6:10], items[i][3:5], items[i][0:2], items[i][10:])) return items", "list items and check the number of rows nData = 0 payload =", "def init_folder(path): if os.path.exists(path): if os.path.isdir(path): return True else: print(\"File [%s] will not", "by comma, extract only the desired elements for i in range(len(items)): items[i] =", "and preserve order. By <NAME> def unique(seq): seen = set() return [x for", "(text, path)) return False finally: fileObj.close() # find unique items and preserve order.", "def reform_items(items): s = [] for i in items: s.append((i['symbol'], i['tradingDate'])) d =", "An efficient python script that reads a line separated list of stock symbols", "+ \"&g=\" + frequency + startDForm + \"&ignore=.csv\") return url # cleanly return", "finally: fileObj.close() # write a line of text to a file def writeln(path,", "d = defaultdict(list) for k, v in s: d[k].append(v) return d # main", "for pos in range(len(rPayload)): if not position: if pattern.match(rPayload[pos]): position = str(pos) #", "\"time series data, YYYY-MM-DD format\")) argparser.add_argument(\"-e\", \"--endDate\", type=str, help=(\"Final date sought for the", "not match global calendar dates, # such as 2015-06-31 # I leave it", "[%s]\" % (e, path)) return False # forming urls specifically for the yahoo", "# write list items en masse to a file def write_items(path, items, mode=\"at\"):", "rPayload: pattern = re.compile(tradingDate) for pos in range(len(rPayload)): if not position: if pattern.match(rPayload[pos]):", "url)) # return the http object contents in usable format def read_decode(httpObj): body", "items: s.append((i['symbol'], i['tradingDate'])) d = defaultdict(list) for k, v in s: d[k].append(v) return", "(value) pairs def reform_items(items): s = [] for i in items: s.append((i['symbol'], i['tradingDate']))", "else: endDForm = \"\" url = (\"http://real-chart.finance.yahoo.com/table.csv\" + \"?s=\" + symbol + endDForm", "str(args.startDate) if args.startDate else \"\" endDate = str(args.endDate) if args.endDate else \"\" if", "relevant daily # volume and adjusted closing prices from Yahoo Finance. # a", "legibility and remove irrelevant variables def reform_payload(items): # reversing the headed list into", "dates for range and saves the relevant daily # volume and adjusted closing", "uniqueSymbols: print(\"Accessing %s\" % symbol) # get the raw payload httpObj = req(form_url(symbol=symbol,", "in s: d[k].append(v) return d # main section ========================================================= # start with parsing", "\" + \"time series data, YYYY-MM-DD format\")) argparser.add_argument(\"-e\", \"--endDate\", type=str, help=(\"Final date sought", "= [] with open(path) as fileObj: # assuming the first line is a", "different payload than expected if # the start or end dates requested do", "global calendar dates, # such as 2015-06-31 # I leave it to the", "mode=\"at\"): with open(path, mode) as fileObj: try: fileObj.write(\"%s\\n\" % text) return True except:", "urllib.request.urlopen(url) except urllib.request.URLError as e: print(\"HTTP Error [%s] with [%s]\" % (e.code, url))", "the headed list into continual order items.append(items[0]) items.reverse() items.pop() # rename the header", "reform provided payload items for legibility and remove irrelevant variables def reform_payload(items): #", "must be created def init_folder(path): if os.path.exists(path): if os.path.isdir(path): return True else: print(\"File", "% path) return False else: try: os.makedirs(path) return True except FileExistsError as e:", "if os.path.exists(path): if os.path.isdir(path): return True else: print(\"File [%s] will not be overwritten\"", "tradingDate in rItems[symbol]: position = \"\" if rPayload: pattern = re.compile(tradingDate) for pos", "as e: print(\"File Error [%s] with [%s]\" % (e, path)) return False #", "\" + \"series data, YYYY-MM-DD format\")) args = argparser.parse_args() items = get_csv_dict(args.items) initFolderSuccess", "Yahoo Finance. # a logfile is also created to summarise the outcome in", "e: print(\"Decode Error [%s]\" % e) # reform provided payload items for legibility", "fileObj.write(\"%s\\n\" % text) return True except: print(\"File error: could not write [%s] to", "(unique key), (value) pairs def reform_items(items): s = [] for i in items:", "for the range of \" + \"time series data, YYYY-MM-DD format\")) argparser.add_argument(\"-e\", \"--endDate\",", "reversing the headed list into continual order items.append(items[0]) items.reverse() items.pop() # rename the", "and initFolderSuccess and initLogSuccess: uniqueSymbols = unique(list(i['symbol'] for i in items)) rItems =", "items[i][0:2], items[i][10:])) return items # write list items en masse to a file", "import re import csv import os from collections import defaultdict # read a", "# reform provided payload items for legibility and remove irrelevant variables def reform_payload(items):", "transform it to list items and check the number of rows nData =", "e: print(\"HTTP Error [%s] with [%s]\" % (e.code, url)) # return the http", "might be quicker to make a list of the results # and use", "= (\"%s-%s-%s%s\" % (items[i][6:10], items[i][3:5], items[i][0:2], items[i][10:])) return items # write list items", "str(args.endDate) if args.endDate else \"\" if items and initFolderSuccess and initLogSuccess: uniqueSymbols =", "\"series data, YYYY-MM-DD format\")) args = argparser.parse_args() items = get_csv_dict(args.items) initFolderSuccess = init_folder(args.folder)", "or leave blank if does not conform if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", start): dateInts = [int(d)", "for line in csv.DictReader(fileObj, fieldnames=header): dictObjs.append(line) return dictObjs # why not convert to", "start=\"\", end=\"\", frequency=\"d\"): # check format, adjust month number, format to string #", "web request def req(url): try: return urllib.request.urlopen(url) except urllib.request.URLError as e: print(\"HTTP Error", "frequency + startDForm + \"&ignore=.csv\") return url # cleanly return the results of", "rows nData = 0 payload = re.split(\"\\n\", read_decode(httpObj)) if payload: if payload[-1] ==", "print(\"Accessing %s\" % symbol) # get the raw payload httpObj = req(form_url(symbol=symbol, start=startDate,", "and initLogSuccess: uniqueSymbols = unique(list(i['symbol'] for i in items)) rItems = reform_items(items) for", "for the yahoo service def form_url(symbol, start=\"\", end=\"\", frequency=\"d\"): # check format, adjust", "outcome in terms of available data # please note that yahoo will return", "Error [%s] with [%s]\" % (e.code, url)) # return the http object contents", "a file def write_items(path, items, mode=\"at\"): with open(path, mode) as fileObj: try: for", "a folder to which stock \" + \"price files are saved.\")) argparser.add_argument(\"log\", type=str,", "type=str, help=(\"Final date sought for the range of time \" + \"series data,", "items)) rItems = reform_items(items) for symbol in uniqueSymbols: print(\"Accessing %s\" % symbol) #", "= re.split(\"\\n\", read_decode(httpObj)) if payload: if payload[-1] == \"\": payload.pop() # workaround for", "= \"\" if rPayload: pattern = re.compile(tradingDate) for pos in range(len(rPayload)): if not", "range(len(rPayload)): if not position: if pattern.match(rPayload[pos]): position = str(pos) # perhaps it might", "as fileObj: # assuming the first line is a header header = csv.reader(fileObj,", "files are saved.\")) argparser.add_argument(\"log\", type=str, help=(\"The path to a machine-readable logfile.\")) argparser.add_argument(\"-s\", \"--startDate\",", "string # or leave blank if does not conform if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", start): dateInts", "pairs def reform_items(items): s = [] for i in items: s.append((i['symbol'], i['tradingDate'])) d", "does not conform if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", start): dateInts = [int(d) for d in re.split(\"-\",", "except FileExistsError as e: print(\"File Error [%s] with [%s]\" % (e, path)) return", "and not seen.add(x)] # transform a nested dictionary into (unique key), (value) pairs", "(args.folder, symbol)), items=rPayload, mode=\"wt\") # get position of each tradingDate and write it", "to logfile for tradingDate in rItems[symbol]: position = \"\" if rPayload: pattern =", "I leave it to the user to check for this. # for usage,", "dictObjs = [] with open(path) as fileObj: # assuming the first line is", "format\")) argparser.add_argument(\"folder\", type=str, help=(\"The path to a folder to which stock \" +", "make a list of the results # and use write_items instead? writeln(path=args.log, mode=\"at\",", "to a machine-readable logfile.\")) argparser.add_argument(\"-s\", \"--startDate\", type=str, help=(\"Initial date sought for the range", "seq if x not in seen and not seen.add(x)] # transform a nested", "import csv import os from collections import defaultdict # read a csv file", "position of each tradingDate and write it to logfile for tradingDate in rItems[symbol]:", "+ endDForm + \"&g=\" + frequency + startDForm + \"&ignore=.csv\") return url #", "if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", end): dateInts = [int(d) for d in re.split(\"-\", end)] dateInts[1] -=", "startDForm = \"&c=%d&a=%d&b=%d\" % tuple(dateInts) else: startDForm = \"\" if re.search(\"^[0-9]{4}-[0-9]{2}-[0-9]{2}$\", end): dateInts", "# volume and adjusted closing prices from Yahoo Finance. # a logfile is", "import os from collections import defaultdict # read a csv file and return", "get_csv_dict(path): dictObjs = [] with open(path) as fileObj: # assuming the first line", "in items: s.append((i['symbol'], i['tradingDate'])) d = defaultdict(list) for k, v in s: d[k].append(v)", "end dates requested do not match global calendar dates, # such as 2015-06-31", "initLogSuccess = writeln(path=args.log, mode=\"wt\", text=\"symbol,tradingDate,position,datapoints\") startDate = str(args.startDate) if args.startDate else \"\" endDate", "required, but a bottleneck except UnicodeDecodeError as e: print(\"Decode Error [%s]\" % e)", "os.path.exists(path): if os.path.isdir(path): return True else: print(\"File [%s] will not be overwritten\" %", "with open(path, mode) as fileObj: try: for i in items: fileObj.write(\"%s\\n\" % i)", "python script that reads a line separated list of stock symbols # with", "[int(d) for d in re.split(\"-\", end)] dateInts[1] -= 1 endDForm = \"&f=%d&d=%d&e=%d\" %", "prices from Yahoo Finance. # a logfile is also created to summarise the", "items.reverse() items.pop() # rename the header fields items[0] = re.sub(\"Date\", \"date\", items[0]) items[0]", "end): dateInts = [int(d) for d in re.split(\"-\", end)] dateInts[1] -= 1 endDForm", "= writeln(path=args.log, mode=\"wt\", text=\"symbol,tradingDate,position,datapoints\") startDate = str(args.startDate) if args.startDate else \"\" endDate =", "# for usage, use -h import argparse import urllib.request import re import csv", "it might be quicker to make a list of the results # and" ]
[ "\"146\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"extension used\", \"category\": \"-Wlanguage-extension-token\", \"project\": None, \"hint\":", "\"52\", \"severity\": \"warning\", \"info\": \"extension used\", \"category\": \"-Wlanguage-extension-token\", \"project\": None, \"hint\": \"\" \"ZEXTERN", "\"info\": 'deprecated directive: ‘%name-prefix \"constexpYY\"’, use ‘%define ' \"api.prefix {constexpYY}’\", \"category\": \"-Wdeprecated\", \"project\":", "\"\" \"In file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres_fe.h:25,\\n\" \" from archive.c:19:\\n\", \"file\":", "Boost.Build engine (b2) is 4.8.0\", \"./src/graph.cc: In member function \\u2018void Edge::Dump(const char*) const\\u2019:\",", "because the Bison\" \"\\n*** output is pre-generated.)\", }, ], id=\"autotools\", ), pytest.param( [", "output is pre-generated.)\", }, ], id=\"autotools\", ), pytest.param( [ { \"ref\": \"libjpeg/1.2.3\", \"name\":", "\"10\", \"severity\": \"warning\", \"info\": \"passing 'unsigned int [4]' to parameter of type 'int", "^\", \"source_subfolder/meson.build:1559:2: ERROR: Problem encountered: \" \"Could not determine size of size_t.\", \"\",", "%ld\", \" 216 | &start, &end, perm, &offset, dev, &inode, file);\", \" |", "function \\u2018void Edge::Dump(const char*) const\\u2019:\", \"./src/graph.cc:409:16: warning: format \\u2018%p\\u2019 expects argument of type", "}, { \"channel\": None, \"info\": \"this is important\", \"name\": None, \"ref\": None, \"severity\":", "\"-w+macro-params-legacy\", \"project\": None, \"hint\": None, }, { \"context\": \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\",", "\"In file included from include\\\\crypto/evp.h:11:\\n\" \"In file included from include\\\\internal/refcount.h:21:\\n\" \"In file included", "\"Makefile.config:565: No sys/sdt.h found, no SDT events are defined, please install \" \"systemtap-sdt-devel", "\"\", \"file\": \"source_subfolder/meson.build\", \"line\": \"1559\", \"column\": \"2\", \"severity\": \"ERROR\", \"category\": None, \"info\": \"Problem", "2 has type ‘const Edge*’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" ' 409", "None, \"info\": \"requirement openssl/1.1.1m overridden by poco/1.11.1 to openssl/1.1.1l\", }, { \"channel\": None,", "\"hint\": \"\" \" 1073 | (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\\n\" \"", "z_off64_t, int));\", \" ^\", \"/build/source_subfolder/bzip2.c: In function ‘applySavedFileAttrToOutputFile’:\", \"/build/source_subfolder/bzip2.c:1073:11: warning: ignoring return value", "\"format ‘%ld’ expects argument of type ‘long int *’, but argument 8 \"", "file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres.h:46,\\n\" \" from stringinfo.c:20:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\":", "\"code '0x1'\", \"project\": None, \"hint\": None, }, ], id=\"msvc\", ), pytest.param( [ {", "\" | ~~~~~~\\n\" \" | |\\n\" \" | long unsigned int *\", },", "an empty translation unit [-Wpedantic]\", \" 284 | #endif\", \" | \", \"WARNING:", "\"hint\": \"\" ' 35 | %name-prefix \"constexpYY\"\\n' \" | ^~~~~~~~~~~~~~~~~~~~~~~~~ | %define api.prefix", "\"\" \" 1073 | (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\\n\" \" |", "\"project\": None, \"hint\": \"\" \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\\n\" \" ^~~~~~\", }, { \"context\":", "\" \"[-Wpointer-sign] [C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\", \"NMAKE : fatal error U1077: 'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : \" \"return code", "\" | long int *\\n\" \" | %ld\\n\" \" 216 | &start, &end,", "Rerun with option \" \"'--update'. [-Wother]\", \"/source_subfolder/common/socket_utils.cc(43): warning C4312: 'reinterpret_cast': conversion \" \"from", "\"ref\": \"libmysqlclient/8.0.25\", \"name\": \"libmysqlclient\", \"version\": \"8.0.25\", \"user\": None, \"channel\": None, \"severity_l\": \"WARN\", \"severity\":", "\"ninja/1.9.0\", \"name\": \"ninja\", \"version\": \"1.9.0\", \"channel\": None, \"user\": None, \"info\": \"This conanfile has", "| nfields = sscanf (line, \"%lx-%lx %9s %lx %9s %ld %s\",', \" |", "file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\", \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52): warning: extension used \" \"[-Wlanguage-extension-token]\", \"ZEXTERN z_off64_t ZEXPORT", "\"file\": \"src/port/pg_crc32c_sse42_choose.c\", \"line\": \"41\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"passing 'unsigned int [4]'", "{constexpYY}’\", \"category\": \"-Wdeprecated\", \"project\": None, \"hint\": \"\" ' 35 | %name-prefix \"constexpYY\"\\n' \"", "CMAKE_INSTALL_OLDINCLUDEDIR\\n\" \" MAKE_INSTALL_SBINDIR\", }, ], id=\"cmake\", ), pytest.param( [ { \"from\": \"Makefile.config\", \"info\":", "argument of type \" \"\\u2018long int *\\u2019, but argument 8 has type \\u2018long", "\"project\": None, \"hint\": \"\" \" 772 | #define PG_INT128_TYPE __int128\\n\" \" | ^~~~~~~~\",", "range checked by comparison on this line\", \"hint\": None, }, { \"context\": \"\",", "\"%lx-%lx %9s %lx %9s %ld %s\",', \" | ~~^\", \" | |\", \"", "\"warning\", \"info\": \"extension used\", \"category\": \"-Wlanguage-extension-token\", \"project\": None, \"hint\": \"\" \"ZEXTERN z_off64_t ZEXPORT", "\"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 772 | #define PG_INT128_TYPE __int128\\n\" \" |", "\"severity\": \"warning\", \"info\": \"ISO C does not support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\":", "None, \"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\": None, \"info\": \"\" \" Manually-specified", "Without Bison you will not be able to build PostgreSQL from Git nor\",", "}, { \"context\": \"\", \"file\": \"C:\\\\src\\\\bzlib.c\", \"line\": \"161\", \"column\": None, \"severity\": \"note\", \"category\":", "sscanf (line, \"%lx-%lx %9s %lx %9s %ld %s\",', \" | ~~^\", \" |", "PG_INT128_TYPE __int128\", \" | ^~~~~~~~\", \"configure: WARNING:\", \"*** Without Bison you will not", "\"info\": \"\" \"\\n*** Without Bison you will not be able to build PostgreSQL", "../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres.h:46,\\n\" \" from stringinfo.c:20:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\",", "\"CMake Warning at libmysql/authentication_ldap/CMakeLists.txt:30 (MESSAGE):\", \" Skipping the LDAP client authentication plugin\", \"\",", "{ \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": \"35\", \"column\": \"1-25\", \"severity\": \"warning\", \"info\": 'deprecated", "None, \"hint\": \"\" \" 772 | #define PG_INT128_TYPE __int128\\n\" \" | ^~~~~~~~\", },", "\"info\": \"requirement openssl/1.1.1m overridden by poco/1.11.1 to openssl/1.1.1l\", }, { \"channel\": None, \"info\":", "|\", \" | void*\", \"ninja/1.9.0 (test package): WARN: This conanfile has no build", "C prohibits argument conversion to \" \"union type [-Wpedantic]\", \" 1640 | G_DEFINE_BOXED_TYPE", "conversion to \" \"union type [-Wpedantic]\", \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\",", "size_t.\", \"\", ] dataset = [ pytest.param( [ { \"context\": \"src/main/src/Em_FilteringQmFu.c: In function", "G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\\n\" \" | ^~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"source_subfolder/src/tramp.c\",", "%9s %ld %s\",\\n' \" | ~~^\\n\" \" | |\\n\" \" | long int", "code '0x1'\", \"clang-cl: warning: /: 'linker' input unused [-Wunused-command-line-argument]\", \"In file included from", "\" | |\\n\" \" | void*\", }, { \"context\": \"\", \"file\": \"src/port/pg_crc32c_sse42_choose.c\", \"line\":", "\" from ../source_subfolder/atk/atkobject.h:27,\\n\" \" from ../source_subfolder/atk/atk.h:25,\\n\" \" from ../source_subfolder/atk/atktext.c:22:\\n\" \"../source_subfolder/atk/atktext.c: In function \"", "\"../source_subfolder/atk/atktext.c: In function \" \"\\u2018atk_text_range_get_type_once\\u2019:\\n\", \"file\": \"../source_subfolder/atk/atktext.c\", \"line\": \"1640\", \"column\": \"52\", \"severity\": \"warning\",", "use \" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\", ' strcat(mode2,\"b\"); /* binary mode", "\" ^\", }, { \"context\": \"/build/source_subfolder/bzip2.c: In function \" \"‘applySavedFileAttrToOutputFile’:\\n\", \"file\": \"/build/source_subfolder/bzip2.c\", \"line\":", "included from /package/include/glib-2.0/gobject/gobject.h:24,\\n\" \" from /package/include/glib-2.0/gobject/gbinding.h:29,\\n\" \" from /package/include/glib-2.0/glib-object.h:22,\\n\" \" from ../source_subfolder/atk/atkobject.h:27,\\n\" \"", "CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \" CMAKE_INSTALL_BINDIR\", \" CMAKE_INSTALL_DATAROOTDIR\", \" CMAKE_INSTALL_INCLUDEDIR\", \" CMAKE_INSTALL_LIBDIR\", \" CMAKE_INSTALL_LIBEXECDIR\", \" CMAKE_INSTALL_OLDINCLUDEDIR\",", "\"column\": None, \"severity\": \"warning\", \"info\": \"\" \"improperly calling multi-line macro `SETUP_STACK_POINTER' with 0", "\"severity_l\": \"WARNING\", \"user\": None, \"version\": None, }, { \"severity_l\": None, \"ref\": \"ninja/1.9.0\", \"name\":", "In member function \" \"\\u2018void Edge::Dump(const char*) const\\u2019:\\n\", \"file\": \"./src/graph.cc\", \"line\": \"409\", \"column\":", "translation unit [-Wpedantic]\", \" 284 | #endif\", \" | \", \"WARNING: this is", "the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"\", \"\", \"libjpeg/1.2.3: WARN: package is corrupted\", \"WARN:", "\"column\": \"2\", \"severity\": \"ERROR\", \"category\": None, \"info\": \"Problem encountered: Could not determine size", "\" Skipping the LDAP client authentication plugin\", \"\", \"\", \"In file included from", "None, }, { \"severity_l\": None, \"ref\": \"ninja/1.9.0\", \"name\": \"ninja\", \"version\": \"1.9.0\", \"channel\": None,", "\"35\", \"column\": \"1-25\", \"severity\": \"warning\", \"info\": 'deprecated directive: ‘%name-prefix \"constexpYY\"’, use ‘%define '", "fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\\n\" \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\",", "included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres.h:46,\\n\" \" from stringinfo.c:20:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\",", "None, }, { \"file\": \"C:\\\\source_subfolder\\\\bzlib.c\", \"line\": \"1418\", \"column\": \"10\", \"category\": \"C4996\", \"severity\": \"warning\",", "systemtap-sdt-dev\", \"line\": \"565\", \"severity\": None, }, { \"from\": \"configure\", \"line\": None, \"severity\": \"WARNING\",", "/* binary mode */', \" ^\", \"Makefile.config:565: No sys/sdt.h found, no SDT events", "8 \" \"has type ‘long unsigned int *’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\":", "\"warning\", \"info\": \"ISO C prohibits argument conversion to union type\", \"category\": \"-Wpedantic\", \"project\":", "<stdatomic.h> is not yet supported when compiling as C\", \" ^\", \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10): \"", "used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", }, { \"file\": \"cmake/ldap.cmake\", \"line\": \"158\",", "\" | long unsigned int *\", \"In file included from ../../src/include/postgres.h:47,\", \" from", "\"-W#pragma-messages\", \"project\": None, \"hint\": \" #pragma message (OPENSSL_VERSION_TEXT \" \"POCO_INTERNAL_OPENSSL_BUILD)\\n\" \" ^\", },", "disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\", \"project\": None, \"hint\":", "long int *\\n\" \" | %ld\\n\" \" 216 | &start, &end, perm, &offset,", "\"category\": \"-W#pragma-messages\", \"project\": None, \"hint\": \" #pragma message (OPENSSL_VERSION_TEXT \" \"POCO_INTERNAL_OPENSSL_BUILD)\\n\" \" ^\",", "None, \"info\": \"package is corrupted\", \"severity\": \"WARN\", \"severity_l\": None, }, { \"ref\": \"libmysqlclient/8.0.25\",", "\"/source_subfolder/src/constexp.y\", \"line\": \"35\", \"column\": \"1-25\", \"severity\": \"warning\", \"info\": 'deprecated directive: ‘%name-prefix \"constexpYY\"’, use", "char*) const\\u2019:\", \"./src/graph.cc:409:16: warning: format \\u2018%p\\u2019 expects argument of type \" \"\\u2018void*\\u2019, but", "\" | void*\", \"ninja/1.9.0 (test package): WARN: This conanfile has no build step\",", "different sign \" \"[-Wpointer-sign] [C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\", \"NMAKE : fatal error U1077: 'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : \"", "function \" \"‘Em_FilteringQmFu_processSensorSignals’:\\n\", \"file\": \"src/main/src/Em_FilteringQmFu.c\", \"line\": \"266\", \"column\": \"5\", \"severity\": \"warning\", \"info\": \"implicit", "used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"\", \"\", \"libjpeg/1.2.3: WARN: package is", "C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\", \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52): warning: extension used \" \"[-Wlanguage-extension-token]\", \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t,", "In member function \\u2018void Edge::Dump(const char*) const\\u2019:\", \"./src/graph.cc:409:16: warning: format \\u2018%p\\u2019 expects argument", "\"libmysqlclient/8.0.25\", \"name\": \"libmysqlclient\", \"version\": \"8.0.25\", \"user\": None, \"channel\": None, \"severity_l\": \"WARN\", \"severity\": None,", "'linker' input unused [-Wunused-command-line-argument]\", \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\", \"In file included from", "\"hint\": None, }, ], id=\"gnu\", ), pytest.param( [ { \"file\": \"/source_subfolder/common/socket_utils.cc\", \"line\": \"43\",", "| %define api.prefix {constexpYY}\", \"/source_subfolder/src/constexp.y: warning: fix-its can be applied. Rerun with option", "\" | |\", \" | long int *\", \" | %ld\", \" 216", "CMAKE_INSTALL_DATAROOTDIR\\n\" \" CMAKE_INSTALL_INCLUDEDIR\\n\" \" CMAKE_INSTALL_LIBDIR\\n\" \" CMAKE_INSTALL_LIBEXECDIR\\n\" \" CMAKE_INSTALL_OLDINCLUDEDIR\\n\" \" MAKE_INSTALL_SBINDIR\", }, ],", "file included from /package/include/glib-2.0/gobject/gobject.h:24,\\n\" \" from /package/include/glib-2.0/gobject/gbinding.h:29,\\n\" \" from /package/include/glib-2.0/glib-object.h:22,\\n\" \" from ../source_subfolder/atk/atkobject.h:27,\\n\"", "CMakeLists.txt:7 (include)\", }, { \"file\": \"libmysql/authentication_ldap/CMakeLists.txt\", \"line\": \"30\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"context\":", "from ../../src/include/postgres.h:47,\\n\" \" from rmtree.c:15:\\n\" \"rmtree.c: In function ‘rmtree’:\\n\" \"In file included from", "\" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"\", \"\", \"libjpeg/1.2.3: WARN: package is corrupted\", \"WARN: libmysqlclient/8.0.25: requirement openssl/1.1.1m", "\"warning\", \"info\": \"passing 'unsigned int [4]' to parameter of type 'int *' converts", "\" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\\n\" \" ^~~~~~\", }, { \"context\": \"\", \"file\": \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\", \"line\":", "\"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\" \" CMAKE_INSTALL_BINDIR\\n\" \" CMAKE_INSTALL_DATAROOTDIR\\n\" \" CMAKE_INSTALL_INCLUDEDIR\\n\" \" CMAKE_INSTALL_LIBDIR\\n\" \" CMAKE_INSTALL_LIBEXECDIR\\n\"", "| ~^\", \" | |\", \" | void*\", \"ninja/1.9.0 (test package): WARN: This", "\" CMAKE_INSTALL_LIBEXECDIR\", \" CMAKE_INSTALL_OLDINCLUDEDIR\", \" MAKE_INSTALL_SBINDIR\", \"\", \"\", \"source_subfolder/src/tramp.c:215:52: warning: format \\u2018%ld\\u2019 expects", "\"file\": \"C:\\\\source_subfolder\\\\bzlib.c\", \"line\": \"1418\", \"column\": \"10\", \"category\": \"C4996\", \"severity\": \"warning\", \"info\": \"'strcat': This", "\"-Wformat=\", \"project\": None, \"hint\": \"\" ' 215 | nfields = sscanf (line, \"%lx-%lx", "\"category\": \"C4312\", \"project\": None, \"hint\": None, }, { \"file\": \"C:\\\\source_subfolder\\\\bzlib.c\", \"line\": \"1418\", \"column\":", "on this line\", \"ebcdic.c:284: warning: ISO C forbids an empty translation unit [-Wpedantic]\",", "pointers to integer types with different sign\", \"category\": \"-Wpointer-sign\", \"project\": \"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\", \"hint\": None,", "\"from\": \"configure\", \"line\": None, \"severity\": \"WARNING\", \"info\": \"\" \"\\n*** Without Bison you will", "215 | nfields = sscanf (line, \"%lx-%lx %9s %lx %9s %ld %s\",', \"", "are using the official distribution of\" \"\\n*** PostgreSQL then you do not need", "\"user\": None, \"channel\": None, \"info\": \"package is corrupted\", \"severity\": \"WARN\", \"severity_l\": None, },", "\" | \", \"WARNING: this is important\", \"warning: Boost.Build engine (b2) is 4.8.0\",", "\"line\": \"41\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"passing 'unsigned int [4]' to parameter", "&inode, file);\", \" | ~~~~~~\", \" | |\", \" | long unsigned int", "\"{constexpYY}\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": None, \"column\": None, \"severity\": \"warning\",", "LDAP client authentication plugin\", \"\", \"\", \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\", \" from", "\"../../src/include/pg_config.h:772:24: warning: ISO C does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \"C:\\\\src\\\\bzlib.c(161) :", "\"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"\", \"\", \"libjpeg/1.2.3: WARN: package is corrupted\", \"WARN: libmysqlclient/8.0.25: requirement", "about this, because the Bison\" \"\\n*** output is pre-generated.)\", }, ], id=\"autotools\", ),", "\"%lx-%lx %9s %lx %9s %ld %s\",\\n' \" | ~~^\\n\" \" | |\\n\" \"", "Edge*\\u2019 [-Wformat=]\", ' 409 | printf(\"] 0x%p\\\\n\", this);', \" | ~^\", \" |", "CMAKE_INSTALL_BINDIR\", \" CMAKE_INSTALL_DATAROOTDIR\", \" CMAKE_INSTALL_INCLUDEDIR\", \" CMAKE_INSTALL_LIBDIR\", \" CMAKE_INSTALL_LIBEXECDIR\", \" CMAKE_INSTALL_OLDINCLUDEDIR\", \" MAKE_INSTALL_SBINDIR\",", "the LDAP client authentication plugin\", }, { \"context\": None, \"severity\": \"Warning\", \"file\": None,", "\"warning\", \"info\": \"\" \"ignoring return value of ‘fchown’, declared with attribute warn_unused_result\", \"category\":", "}, ], id=\"build\", ), ] @pytest.mark.parametrize(\"expected\", dataset) def test_warnings_regex(expected, request): compiler = request.node.callspec.id", "\"Warning\", \"function\": \"MESSAGE\", \"info\": \" Could not find LDAP\", \"context\": \"\" \"Call Stack", "message (OPENSSL_VERSION_TEXT \" \"POCO_INTERNAL_OPENSSL_BUILD)\\n\" \" ^\", }, { \"context\": \"\", \"file\": \"source_subfolder/meson.build\", \"line\":", "memset(&reicevedSignals, 0, sizeof(reicevedSignals));\\n\" \" ^~~~~~\", }, { \"context\": \"\", \"file\": \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\", \"line\": \"92\",", "please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"line\": \"565\", \"severity\": None, }, { \"from\":", "not used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\" \" CMAKE_INSTALL_BINDIR\\n\" \" CMAKE_INSTALL_DATAROOTDIR\\n\" \"", "input unused [-Wunused-command-line-argument]\", \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\", \"In file included from include\\\\crypto/evp.h:11:\",", "\" | void*\", }, { \"context\": \"\", \"file\": \"src/port/pg_crc32c_sse42_choose.c\", \"line\": \"41\", \"column\": \"10\",", "help for details.\", ' strcat(mode2,\"b\"); /* binary mode */', \" ^\", \"Makefile.config:565: No", "}, { \"ref\": \"libmysqlclient/8.0.25\", \"name\": \"libmysqlclient\", \"version\": \"8.0.25\", \"user\": None, \"channel\": None, \"severity_l\":", "from Git nor\" \"\\n*** change any of the parser definition files. You can", "do not need to worry about this, because the Bison\", \"*** output is", "\"warning\", \"info\": \"implicit declaration of function ‘memset’\", \"category\": \"-Wimplicit-function-declaration\", \"project\": None, \"hint\": \"\"", "\"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \" CMAKE_INSTALL_BINDIR\", \" CMAKE_INSTALL_DATAROOTDIR\", \" CMAKE_INSTALL_INCLUDEDIR\", \" CMAKE_INSTALL_LIBDIR\", \" CMAKE_INSTALL_LIBEXECDIR\",", "{ \"context\": \"\" \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\\n\" \" from /package/include/glib-2.0/gobject/gbinding.h:29,\\n\" \" from", "\"'reinterpret_cast': conversion from 'int' to 'HANDLE' of greater size\", \"category\": \"C4312\", \"project\": None,", "strcat(mode2,\"b\"); /* binary mode */', \" ^\", \"Makefile.config:565: No sys/sdt.h found, no SDT", "{ \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": None, \"column\": None, \"severity\": \"warning\", \"info\": \"fix-its", "\"file\": \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\", \"line\": \"35\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"OpenSSL 1.1.1l 24 Aug", "(line, \"%lx-%lx %9s %lx %9s %ld %s\",\\n' \" | ~~^\\n\" \" | |\\n\"", "Warning at libmysql/authentication_ldap/CMakeLists.txt:30 (MESSAGE):\", \" Skipping the LDAP client authentication plugin\", \"\", \"\",", "type 'int *' converts between pointers to integer types with different sign \"", "}, { \"context\": \"/build/source_subfolder/bzip2.c: In function \" \"‘applySavedFileAttrToOutputFile’:\\n\", \"file\": \"/build/source_subfolder/bzip2.c\", \"line\": \"1073\", \"column\":", "\"project\": None, }, { \"context\": \"\", \"file\": \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\", \"line\": \"35\", \"column\": \"10\", \"severity\":", "None, \"info\": \"<stdatomic.h> is not yet supported when compiling as C\", \"hint\": \"#error", "\\u2018long unsigned int *\\u2019 [-Wformat=]\", ' 215 | nfields = sscanf (line, \"%lx-%lx", "\"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\": None, \"info\": \" Manually-specified", "need to worry about this, because the Bison\" \"\\n*** output is pre-generated.)\", },", "\"C:\\\\src\\\\bzlib.c(161) : note: index 'blockSize100k' range checked by comparison on this line\", \"ebcdic.c:284:", "package): WARN: This conanfile has no build step\", \"src/port/pg_crc32c_sse42_choose.c(41,10): warning : passing 'unsigned", "\"In file included from include\\\\internal/refcount.h:21:\\n\" \"In file included from \" \"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\", \"file\": \"C:\\\\Program", "\"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\", \"info\": \"ISO C does not", "| printf(\"] 0x%p\\\\n\", this);', \" | ~^\", \" | |\", \" | void*\",", ");\", \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", \"/source_subfolder/src/constexp.y:35.1-25: warning: deprecated directive: ‘%name-prefix \" '\"constexpYY\"’, use ‘%define", "8 has type \\u2018long unsigned int *\\u2019 [-Wformat=]\", ' 215 | nfields =", "fileMetaInfo.st_gid );\\n\" \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": \"35\",", "../../src/include/postgres.h:47,\", \" from rmtree.c:15:\", \"rmtree.c: In function \\u2018rmtree\\u2019:\", \"In file included from ../../src/include/c.h:54,\",", "Bison\", \"*** output is pre-generated.)\", \"end\", \"CMake Warning at cmake/ldap.cmake:158 (MESSAGE):\", \" Could", "\"package is corrupted\", \"severity\": \"WARN\", \"severity_l\": None, }, { \"ref\": \"libmysqlclient/8.0.25\", \"name\": \"libmysqlclient\",", "\"context\": \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\\n\" \"In file included from include\\\\crypto/evp.h:11:\\n\" \"In file", "\" | |\\n\" \" | long int *\\n\" \" | %ld\\n\" \" 216", "\"NMAKE\", \"line\": None, \"column\": None, \"severity\": \"fatal error\", \"category\": \"U1077\", \"info\": \"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' :", "[ { \"context\": \"src/main/src/Em_FilteringQmFu.c: In function \" \"‘Em_FilteringQmFu_processSensorSignals’:\\n\", \"file\": \"src/main/src/Em_FilteringQmFu.c\", \"line\": \"266\", \"column\":", "type \" \"\\u2018long int *\\u2019, but argument 8 has type \\u2018long unsigned int", "| ^~~~~~~~\", }, { \"context\": \"\" \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\\n\" \" from", "\"warning\", \"info\": \"/: 'linker' input unused\", \"category\": \"-Wunused-command-line-argument\", \"line\": None, \"column\": None, \"project\":", "\" | ~~~~~~\", \" | |\", \" | long unsigned int *\", \"In", "no SDT events are defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"line\": \"565\",", "| &start, &end, perm, &offset, dev, &inode, file);\", \" | ~~~~~~\", \" |", "step\", \"severity\": \"WARN\", }, ], id=\"conan\", ), pytest.param( [ { \"severity\": \"warning\", \"info\":", "translation unit\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \" 284 | #endif\\n | \",", "\"./src/graph.cc:409:16: warning: format \\u2018%p\\u2019 expects argument of type \" \"\\u2018void*\\u2019, but argument 2", "\"/build/source_subfolder/bzip2.c: In function \" \"‘applySavedFileAttrToOutputFile’:\\n\", \"file\": \"/build/source_subfolder/bzip2.c\", \"line\": \"1073\", \"column\": \"11\", \"severity\": \"warning\",", "(If you are using the official distribution of\", \"*** PostgreSQL then you do", "you do not need to worry about this, because the Bison\", \"*** output", "( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\\n\" \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\":", "*\", \"In file included from ../../src/include/postgres.h:47,\", \" from rmtree.c:15:\", \"rmtree.c: In function \\u2018rmtree\\u2019:\",", "from conmon.warnings import Regex output = [ \"src/main/src/Em_FilteringQmFu.c: In function \" \"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\", \"src/main/src/Em_FilteringQmFu.c:266:5:", "| long int *\", \" | %ld\", \" 216 | &start, &end, perm,", "1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\\n\" \" | ^~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\",", "OpenSSL 1.1.1l 24 Aug 2021 [-W#pragma-messages]\", \" #pragma message (OPENSSL_VERSION_TEXT POCO_INTERNAL_OPENSSL_BUILD)\", \" ^\",", "\" \"return code '0x1'\", \"clang-cl: warning: /: 'linker' input unused [-Wunused-command-line-argument]\", \"In file", "\"info\": \"\" \"ignoring return value of ‘fchown’, declared with attribute warn_unused_result\", \"category\": \"-Wunused-result\",", "please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"CMake Warning:\", \" Manually-specified variables were not", "attribute warn_unused_result [-Wunused-result]\", \" 1073 | (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\",", "\"context\": \"src/main/src/Em_FilteringQmFu.c: In function \" \"‘Em_FilteringQmFu_processSensorSignals’:\\n\", \"file\": \"src/main/src/Em_FilteringQmFu.c\", \"line\": \"266\", \"column\": \"5\", \"severity\":", "\"\", \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\", \" from /package/include/glib-2.0/gobject/gbinding.h:29,\", \" from /package/include/glib-2.0/glib-object.h:22,\", \"", "\"project\": None, \"hint\": \"\" \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\\n\" \" ^\",", "not support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 772 |", "\"\\n*** PostgreSQL then you do not need to worry about this, because the", "\"This conanfile has no build step\", \"severity\": \"WARN\", }, ], id=\"conan\", ), pytest.param(", "None, \"info\": \" Manually-specified variables were not used by the project:\\n\" \"\\n\" \"", "None, \"hint\": \"\" ' 215 | nfields = sscanf (line, \"%lx-%lx %9s %lx", "\"info\": \"Boost.Build engine (b2) is 4.8.0\", }, ], id=\"build\", ), ] @pytest.mark.parametrize(\"expected\", dataset)", "\"improperly calling multi-line macro `SETUP_STACK_POINTER' with 0 parameters\", \"category\": \"-w+macro-params-legacy\", \"project\": None, \"hint\":", "\"file\": \"ebcdic.c\", \"line\": \"284\", \"column\": None, \"severity\": \"warning\", \"info\": \"ISO C forbids an", "\"'--update'. [-Wother]\", \"/source_subfolder/common/socket_utils.cc(43): warning C4312: 'reinterpret_cast': conversion \" \"from 'int' to 'HANDLE' of", "then you do not need to worry about this, because the Bison\", \"***", "See online help for details.\", ' strcat(mode2,\"b\"); /* binary mode */', \" ^\",", "], id=\"cmake\", ), pytest.param( [ { \"from\": \"Makefile.config\", \"info\": \"No sys/sdt.h found, no", "\"hint\": \"\" \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\\n\" \" ^\", }, {", "' strcat(mode2,\"b\"); /* binary mode */\\n ^', }, { \"file\": \"NMAKE\", \"line\": None,", "\"project\": None, \"hint\": \"\" ' 409 | printf(\"] 0x%p\\\\n\", this);\\n' \" | ~^\\n\"", "\"\", ] dataset = [ pytest.param( [ { \"context\": \"src/main/src/Em_FilteringQmFu.c: In function \"", "warning: ISO C forbids an empty translation unit [-Wpedantic]\", \" 284 | #endif\",", "| long unsigned int *\", }, { \"context\": \"\" \"In file included from", "as C\", \"hint\": \"#error <stdatomic.h> is not yet supported when compiling as C\\n\"", "\"1418\", \"column\": \"10\", \"category\": \"C4996\", \"severity\": \"warning\", \"info\": \"'strcat': This function or variable", "To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\", \"project\": None,", "CMAKE_INSTALL_BINDIR\\n\" \" CMAKE_INSTALL_DATAROOTDIR\\n\" \" CMAKE_INSTALL_INCLUDEDIR\\n\" \" CMAKE_INSTALL_LIBDIR\\n\" \" CMAKE_INSTALL_LIBEXECDIR\\n\" \" CMAKE_INSTALL_OLDINCLUDEDIR\\n\" \" MAKE_INSTALL_SBINDIR\",", "None, \"severity_l\": \"WARN\", \"severity\": None, \"info\": \"requirement openssl/1.1.1m overridden by poco/1.11.1 to openssl/1.1.1l\",", "from /package/include/glib-2.0/gobject/gbinding.h:29,\", \" from /package/include/glib-2.0/glib-object.h:22,\", \" from ../source_subfolder/atk/atkobject.h:27,\", \" from ../source_subfolder/atk/atk.h:25,\", \" from", "Could not find LDAP\", \"context\": \"\" \"Call Stack (most recent call first):\\n\" \"", "(MESSAGE):\", \" Could not find LDAP\", \"Call Stack (most recent call first):\", \"", "not be able to build PostgreSQL from Git nor\" \"\\n*** change any of", "OF((gzFile, z_off64_t, int));\", \" ^\", \"/build/source_subfolder/bzip2.c: In function ‘applySavedFileAttrToOutputFile’:\", \"/build/source_subfolder/bzip2.c:1073:11: warning: ignoring return", "\" CMAKE_INSTALL_OLDINCLUDEDIR\\n\" \" MAKE_INSTALL_SBINDIR\", }, ], id=\"cmake\", ), pytest.param( [ { \"from\": \"Makefile.config\",", "/package/include/glib-2.0/glib-object.h:22,\\n\" \" from ../source_subfolder/atk/atkobject.h:27,\\n\" \" from ../source_subfolder/atk/atk.h:25,\\n\" \" from ../source_subfolder/atk/atktext.c:22:\\n\" \"../source_subfolder/atk/atktext.c: In function", "has type \\u2018const Edge*\\u2019 [-Wformat=]\", ' 409 | printf(\"] 0x%p\\\\n\", this);', \" |", "\"info\": \"implicit declaration of function ‘memset’\", \"category\": \"-Wimplicit-function-declaration\", \"project\": None, \"hint\": \"\" \"", "types with different sign\", \"category\": \"-Wpointer-sign\", \"project\": \"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\", \"hint\": None, }, { \"context\":", "\"15\", \"column\": \"2\", \"severity\": \"error\", \"category\": None, \"info\": \"<stdatomic.h> is not yet supported", "is not yet supported when compiling as C\", \"hint\": \"#error <stdatomic.h> is not", "%ld\\n\" \" 216 | &start, &end, perm, &offset, dev, &inode, file);\\n\" \" |", "size_t.\", \"project\": None, \"hint\": None, }, ], id=\"gnu\", ), pytest.param( [ { \"file\":", "\"file\": \"src/main/src/Em_FilteringQmFu.c\", \"line\": \"266\", \"column\": \"5\", \"severity\": \"warning\", \"info\": \"implicit declaration of function", "\"\\n*** output is pre-generated.)\", }, ], id=\"autotools\", ), pytest.param( [ { \"ref\": \"libjpeg/1.2.3\",", "\" \"{constexpYY}\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": None, \"column\": None, \"severity\":", "| G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\", \" | ^~~~~~~~~~~~~~~~~~~\", \"CMake Warning:\", \" Manually-specified variables", "by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"\", \"\", \"libjpeg/1.2.3: WARN: package is corrupted\",", "file included from include\\\\crypto/evp.h:11:\", \"In file included from include\\\\internal/refcount.h:21:\", \"In file included from", "forbids an empty translation unit\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \" 284 |", "[-Wimplicit-function-declaration]\", \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\", \" ^~~~~~\", \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92: warning: improperly calling \" \"multi-line", "\"file\": \"source_subfolder/src/tramp.c\", \"line\": \"215\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"format ‘%ld’ expects argument", "\"context\": \"\", \"file\": \"src/port/pg_crc32c_sse42_choose.c\", \"line\": \"41\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"passing 'unsigned", "with option \" \"'--update'. [-Wother]\", \"/source_subfolder/common/socket_utils.cc(43): warning C4312: 'reinterpret_cast': conversion \" \"from 'int'", "\"92\", \"column\": None, \"severity\": \"warning\", \"info\": \"\" \"improperly calling multi-line macro `SETUP_STACK_POINTER' with", "may be unsafe. Consider using \" \"strcat_s instead. To disable deprecation, use \"", "conmon.warnings import Regex output = [ \"src/main/src/Em_FilteringQmFu.c: In function \" \"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\", \"src/main/src/Em_FilteringQmFu.c:266:5: warning:", "definition files. You can obtain Bison from\", \"*** a GNU mirror site. (If", "argument of type \" \"\\u2018void*\\u2019, but argument 2 has type \\u2018const Edge*\\u2019 [-Wformat=]\",", "\"fatal error\", \"category\": \"U1077\", \"info\": \"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : return \" \"code '0x1'\", \"project\": None,", "[ pytest.param( [ { \"context\": \"src/main/src/Em_FilteringQmFu.c: In function \" \"‘Em_FilteringQmFu_processSensorSignals’:\\n\", \"file\": \"src/main/src/Em_FilteringQmFu.c\", \"line\":", "CMAKE_INSTALL_LIBDIR\", \" CMAKE_INSTALL_LIBEXECDIR\", \" CMAKE_INSTALL_OLDINCLUDEDIR\", \" MAKE_INSTALL_SBINDIR\", \"\", \"\", \"source_subfolder/src/tramp.c:215:52: warning: format \\u2018%ld\\u2019", "CMAKE_INSTALL_LIBDIR\\n\" \" CMAKE_INSTALL_LIBEXECDIR\\n\" \" CMAKE_INSTALL_OLDINCLUDEDIR\\n\" \" MAKE_INSTALL_SBINDIR\", }, ], id=\"cmake\", ), pytest.param( [", "\"from\": \"Makefile.config\", \"info\": \"No sys/sdt.h found, no SDT events are defined, please install", "\"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : return \" \"code '0x1'\", \"project\": None, \"hint\": None, }, ], id=\"msvc\",", "official distribution of\" \"\\n*** PostgreSQL then you do not need to worry about", "[-Wother]\", \"/source_subfolder/common/socket_utils.cc(43): warning C4312: 'reinterpret_cast': conversion \" \"from 'int' to 'HANDLE' of greater", "C4996: 'strcat': This function or variable \" \"may be unsafe. Consider using strcat_s", "an empty translation unit\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \" 284 | #endif\\n", "coding: UTF-8 -*- import re import pytest from conmon.warnings import Regex output =", "has no build step\", \"src/port/pg_crc32c_sse42_choose.c(41,10): warning : passing 'unsigned int [4]' to \"", "but argument 8 has type \\u2018long unsigned int *\\u2019 [-Wformat=]\", ' 215 |", "'0x1'\", \"clang-cl: warning: /: 'linker' input unused [-Wunused-command-line-argument]\", \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\",", "from stringinfo.c:20:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\", \"info\": \"ISO C", "call first):\\n\" \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\\n\" \" CMakeLists.txt:7 (include)\", }, { \"file\": \"libmysql/authentication_ldap/CMakeLists.txt\", \"line\":", "\"context\": \"\" \"Call Stack (most recent call first):\\n\" \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\\n\" \" CMakeLists.txt:7", "{ \"from\": \"Makefile.config\", \"info\": \"No sys/sdt.h found, no SDT events are defined, please", "None, \"user\": None, \"info\": \"This conanfile has no build step\", \"severity\": \"WARN\", },", "\"project\": None, \"info\": \"index 'blockSize100k' range checked by comparison on this line\", \"hint\":", "] dataset = [ pytest.param( [ { \"context\": \"src/main/src/Em_FilteringQmFu.c: In function \" \"‘Em_FilteringQmFu_processSensorSignals’:\\n\",", "\"line\": \"146\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"extension used\", \"category\": \"-Wlanguage-extension-token\", \"project\": None,", "\"column\": \"52\", \"severity\": \"warning\", \"info\": \"extension used\", \"category\": \"-Wlanguage-extension-token\", \"project\": None, \"hint\": \"\"", "\" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", \"/source_subfolder/src/constexp.y:35.1-25: warning: deprecated directive: ‘%name-prefix \" '\"constexpYY\"’, use ‘%define api.prefix", "24 Aug 2021\", \"category\": \"-W#pragma-messages\", \"project\": None, \"hint\": \" #pragma message (OPENSSL_VERSION_TEXT \"", "\"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\", \"file\": \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h\", \"line\": \"15\", \"column\": \"2\", \"severity\": \"error\",", "of type ‘long int *’, but argument 8 \" \"has type ‘long unsigned", "is 4.8.0\", \"./src/graph.cc: In member function \\u2018void Edge::Dump(const char*) const\\u2019:\", \"./src/graph.cc:409:16: warning: format", "\"line\": \"1418\", \"column\": \"10\", \"category\": \"C4996\", \"severity\": \"warning\", \"info\": \"'strcat': This function or", "\"hint\": ' strcat(mode2,\"b\"); /* binary mode */\\n ^', }, { \"file\": \"NMAKE\", \"line\":", "[-Wunused-result]\", \" 1073 | (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\", \" |", "\"project\": None, \"hint\": None, }, { \"file\": \"C:\\\\source_subfolder\\\\bzlib.c\", \"line\": \"1418\", \"column\": \"10\", \"category\":", "import re import pytest from conmon.warnings import Regex output = [ \"src/main/src/Em_FilteringQmFu.c: In", "any of the parser definition files. You can obtain Bison from\", \"*** a", "of the parser definition files. You can obtain Bison from\" \"\\n*** a GNU", "__int128\\n\" \" | ^~~~~~~~\", }, { \"context\": \"\" \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\\n\"", "authentication plugin\", }, { \"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\":", "(x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h\", \"line\": \"15\", \"column\": \"2\", \"severity\": \"error\", \"category\": None, \"info\": \"<stdatomic.h>", "‘void*’, \" \"but argument 2 has type ‘const Edge*’\", \"category\": \"-Wformat=\", \"project\": None,", "\"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": None, \"column\": None, \"severity\": \"warning\", \"info\": \"fix-its can", "change any of the parser definition files. You can obtain Bison from\", \"***", "\"*** Without Bison you will not be able to build PostgreSQL from Git", "None, }, { \"context\": \"\", \"file\": \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\", \"line\": \"35\", \"column\": \"10\", \"severity\": \"warning\",", "line\", \"hint\": None, }, { \"context\": \"\", \"file\": \"ebcdic.c\", \"line\": \"284\", \"column\": None,", "| |\", \" | long unsigned int *\", \"In file included from ../../src/include/postgres.h:47,\",", "\"info\": \"fix-its can be applied. Rerun with option '--update'.\", \"category\": \"-Wother\", \"project\": None,", "\"severity\": \"warning\", \"info\": \"/: 'linker' input unused\", \"category\": \"-Wunused-command-line-argument\", \"line\": None, \"column\": None,", "'unsigned int [4]' to \" \"parameter of type 'int *' converts between pointers", "PostgreSQL then you do not need to worry about this, because the Bison\",", "None, \"info\": \"index 'blockSize100k' range checked by comparison on this line\", \"hint\": None,", "Aug 2021 [-W#pragma-messages]\", \" #pragma message (OPENSSL_VERSION_TEXT POCO_INTERNAL_OPENSSL_BUILD)\", \" ^\", \"source_subfolder/meson.build:1559:2: ERROR: Problem", "^~~~~~\", }, { \"context\": \"\", \"file\": \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\", \"line\": \"92\", \"column\": None, \"severity\": \"warning\",", "type 'int *' converts \" \"between pointers to integer types with different sign\",", "\"line\": None, \"severity\": \"WARNING\", \"info\": \"\" \"\\n*** Without Bison you will not be", "\" 772 | #define PG_INT128_TYPE __int128\\n\" \" | ^~~~~~~~\", }, { \"context\": \"\"", "\" \"may be unsafe. Consider using strcat_s instead. To disable deprecation, use \"", "../source_subfolder/atk/atktext.c:22:\\n\" \"../source_subfolder/atk/atktext.c: In function \" \"\\u2018atk_text_range_get_type_once\\u2019:\\n\", \"file\": \"../source_subfolder/atk/atktext.c\", \"line\": \"1640\", \"column\": \"52\", \"severity\":", "\"284\", \"column\": None, \"severity\": \"warning\", \"info\": \"ISO C forbids an empty translation unit\",", "binary mode */', \" ^\", \"Makefile.config:565: No sys/sdt.h found, no SDT events are", "| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": \"35\", \"column\": \"1-25\", \"severity\":", "z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\", \" ^\", \"/build/source_subfolder/bzip2.c: In function ‘applySavedFileAttrToOutputFile’:\", \"/build/source_subfolder/bzip2.c:1073:11:", "has no build step\", \"severity\": \"WARN\", }, ], id=\"conan\", ), pytest.param( [ {", "of type \" \"\\u2018void*\\u2019, but argument 2 has type \\u2018const Edge*\\u2019 [-Wformat=]\", '", "\"CMake Warning at cmake/ldap.cmake:158 (MESSAGE):\", \" Could not find LDAP\", \"Call Stack (most", "‘rmtree’:\\n\" \"In file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres.h:46,\\n\" \" from stringinfo.c:20:\\n\", \"file\":", "\"column\": None, \"severity\": \"warning\", \"info\": \"fix-its can be applied. Rerun with option '--update'.\",", "Manually-specified variables were not used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", }, {", "%s\",\\n' \" | ~~^\\n\" \" | |\\n\" \" | long int *\\n\" \"", "\\u2018atk_text_range_get_type_once\\u2019:\", \"../source_subfolder/atk/atktext.c:1640:52: warning: ISO C prohibits argument conversion to \" \"union type [-Wpedantic]\",", "with 0 parameters [-w+macro-params-legacy]\", \"some text\", \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\", \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52): warning:", "None, }, { \"context\": \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\", \"file\": \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\", \"line\": \"146\",", "\"35\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"OpenSSL 1.1.1l 24 Aug 2021\", \"category\": \"-W#pragma-messages\",", "\"constexpYY\"', \" | ^~~~~~~~~~~~~~~~~~~~~~~~~\" \" | %define api.prefix {constexpYY}\", \"/source_subfolder/src/constexp.y: warning: fix-its can", "warning C4312: 'reinterpret_cast': conversion \" \"from 'int' to 'HANDLE' of greater size\", \"C:\\\\source_subfolder\\\\bzlib.c(1418,10):", "this, because the Bison\", \"*** output is pre-generated.)\", \"end\", \"CMake Warning at cmake/ldap.cmake:158", "^~~~~~~~~~~~~~~~~~~~~~~~~\" \" | %define api.prefix {constexpYY}\", \"/source_subfolder/src/constexp.y: warning: fix-its can be applied. Rerun", "package is corrupted\", \"WARN: libmysqlclient/8.0.25: requirement openssl/1.1.1m \" \"overridden by poco/1.11.1 to openssl/1.1.1l\",", "‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 772 | #define PG_INT128_TYPE", "\"ref\": \"libjpeg/1.2.3\", \"name\": \"libjpeg\", \"version\": \"1.2.3\", \"user\": None, \"channel\": None, \"info\": \"package is", "24 Aug 2021 [-W#pragma-messages]\", \" #pragma message (OPENSSL_VERSION_TEXT POCO_INTERNAL_OPENSSL_BUILD)\", \" ^\", \"source_subfolder/meson.build:1559:2: ERROR:", "\"1073\", \"column\": \"11\", \"severity\": \"warning\", \"info\": \"\" \"ignoring return value of ‘fchown’, declared", "\"\", \"file\": \"clang-cl\", \"severity\": \"warning\", \"info\": \"/: 'linker' input unused\", \"category\": \"-Wunused-command-line-argument\", \"line\":", "None, }, ], id=\"msvc\", ), pytest.param( [ { \"context\": None, \"severity\": \"Warning\", \"file\":", "function ‘applySavedFileAttrToOutputFile’:\", \"/build/source_subfolder/bzip2.c:1073:11: warning: ignoring return value of ‘fchown’, declared \" \"with attribute", "nor\", \"*** change any of the parser definition files. You can obtain Bison", "instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\", '", "\"266\", \"column\": \"5\", \"severity\": \"warning\", \"info\": \"implicit declaration of function ‘memset’\", \"category\": \"-Wimplicit-function-declaration\",", "0, sizeof(reicevedSignals));\", \" ^~~~~~\", \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92: warning: improperly calling \" \"multi-line macro `SETUP_STACK_POINTER' with", "of type 'int *' converts between pointers to integer types with different sign", "\"error\", \"category\": None, \"info\": \"<stdatomic.h> is not yet supported when compiling as C\",", "\"severity_l\": None, \"ref\": \"ninja/1.9.0\", \"name\": \"ninja\", \"version\": \"1.9.0\", \"channel\": None, \"user\": None, \"info\":", "\" MAKE_INSTALL_SBINDIR\", \"\", \"\", \"source_subfolder/src/tramp.c:215:52: warning: format \\u2018%ld\\u2019 expects argument of type \"", "not yet supported when compiling as C\", \"#error <stdatomic.h> is not yet supported", "‘fchown’, declared \" \"with attribute warn_unused_result [-Wunused-result]\", \" 1073 | (void) fchown (", "| ~~~~~~\", \" | |\", \" | long unsigned int *\", \"In file", "/package/include/glib-2.0/gobject/gbinding.h:29,\\n\" \" from /package/include/glib-2.0/glib-object.h:22,\\n\" \" from ../source_subfolder/atk/atkobject.h:27,\\n\" \" from ../source_subfolder/atk/atk.h:25,\\n\" \" from ../source_subfolder/atk/atktext.c:22:\\n\"", "\"file\": \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\", \"line\": \"146\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"extension used\", \"category\": \"-Wlanguage-extension-token\",", "{constexpYY}’ [-Wdeprecated]', ' 35 | %name-prefix \"constexpYY\"', \" | ^~~~~~~~~~~~~~~~~~~~~~~~~\" \" | %define", "\"context\": \"/build/source_subfolder/bzip2.c: In function \" \"‘applySavedFileAttrToOutputFile’:\\n\", \"file\": \"/build/source_subfolder/bzip2.c\", \"line\": \"1073\", \"column\": \"11\", \"severity\":", "\"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": \"35\", \"column\": \"1-25\", \"severity\": \"warning\", \"info\": 'deprecated directive: ‘%name-prefix", "\"file\": \"libmysql/authentication_ldap/CMakeLists.txt\", \"line\": \"30\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"context\": None, \"info\": \" Skipping", "\"context\": None, \"info\": \" Skipping the LDAP client authentication plugin\", }, { \"context\":", "*\\n\" \" | %ld\\n\" \" 216 | &start, &end, perm, &offset, dev, &inode,", "| ^~~~~~~~~~~~~~~~~~~~~~~~~\" \" | %define api.prefix {constexpYY}\", \"/source_subfolder/src/constexp.y: warning: fix-its can be applied.", "| G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\\n\" \" | ^~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\":", "| ~^\\n\" \" | |\\n\" \" | void*\", }, { \"context\": \"\", \"file\":", "\"category\": None, \"info\": \"<stdatomic.h> is not yet supported when compiling as C\", \"hint\":", "\"project\": None, \"hint\": \"\" ' 215 | nfields = sscanf (line, \"%lx-%lx %9s", "\"line\": None, \"column\": None, \"severity\": \"warning\", \"info\": \"fix-its can be applied. Rerun with", "api.prefix {constexpYY}’ [-Wdeprecated]', ' 35 | %name-prefix \"constexpYY\"', \" | ^~~~~~~~~~~~~~~~~~~~~~~~~\" \" |", "\"*** output is pre-generated.)\", \"end\", \"CMake Warning at cmake/ldap.cmake:158 (MESSAGE):\", \" Could not", "None, \"ref\": None, \"severity\": None, \"severity_l\": \"WARNING\", \"user\": None, \"version\": None, }, {", "\"severity\": \"warning\", \"info\": \"'reinterpret_cast': conversion from 'int' to 'HANDLE' of greater size\", \"category\":", "from ../../src/include/postgres.h:47,\", \" from rmtree.c:15:\", \"rmtree.c: In function \\u2018rmtree\\u2019:\", \"In file included from", "\"severity\": \"warning\", \"info\": \"ISO C prohibits argument conversion to union type\", \"category\": \"-Wpedantic\",", "int *\\u2019 [-Wformat=]\", ' 215 | nfields = sscanf (line, \"%lx-%lx %9s %lx", "step\", \"src/port/pg_crc32c_sse42_choose.c(41,10): warning : passing 'unsigned int [4]' to \" \"parameter of type", "%ld %s\",\\n' \" | ~~^\\n\" \" | |\\n\" \" | long int *\\n\"", "types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": None, }, { \"context\": \"\", \"file\": \"C:\\\\src\\\\bzlib.c\",", "function \" \"‘applySavedFileAttrToOutputFile’:\\n\", \"file\": \"/build/source_subfolder/bzip2.c\", \"line\": \"1073\", \"column\": \"11\", \"severity\": \"warning\", \"info\": \"\"", "project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\" \" CMAKE_INSTALL_BINDIR\\n\" \" CMAKE_INSTALL_DATAROOTDIR\\n\" \" CMAKE_INSTALL_INCLUDEDIR\\n\" \" CMAKE_INSTALL_LIBDIR\\n\" \"", "type \\u2018const Edge*\\u2019 [-Wformat=]\", ' 409 | printf(\"] 0x%p\\\\n\", this);', \" | ~^\",", "argument 2 has type ‘const Edge*’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" '", "\"-Wpedantic\", \"project\": None, \"hint\": None, }, { \"context\": \"\", \"file\": \"C:\\\\src\\\\bzlib.c\", \"line\": \"161\",", "1.1.1l 24 Aug 2021\", \"category\": \"-W#pragma-messages\", \"project\": None, \"hint\": \" #pragma message (OPENSSL_VERSION_TEXT", "CMAKE_INSTALL_INCLUDEDIR\", \" CMAKE_INSTALL_LIBDIR\", \" CMAKE_INSTALL_LIBEXECDIR\", \" CMAKE_INSTALL_OLDINCLUDEDIR\", \" MAKE_INSTALL_SBINDIR\", \"\", \"\", \"source_subfolder/src/tramp.c:215:52: warning:", "}, { \"file\": \"libmysql/authentication_ldap/CMakeLists.txt\", \"line\": \"30\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"context\": None, \"info\":", "comparison on this line\", \"ebcdic.c:284: warning: ISO C forbids an empty translation unit", "\" CMAKE_INSTALL_DATAROOTDIR\\n\" \" CMAKE_INSTALL_INCLUDEDIR\\n\" \" CMAKE_INSTALL_LIBDIR\\n\" \" CMAKE_INSTALL_LIBEXECDIR\\n\" \" CMAKE_INSTALL_OLDINCLUDEDIR\\n\" \" MAKE_INSTALL_SBINDIR\", },", "\" 1073 | (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\", \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\",", "the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", }, { \"file\": \"cmake/ldap.cmake\", \"line\": \"158\", \"severity\": \"Warning\",", "4.8.0\", }, ], id=\"build\", ), ] @pytest.mark.parametrize(\"expected\", dataset) def test_warnings_regex(expected, request): compiler =", "\"project\": None, \"hint\": None, }, { \"context\": \"\" \"In file included from ../../src/include/c.h:54,\\n\"", "= [ \"src/main/src/Em_FilteringQmFu.c: In function \" \"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\", \"src/main/src/Em_FilteringQmFu.c:266:5: warning: implicit declaration of function", "comparison on this line\", \"hint\": None, }, { \"context\": \"\", \"file\": \"ebcdic.c\", \"line\":", "\"*** PostgreSQL then you do not need to worry about this, because the", "any of the parser definition files. You can obtain Bison from\" \"\\n*** a", "\"ISO C does not support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": None,", "as C\\n\" \" ^\", \"project\": None, }, { \"context\": \"\", \"file\": \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\", \"line\":", "this);', \" | ~^\", \" | |\", \" | void*\", \"ninja/1.9.0 (test package):", "None, \"severity\": \"warning\", \"info\": \"ISO C forbids an empty translation unit\", \"category\": \"-Wpedantic\",", "35 | %name-prefix \"constexpYY\"', \" | ^~~~~~~~~~~~~~~~~~~~~~~~~\" \" | %define api.prefix {constexpYY}\", \"/source_subfolder/src/constexp.y:", "\"/source_subfolder/src/constexp.y: warning: fix-its can be applied. Rerun with option \" \"'--update'. [-Wother]\", \"/source_subfolder/common/socket_utils.cc(43):", "C does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \"C:\\\\src\\\\bzlib.c(161) : note: index 'blockSize100k'", "#define PG_INT128_TYPE __int128\\n\" \" | ^~~~~~~~\", }, { \"context\": \"\" \"In file included", "import pytest from conmon.warnings import Regex output = [ \"src/main/src/Em_FilteringQmFu.c: In function \"", "| |\\n\" \" | long int *\\n\" \" | %ld\\n\" \" 216 |", "\" | long int *\", \" | %ld\", \" 216 | &start, &end,", "\"warning\", \"info\": 'deprecated directive: ‘%name-prefix \"constexpYY\"’, use ‘%define ' \"api.prefix {constexpYY}’\", \"category\": \"-Wdeprecated\",", "{ \"context\": \"\", \"file\": \"source_subfolder/src/tramp.c\", \"line\": \"215\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"format", "| nfields = sscanf (line, \"%lx-%lx %9s %lx %9s %ld %s\",\\n' \" |", "[-Wpedantic]\", \"C:\\\\src\\\\bzlib.c(161) : note: index 'blockSize100k' range checked by comparison on this line\",", "\"project\": None, \"hint\": \" 284 | #endif\\n | \", }, { \"context\": \"./src/graph.cc:", "compiling as C\\n\" \" ^\", \"project\": None, }, { \"context\": \"\", \"file\": \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\",", "poco/1.11.1 to openssl/1.1.1l\", \"In file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres_fe.h:25,\", \" from", "\" \"\\u2018long int *\\u2019, but argument 8 has type \\u2018long unsigned int *\\u2019", "\"column\": None, \"severity\": \"note\", \"category\": None, \"project\": None, \"info\": \"index 'blockSize100k' range checked", "stringinfo.c:20:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \"C:\\\\src\\\\bzlib.c(161)", "perm, &offset, dev, &inode, file);\\n\" \" | ~~~~~~\\n\" \" | |\\n\" \" |", "\"context\": \"\", \"file\": \"C:\\\\src\\\\bzlib.c\", \"line\": \"161\", \"column\": None, \"severity\": \"note\", \"category\": None, \"project\":", "\"libmysql/authentication_ldap/CMakeLists.txt\", \"line\": \"30\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"context\": None, \"info\": \" Skipping the", "This function or variable \" \"may be unsafe. Consider using strcat_s instead. To", "LDAP\", \"Call Stack (most recent call first):\", \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\", \" CMakeLists.txt:7 (include)\",", "\"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\", \"hint\": None, }, { \"context\": \"\", \"file\": \"clang-cl\", \"severity\": \"warning\", \"info\": \"/:", "\"\", \"file\": \"source_subfolder/src/tramp.c\", \"line\": \"215\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"format ‘%ld’ expects", ": \" \"return code '0x1'\", \"clang-cl: warning: /: 'linker' input unused [-Wunused-command-line-argument]\", \"In", "warning: implicit declaration of function \" \"\\u2018memset\\u2019 [-Wimplicit-function-declaration]\", \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\", \"", "\"channel\": None, \"info\": \"package is corrupted\", \"severity\": \"WARN\", \"severity_l\": None, }, { \"ref\":", "can obtain Bison from\" \"\\n*** a GNU mirror site. (If you are using", "macro `SETUP_STACK_POINTER' with 0 parameters [-w+macro-params-legacy]\", \"some text\", \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\",", "is corrupted\", \"severity\": \"WARN\", \"severity_l\": None, }, { \"ref\": \"libmysqlclient/8.0.25\", \"name\": \"libmysqlclient\", \"version\":", "\"severity\": \"ERROR\", \"category\": None, \"info\": \"Problem encountered: Could not determine size of size_t.\",", "None, \"channel\": None, \"severity_l\": \"WARN\", \"severity\": None, \"info\": \"requirement openssl/1.1.1m overridden by poco/1.11.1", "disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\", ' strcat(mode2,\"b\"); /*", "libmysqlclient/8.0.25: requirement openssl/1.1.1m \" \"overridden by poco/1.11.1 to openssl/1.1.1l\", \"In file included from", "\"configure\", \"line\": None, \"severity\": \"WARNING\", \"info\": \"\" \"\\n*** Without Bison you will not", "\" from rmtree.c:15:\", \"rmtree.c: In function \\u2018rmtree\\u2019:\", \"In file included from ../../src/include/c.h:54,\", \"", "'--update'.\", \"category\": \"-Wother\", \"project\": None, \"hint\": None, }, { \"context\": \"\" \"In file", "}, ], id=\"conan\", ), pytest.param( [ { \"severity\": \"warning\", \"info\": \"Boost.Build engine (b2)", "from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\", \"file\": \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\", \"line\": \"146\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"extension used\",", "because the Bison\", \"*** output is pre-generated.)\", \"end\", \"CMake Warning at cmake/ldap.cmake:158 (MESSAGE):\",", "[ \"src/main/src/Em_FilteringQmFu.c: In function \" \"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\", \"src/main/src/Em_FilteringQmFu.c:266:5: warning: implicit declaration of function \"", "\"-Wother\", \"project\": None, \"hint\": None, }, { \"context\": \"\" \"In file included from", "None, \"severity\": None, \"severity_l\": \"WARNING\", \"user\": None, \"version\": None, }, { \"severity_l\": None,", "\"\", \"file\": \"src/port/pg_crc32c_sse42_choose.c\", \"line\": \"41\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"passing 'unsigned int", "openssl/1.1.1m overridden by poco/1.11.1 to openssl/1.1.1l\", }, { \"channel\": None, \"info\": \"this is", "strcat(mode2,\"b\"); /* binary mode */\\n ^', }, { \"file\": \"NMAKE\", \"line\": None, \"column\":", "ISO C forbids an empty translation unit [-Wpedantic]\", \" 284 | #endif\", \"", "\" from ../source_subfolder/atk/atktext.c:22:\", \"../source_subfolder/atk/atktext.c: In function \\u2018atk_text_range_get_type_once\\u2019:\", \"../source_subfolder/atk/atktext.c:1640:52: warning: ISO C prohibits argument", "you will not be able to build PostgreSQL from Git nor\" \"\\n*** change", "\"Boost.Build engine (b2) is 4.8.0\", }, ], id=\"build\", ), ] @pytest.mark.parametrize(\"expected\", dataset) def", "^~~~~~~~\", }, { \"context\": \"\" \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\\n\" \" from /package/include/glib-2.0/gobject/gbinding.h:29,\\n\"", "files. You can obtain Bison from\", \"*** a GNU mirror site. (If you", "MAKE_INSTALL_SBINDIR\", \"\", \"\", \"source_subfolder/src/tramp.c:215:52: warning: format \\u2018%ld\\u2019 expects argument of type \" \"\\u2018long", "find LDAP\", \"context\": \"\" \"Call Stack (most recent call first):\\n\" \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\\n\"", "included from \" \"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\", \"file\": \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h\", \"line\": \"15\", \"column\":", "\"\", \"\", \"CMake Warning at libmysql/authentication_ldap/CMakeLists.txt:30 (MESSAGE):\", \" Skipping the LDAP client authentication", "\"src/main/src/Em_FilteringQmFu.c\", \"line\": \"266\", \"column\": \"5\", \"severity\": \"warning\", \"info\": \"implicit declaration of function ‘memset’\",", "yet supported when compiling as C\\n\" \" ^\", \"project\": None, }, { \"context\":", "this, because the Bison\" \"\\n*** output is pre-generated.)\", }, ], id=\"autotools\", ), pytest.param(", "conversion \" \"from 'int' to 'HANDLE' of greater size\", \"C:\\\\source_subfolder\\\\bzlib.c(1418,10): warning C4996: 'strcat':", "warning: improperly calling \" \"multi-line macro `SETUP_STACK_POINTER' with 0 parameters [-w+macro-params-legacy]\", \"some text\",", "#define PG_INT128_TYPE __int128\", \" | ^~~~~~~~\", \"configure: WARNING:\", \"*** Without Bison you will", "about this, because the Bison\", \"*** output is pre-generated.)\", \"end\", \"CMake Warning at", "\"warning\", \"info\": \"\" \"format ‘%p’ expects argument of type ‘void*’, \" \"but argument", "converts \" \"between pointers to integer types with different sign\", \"category\": \"-Wpointer-sign\", \"project\":", "used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \" CMAKE_INSTALL_BINDIR\", \" CMAKE_INSTALL_DATAROOTDIR\", \" CMAKE_INSTALL_INCLUDEDIR\",", "~~~~~~\", \" | |\", \" | long unsigned int *\", \"In file included", "\"project\": None, \"hint\": None, }, { \"context\": \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\\n\" \"In", "\"types [-Wpedantic]\", \"C:\\\\src\\\\bzlib.c(161) : note: index 'blockSize100k' range checked by comparison on this", "{ \"context\": \"\" \"In file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres_fe.h:25,\\n\" \" from", "is not yet supported when compiling as C\", \" ^\", \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10): \" \"warning:", "to \" \"parameter of type 'int *' converts between pointers to integer types", "], id=\"autotools\", ), pytest.param( [ { \"ref\": \"libjpeg/1.2.3\", \"name\": \"libjpeg\", \"version\": \"1.2.3\", \"user\":", "\"ISO C does not support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\"", "\"hint\": None, }, { \"context\": \"\", \"file\": \"clang-cl\", \"severity\": \"warning\", \"info\": \"/: 'linker'", "../source_subfolder/atk/atk.h:25,\\n\" \" from ../source_subfolder/atk/atktext.c:22:\\n\" \"../source_subfolder/atk/atktext.c: In function \" \"\\u2018atk_text_range_get_type_once\\u2019:\\n\", \"file\": \"../source_subfolder/atk/atktext.c\", \"line\": \"1640\",", "atk_text_range_copy,\", \" | ^~~~~~~~~~~~~~~~~~~\", \"CMake Warning:\", \" Manually-specified variables were not used by", "included from ../../src/include/postgres.h:47,\\n\" \" from rmtree.c:15:\\n\" \"rmtree.c: In function ‘rmtree’:\\n\" \"In file included", "\"line\": \"35\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"OpenSSL 1.1.1l 24 Aug 2021\", \"category\":", "Warning at cmake/ldap.cmake:158 (MESSAGE):\", \" Could not find LDAP\", \"Call Stack (most recent", "ignoring return value of ‘fchown’, declared \" \"with attribute warn_unused_result [-Wunused-result]\", \" 1073", "In function \\u2018atk_text_range_get_type_once\\u2019:\", \"../source_subfolder/atk/atktext.c:1640:52: warning: ISO C prohibits argument conversion to \" \"union", "corrupted\", \"severity\": \"WARN\", \"severity_l\": None, }, { \"ref\": \"libmysqlclient/8.0.25\", \"name\": \"libmysqlclient\", \"version\": \"8.0.25\",", "of type ‘void*’, \" \"but argument 2 has type ‘const Edge*’\", \"category\": \"-Wformat=\",", "\"file\": None, \"line\": None, \"function\": None, \"info\": \"\" \" Manually-specified variables were not", "\"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\", \" ^\", \"/build/source_subfolder/bzip2.c: In function ‘applySavedFileAttrToOutputFile’:\",", "\"context\": \"\" \"In file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres_fe.h:25,\\n\" \" from archive.c:19:\\n\",", "\"name\": None, \"ref\": None, \"severity\": None, \"severity_l\": \"WARNING\", \"user\": None, \"version\": None, },", "\"category\": \"-w+macro-params-legacy\", \"project\": None, \"hint\": None, }, { \"context\": \"In file included from", "\"severity\": \"warning\", \"info\": \"format ‘%ld’ expects argument of type ‘long int *’, but", "35 | %name-prefix \"constexpYY\"\\n' \" | ^~~~~~~~~~~~~~~~~~~~~~~~~ | %define api.prefix \" \"{constexpYY}\", },", "\"severity\": \"WARN\", \"severity_l\": None, }, { \"ref\": \"libmysqlclient/8.0.25\", \"name\": \"libmysqlclient\", \"version\": \"8.0.25\", \"user\":", ": fatal error U1077: 'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : \" \"return code '0x1'\", \"clang-cl: warning: /:", "No sys/sdt.h found, no SDT events are defined, please install \" \"systemtap-sdt-devel or", "2021 [-W#pragma-messages]\", \" #pragma message (OPENSSL_VERSION_TEXT POCO_INTERNAL_OPENSSL_BUILD)\", \" ^\", \"source_subfolder/meson.build:1559:2: ERROR: Problem encountered:", "^~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"source_subfolder/src/tramp.c\", \"line\": \"215\", \"column\": \"52\", \"severity\": \"warning\",", "\" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\\n\" \" | ^~~~~~~~~~~~~~~~~~~\", }, { \"context\":", "*’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" ' 215 | nfields = sscanf", "‘long int *’, but argument 8 \" \"has type ‘long unsigned int *’\",", "(OPENSSL_VERSION_TEXT \" \"POCO_INTERNAL_OPENSSL_BUILD)\\n\" \" ^\", }, { \"context\": \"\", \"file\": \"source_subfolder/meson.build\", \"line\": \"1559\",", "None, \"severity\": \"warning\", \"info\": \"fix-its can be applied. Rerun with option '--update'.\", \"category\":", "file included from ../../src/include/postgres.h:47,\", \" from rmtree.c:15:\", \"rmtree.c: In function \\u2018rmtree\\u2019:\", \"In file", "*/', \" ^\", \"Makefile.config:565: No sys/sdt.h found, no SDT events are defined, please", "\" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \" CMAKE_INSTALL_BINDIR\", \" CMAKE_INSTALL_DATAROOTDIR\", \" CMAKE_INSTALL_INCLUDEDIR\", \" CMAKE_INSTALL_LIBDIR\", \" CMAKE_INSTALL_LIBEXECDIR\", \"", "from /package/include/glib-2.0/glib-object.h:22,\", \" from ../source_subfolder/atk/atkobject.h:27,\", \" from ../source_subfolder/atk/atk.h:25,\", \" from ../source_subfolder/atk/atktext.c:22:\", \"../source_subfolder/atk/atktext.c: In", "\"systemtap-sdt-devel or systemtap-sdt-dev\", \"CMake Warning:\", \" Manually-specified variables were not used by the", "from /package/include/glib-2.0/gobject/gbinding.h:29,\\n\" \" from /package/include/glib-2.0/glib-object.h:22,\\n\" \" from ../source_subfolder/atk/atkobject.h:27,\\n\" \" from ../source_subfolder/atk/atk.h:25,\\n\" \" from", "SDT events are defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"line\": \"565\", \"severity\":", "# -*- coding: UTF-8 -*- import re import pytest from conmon.warnings import Regex", "import Regex output = [ \"src/main/src/Em_FilteringQmFu.c: In function \" \"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\", \"src/main/src/Em_FilteringQmFu.c:266:5: warning: implicit", "\"info\": \" Skipping the LDAP client authentication plugin\", }, { \"context\": None, \"severity\":", "\"severity\": \"Warning\", \"function\": \"MESSAGE\", \"context\": None, \"info\": \" Skipping the LDAP client authentication", "\", \"WARNING: this is important\", \"warning: Boost.Build engine (b2) is 4.8.0\", \"./src/graph.cc: In", "from ../../src/include/c.h:54,\", \" from ../../src/include/postgres_fe.h:25,\", \" from archive.c:19:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does", "\" \"has type ‘long unsigned int *’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\"", "ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\", \" ^\", \"/build/source_subfolder/bzip2.c: In function ‘applySavedFileAttrToOutputFile’:\", \"/build/source_subfolder/bzip2.c:1073:11: warning:", "\" \"error: <stdatomic.h> is not yet supported when compiling as C\", \"#error <stdatomic.h>", "[-Wunused-command-line-argument]\", \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\", \"In file included from include\\\\crypto/evp.h:11:\", \"In file", "\"hint\": None, }, { \"context\": \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\\n\" \"In file included", "\"column\": \"5\", \"severity\": \"warning\", \"info\": \"implicit declaration of function ‘memset’\", \"category\": \"-Wimplicit-function-declaration\", \"project\":", "Manually-specified variables were not used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\" \" CMAKE_INSTALL_BINDIR\\n\"", "\"category\": \"-Wother\", \"project\": None, \"hint\": None, }, { \"context\": \"\" \"In file included", "value of ‘fchown’, declared \" \"with attribute warn_unused_result [-Wunused-result]\", \" 1073 | (void)", "unit\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \" 284 | #endif\\n | \", },", "{ \"context\": \"\", \"file\": \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\", \"line\": \"35\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"OpenSSL", "C prohibits argument conversion to union type\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\"", "of\" \"\\n*** PostgreSQL then you do not need to worry about this, because", "\"In file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres.h:46,\\n\" \" from stringinfo.c:20:\\n\", \"file\": \"../../src/include/pg_config.h\",", "\"info\": \" Manually-specified variables were not used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\"", "from ../../src/include/postgres_fe.h:25,\", \" from archive.c:19:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not support \\u2018__int128\\u2019", "from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\", \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52): warning: extension used \" \"[-Wlanguage-extension-token]\", \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile,", "../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres_fe.h:25,\\n\" \" from archive.c:19:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\",", "\"line\": \"43\", \"column\": None, \"severity\": \"warning\", \"info\": \"'reinterpret_cast': conversion from 'int' to 'HANDLE'", "has type ‘const Edge*’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" ' 409 |", "\\u2018void Edge::Dump(const char*) const\\u2019:\", \"./src/graph.cc:409:16: warning: format \\u2018%p\\u2019 expects argument of type \"", "\"#error <stdatomic.h> is not yet supported when compiling as C\", \" ^\", \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10):", "as C\", \"#error <stdatomic.h> is not yet supported when compiling as C\", \"", "| |\\n\" \" | long unsigned int *\", }, { \"context\": \"\" \"In", "empty translation unit\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \" 284 | #endif\\n |", "using the official distribution of\" \"\\n*** PostgreSQL then you do not need to", "online help for details.\", ' strcat(mode2,\"b\"); /* binary mode */', \" ^\", \"Makefile.config:565:", "int));\", \" ^\", \"/build/source_subfolder/bzip2.c: In function ‘applySavedFileAttrToOutputFile’:\", \"/build/source_subfolder/bzip2.c:1073:11: warning: ignoring return value of", "\" | ~~^\", \" | |\", \" | long int *\", \" |", "__int128\", \" | ^~~~~~~~\", \"configure: WARNING:\", \"*** Without Bison you will not be", "dev, &inode, file);\", \" | ~~~~~~\", \" | |\", \" | long unsigned", "None, \"hint\": \"\" ' 35 | %name-prefix \"constexpYY\"\\n' \" | ^~~~~~~~~~~~~~~~~~~~~~~~~ | %define", "\"hint\": None, }, { \"context\": \"\" \"In file included from ../../src/include/c.h:54,\\n\" \" from", "\"category\": \"U1077\", \"info\": \"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : return \" \"code '0x1'\", \"project\": None, \"hint\": None,", "warning: deprecated directive: ‘%name-prefix \" '\"constexpYY\"’, use ‘%define api.prefix {constexpYY}’ [-Wdeprecated]', ' 35", "%define api.prefix \" \"{constexpYY}\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": None, \"column\":", "mirror site. (If you are using the official distribution of\" \"\\n*** PostgreSQL then", "not need to worry about this, because the Bison\", \"*** output is pre-generated.)\",", "\"warning: OpenSSL 1.1.1l 24 Aug 2021 [-W#pragma-messages]\", \" #pragma message (OPENSSL_VERSION_TEXT POCO_INTERNAL_OPENSSL_BUILD)\", \"", "\"warning\", \"info\": \"format ‘%ld’ expects argument of type ‘long int *’, but argument", "}, { \"file\": \"NMAKE\", \"line\": None, \"column\": None, \"severity\": \"fatal error\", \"category\": \"U1077\",", "declared with attribute warn_unused_result\", \"category\": \"-Wunused-result\", \"project\": None, \"hint\": \"\" \" 1073 |", "by comparison on this line\", \"hint\": None, }, { \"context\": \"\", \"file\": \"ebcdic.c\",", "to build PostgreSQL from Git nor\" \"\\n*** change any of the parser definition", "included from ../../src/include/postgres.h:47,\", \" from rmtree.c:15:\", \"rmtree.c: In function \\u2018rmtree\\u2019:\", \"In file included", "}, ], id=\"gnu\", ), pytest.param( [ { \"file\": \"/source_subfolder/common/socket_utils.cc\", \"line\": \"43\", \"column\": None,", "is pre-generated.)\", \"end\", \"CMake Warning at cmake/ldap.cmake:158 (MESSAGE):\", \" Could not find LDAP\",", "MAKE_INSTALL_SBINDIR\", }, ], id=\"cmake\", ), pytest.param( [ { \"from\": \"Makefile.config\", \"info\": \"No sys/sdt.h", "\" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", }, { \"file\": \"cmake/ldap.cmake\", \"line\": \"158\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"info\":", "\"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\": None, \"info\": \" Manually-specified variables were", "Warning:\", \" Manually-specified variables were not used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\",", "\"info\": \"this is important\", \"name\": None, \"ref\": None, \"severity\": None, \"severity_l\": \"WARNING\", \"user\":", "'int' to 'HANDLE' of greater size\", \"category\": \"C4312\", \"project\": None, \"hint\": None, },", "\"column\": \"16\", \"severity\": \"warning\", \"info\": \"\" \"format ‘%p’ expects argument of type ‘void*’,", "'HANDLE' of greater size\", \"C:\\\\source_subfolder\\\\bzlib.c(1418,10): warning C4996: 'strcat': This function or variable \"", "\"info\": \" Could not find LDAP\", \"context\": \"\" \"Call Stack (most recent call", "\"severity\": \"WARN\", }, ], id=\"conan\", ), pytest.param( [ { \"severity\": \"warning\", \"info\": \"Boost.Build", "output is pre-generated.)\", \"end\", \"CMake Warning at cmake/ldap.cmake:158 (MESSAGE):\", \" Could not find", "support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": None, }, { \"context\": \"\",", "warning C4996: 'strcat': This function or variable \" \"may be unsafe. Consider using", "\"/build/source_subfolder/bzip2.c: In function ‘applySavedFileAttrToOutputFile’:\", \"/build/source_subfolder/bzip2.c:1073:11: warning: ignoring return value of ‘fchown’, declared \"", "Problem encountered: \" \"Could not determine size of size_t.\", \"\", ] dataset =", "{ \"context\": \"\", \"file\": \"clang-cl\", \"severity\": \"warning\", \"info\": \"/: 'linker' input unused\", \"category\":", "pytest.param( [ { \"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\": None,", "&end, perm, &offset, dev, &inode, file);\\n\" \" | ~~~~~~\\n\" \" | |\\n\" \"", "\"Warning\", \"file\": None, \"line\": None, \"function\": None, \"info\": \"\" \" Manually-specified variables were", "| %name-prefix \"constexpYY\"\\n' \" | ^~~~~~~~~~~~~~~~~~~~~~~~~ | %define api.prefix \" \"{constexpYY}\", }, {", "\"2\", \"severity\": \"error\", \"category\": None, \"info\": \"<stdatomic.h> is not yet supported when compiling", "Edge::Dump(const char*) const\\u2019:\\n\", \"file\": \"./src/graph.cc\", \"line\": \"409\", \"column\": \"16\", \"severity\": \"warning\", \"info\": \"\"", "warn_unused_result [-Wunused-result]\", \" 1073 | (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\", \"", "\"file\": \"../source_subfolder/atk/atktext.c\", \"line\": \"1640\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"ISO C prohibits argument", "\"hint\": None, }, { \"file\": \"C:\\\\source_subfolder\\\\bzlib.c\", \"line\": \"1418\", \"column\": \"10\", \"category\": \"C4996\", \"severity\":", "z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\\n\" \" ^\", }, { \"context\": \"/build/source_subfolder/bzip2.c: In", "( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\", \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", \"/source_subfolder/src/constexp.y:35.1-25: warning: deprecated directive: ‘%name-prefix", "encountered: \" \"Could not determine size of size_t.\", \"\", ] dataset = [", "\"category\": None, \"info\": \"Problem encountered: Could not determine size of size_t.\", \"project\": None,", "engine (b2) is 4.8.0\", }, ], id=\"build\", ), ] @pytest.mark.parametrize(\"expected\", dataset) def test_warnings_regex(expected,", "Git nor\" \"\\n*** change any of the parser definition files. You can obtain", "site. (If you are using the official distribution of\", \"*** PostgreSQL then you", "from rmtree.c:15:\\n\" \"rmtree.c: In function ‘rmtree’:\\n\" \"In file included from ../../src/include/c.h:54,\\n\" \" from", "\" from ../../src/include/postgres.h:46,\", \" from stringinfo.c:20:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not support", "\"warning\", \"info\": \"fix-its can be applied. Rerun with option '--update'.\", \"category\": \"-Wother\", \"project\":", "Stack (most recent call first):\\n\" \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\\n\" \" CMakeLists.txt:7 (include)\", }, {", "\"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\", \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52): warning: extension used \" \"[-Wlanguage-extension-token]\", \"ZEXTERN z_off64_t", "the LDAP client authentication plugin\", \"\", \"\", \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\", \"", "\"../source_subfolder/atk/atktext.c: In function \\u2018atk_text_range_get_type_once\\u2019:\", \"../source_subfolder/atk/atktext.c:1640:52: warning: ISO C prohibits argument conversion to \"", "^\", \"project\": None, }, { \"context\": \"\", \"file\": \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\", \"line\": \"35\", \"column\": \"10\",", "build step\", \"src/port/pg_crc32c_sse42_choose.c(41,10): warning : passing 'unsigned int [4]' to \" \"parameter of", "\"1640\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"ISO C prohibits argument conversion to union", "\"strcat_s instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\",", "\"info\": \"\" \" Manually-specified variables were not used by the project:\\n\" \"\\n\" \"", "distribution of\" \"\\n*** PostgreSQL then you do not need to worry about this,", "^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": \"35\", \"column\": \"1-25\", \"severity\": \"warning\",", "int *\\u2019, but argument 8 has type \\u2018long unsigned int *\\u2019 [-Wformat=]\", '", "you do not need to worry about this, because the Bison\" \"\\n*** output", "\" \"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\", \"file\": \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h\", \"line\": \"15\", \"column\": \"2\", \"severity\":", "\"hint\": \"\" \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\\n\" \" ^~~~~~\", }, { \"context\": \"\", \"file\":", "pytest.param( [ { \"ref\": \"libjpeg/1.2.3\", \"name\": \"libjpeg\", \"version\": \"1.2.3\", \"user\": None, \"channel\": None,", "\"file\": \"NMAKE\", \"line\": None, \"column\": None, \"severity\": \"fatal error\", \"category\": \"U1077\", \"info\": \"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE'", "void*\", \"ninja/1.9.0 (test package): WARN: This conanfile has no build step\", \"src/port/pg_crc32c_sse42_choose.c(41,10): warning", "with different sign \" \"[-Wpointer-sign] [C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\", \"NMAKE : fatal error U1077: 'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' :", "\"index 'blockSize100k' range checked by comparison on this line\", \"hint\": None, }, {", "), pytest.param( [ { \"severity\": \"warning\", \"info\": \"Boost.Build engine (b2) is 4.8.0\", },", "will not be able to build PostgreSQL from Git nor\" \"\\n*** change any", "\"Call Stack (most recent call first):\", \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\", \" CMakeLists.txt:7 (include)\", \"\",", "fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\", \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", \"/source_subfolder/src/constexp.y:35.1-25: warning: deprecated directive:", "}, { \"context\": \"./src/graph.cc: In member function \" \"\\u2018void Edge::Dump(const char*) const\\u2019:\\n\", \"file\":", "\" | %define api.prefix {constexpYY}\", \"/source_subfolder/src/constexp.y: warning: fix-its can be applied. Rerun with", "\"*** change any of the parser definition files. You can obtain Bison from\",", "\"fix-its can be applied. Rerun with option '--update'.\", \"category\": \"-Wother\", \"project\": None, \"hint\":", "C\\n\" \" ^\", \"project\": None, }, { \"context\": \"\", \"file\": \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\", \"line\": \"35\",", "{ \"context\": \"\", \"file\": \"C:\\\\src\\\\bzlib.c\", \"line\": \"161\", \"column\": None, \"severity\": \"note\", \"category\": None,", "\"ninja\", \"version\": \"1.9.0\", \"channel\": None, \"user\": None, \"info\": \"This conanfile has no build", "0 parameters\", \"category\": \"-w+macro-params-legacy\", \"project\": None, \"hint\": None, }, { \"context\": \"In file", "\"ninja/1.9.0 (test package): WARN: This conanfile has no build step\", \"src/port/pg_crc32c_sse42_choose.c(41,10): warning :", "\"./src/graph.cc\", \"line\": \"409\", \"column\": \"16\", \"severity\": \"warning\", \"info\": \"\" \"format ‘%p’ expects argument", "using strcat_s instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help for", "\" | ^~~~~~~~\", }, { \"context\": \"\" \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\\n\" \"", "int *’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" ' 215 | nfields =", "C does not support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \"", "%define api.prefix {constexpYY}\", \"/source_subfolder/src/constexp.y: warning: fix-its can be applied. Rerun with option \"", "included from crypto\\\\asn1\\\\a_sign.c:22:\\n\" \"In file included from include\\\\crypto/evp.h:11:\\n\" \"In file included from include\\\\internal/refcount.h:21:\\n\"", "In function \" \"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\", \"src/main/src/Em_FilteringQmFu.c:266:5: warning: implicit declaration of function \" \"\\u2018memset\\u2019 [-Wimplicit-function-declaration]\",", "}, { \"from\": \"configure\", \"line\": None, \"severity\": \"WARNING\", \"info\": \"\" \"\\n*** Without Bison", "does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \"C:\\\\src\\\\bzlib.c(161) : note: index 'blockSize100k' range", "Studio\\\\include\\\\stdatomic.h\", \"line\": \"15\", \"column\": \"2\", \"severity\": \"error\", \"category\": None, \"info\": \"<stdatomic.h> is not", "[-Wpedantic]\", \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\", \" | ^~~~~~~~~~~~~~~~~~~\", \"CMake Warning:\",", "gzseek64 OF((gzFile, z_off64_t, int));\", \" ^\", \"/build/source_subfolder/bzip2.c: In function ‘applySavedFileAttrToOutputFile’:\", \"/build/source_subfolder/bzip2.c:1073:11: warning: ignoring", "\"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", }, { \"file\": \"cmake/ldap.cmake\", \"line\": \"158\", \"severity\": \"Warning\", \"function\": \"MESSAGE\",", "\"source_subfolder/src/tramp.c\", \"line\": \"215\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"format ‘%ld’ expects argument of", "\\u2018const Edge*\\u2019 [-Wformat=]\", ' 409 | printf(\"] 0x%p\\\\n\", this);', \" | ~^\", \"", "|\", \" | long int *\", \" | %ld\", \" 216 | &start,", "\"column\": \"52\", \"severity\": \"warning\", \"info\": \"ISO C prohibits argument conversion to union type\",", "argument 8 \" \"has type ‘long unsigned int *’\", \"category\": \"-Wformat=\", \"project\": None,", "determine size of size_t.\", \"\", ] dataset = [ pytest.param( [ { \"context\":", "file included from include\\\\internal/refcount.h:21:\\n\" \"In file included from \" \"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\", \"file\": \"C:\\\\Program Files", "= request.node.callspec.id matches = list( match.groupdict() for match in re.finditer(Regex.get(compiler), \"\\n\".join(output)) ) assert", "authentication plugin\", \"\", \"\", \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\", \" from /package/include/glib-2.0/gobject/gbinding.h:29,\", \"", "‘fchown’, declared with attribute warn_unused_result\", \"category\": \"-Wunused-result\", \"project\": None, \"hint\": \"\" \" 1073", "772 | #define PG_INT128_TYPE __int128\", \" | ^~~~~~~~\", \"configure: WARNING:\", \"*** Without Bison", "C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\", \"file\": \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\", \"line\": \"146\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"extension used\", \"category\":", "\" from archive.c:19:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\", \"info\": \"ISO", "this line\", \"hint\": None, }, { \"context\": \"\", \"file\": \"ebcdic.c\", \"line\": \"284\", \"column\":", "|\\n\" \" | long int *\\n\" \" | %ld\\n\" \" 216 | &start,", "but argument 2 has type \\u2018const Edge*\\u2019 [-Wformat=]\", ' 409 | printf(\"] 0x%p\\\\n\",", "0x%p\\\\n\", this);', \" | ~^\", \" | |\", \" | void*\", \"ninja/1.9.0 (test", "fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\\n\" \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\",", "warning: format \\u2018%ld\\u2019 expects argument of type \" \"\\u2018long int *\\u2019, but argument", "*’, but argument 8 \" \"has type ‘long unsigned int *’\", \"category\": \"-Wformat=\",", "\" \"warning: OpenSSL 1.1.1l 24 Aug 2021 [-W#pragma-messages]\", \" #pragma message (OPENSSL_VERSION_TEXT POCO_INTERNAL_OPENSSL_BUILD)\",", "{ \"context\": \"src/main/src/Em_FilteringQmFu.c: In function \" \"‘Em_FilteringQmFu_processSensorSignals’:\\n\", \"file\": \"src/main/src/Em_FilteringQmFu.c\", \"line\": \"266\", \"column\": \"5\",", "id=\"msvc\", ), pytest.param( [ { \"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\": None,", "-*- import re import pytest from conmon.warnings import Regex output = [ \"src/main/src/Em_FilteringQmFu.c:", "\"No sys/sdt.h found, no SDT events are defined, please install \" \"systemtap-sdt-devel or", "\"OpenSSL 1.1.1l 24 Aug 2021\", \"category\": \"-W#pragma-messages\", \"project\": None, \"hint\": \" #pragma message", "Visual Studio\\\\include\\\\stdatomic.h(15,2): \" \"error: <stdatomic.h> is not yet supported when compiling as C\",", "*\\u2019 [-Wformat=]\", ' 215 | nfields = sscanf (line, \"%lx-%lx %9s %lx %9s", "\"context\": \"\" \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\\n\" \" from /package/include/glib-2.0/gobject/gbinding.h:29,\\n\" \" from /package/include/glib-2.0/glib-object.h:22,\\n\"", "value of ‘fchown’, declared with attribute warn_unused_result\", \"category\": \"-Wunused-result\", \"project\": None, \"hint\": \"\"", "error U1077: 'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : \" \"return code '0x1'\", \"clang-cl: warning: /: 'linker' input", "file included from crypto\\\\asn1\\\\a_sign.c:22:\", \"In file included from include\\\\crypto/evp.h:11:\", \"In file included from", "\"function\": \"MESSAGE\", \"info\": \" Could not find LDAP\", \"context\": \"\" \"Call Stack (most", "^~~~~~~~\", \"configure: WARNING:\", \"*** Without Bison you will not be able to build", "None, \"hint\": None, }, { \"context\": \"\", \"file\": \"C:\\\\src\\\\bzlib.c\", \"line\": \"161\", \"column\": None,", "\"In file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres_fe.h:25,\", \" from archive.c:19:\", \"../../src/include/pg_config.h:772:24: warning:", "from rmtree.c:15:\", \"rmtree.c: In function \\u2018rmtree\\u2019:\", \"In file included from ../../src/include/c.h:54,\", \" from", "'strcat': This function or variable \" \"may be unsafe. Consider using strcat_s instead.", "included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres_fe.h:25,\\n\" \" from archive.c:19:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\",", "\" Manually-specified variables were not used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", },", "\" \"overridden by poco/1.11.1 to openssl/1.1.1l\", \"In file included from ../../src/include/c.h:54,\", \" from", "%name-prefix \"constexpYY\"', \" | ^~~~~~~~~~~~~~~~~~~~~~~~~\" \" | %define api.prefix {constexpYY}\", \"/source_subfolder/src/constexp.y: warning: fix-its", "/package/include/glib-2.0/gobject/gobject.h:24,\", \" from /package/include/glib-2.0/gobject/gbinding.h:29,\", \" from /package/include/glib-2.0/glib-object.h:22,\", \" from ../source_subfolder/atk/atkobject.h:27,\", \" from ../source_subfolder/atk/atk.h:25,\",", "are using the official distribution of\", \"*** PostgreSQL then you do not need", "supported when compiling as C\", \"hint\": \"#error <stdatomic.h> is not yet supported when", "line\", \"ebcdic.c:284: warning: ISO C forbids an empty translation unit [-Wpedantic]\", \" 284", "{ \"file\": \"cmake/ldap.cmake\", \"line\": \"158\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"info\": \" Could not", "mirror site. (If you are using the official distribution of\", \"*** PostgreSQL then", "\" from ../../src/include/postgres_fe.h:25,\", \" from archive.c:19:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not support", "\"constexpYY\"’, use ‘%define ' \"api.prefix {constexpYY}’\", \"category\": \"-Wdeprecated\", \"project\": None, \"hint\": \"\" '", "{ \"file\": \"libmysql/authentication_ldap/CMakeLists.txt\", \"line\": \"30\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"context\": None, \"info\": \"", "\"\" \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\\n\" \" ^~~~~~\", }, { \"context\": \"\", \"file\": \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\",", "\"column\": \"2\", \"severity\": \"error\", \"category\": None, \"info\": \"<stdatomic.h> is not yet supported when", "attribute warn_unused_result\", \"category\": \"-Wunused-result\", \"project\": None, \"hint\": \"\" \" 1073 | (void) fchown", "\" \"Could not determine size of size_t.\", \"\", ] dataset = [ pytest.param(", "when compiling as C\", \"hint\": \"#error <stdatomic.h> is not yet supported when compiling", "\"constexpYY\"\\n' \" | ^~~~~~~~~~~~~~~~~~~~~~~~~ | %define api.prefix \" \"{constexpYY}\", }, { \"context\": \"\",", "[-Wformat=]\", ' 409 | printf(\"] 0x%p\\\\n\", this);', \" | ~^\", \" | |\",", "\" Manually-specified variables were not used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"", "&offset, dev, &inode, file);\\n\" \" | ~~~~~~\\n\" \" | |\\n\" \" | long", "CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\", \" CMakeLists.txt:7 (include)\", \"\", \"\", \"CMake Warning at libmysql/authentication_ldap/CMakeLists.txt:30 (MESSAGE):\", \"", "variables were not used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", }, { \"file\":", "\"file\": \"./src/graph.cc\", \"line\": \"409\", \"column\": \"16\", \"severity\": \"warning\", \"info\": \"\" \"format ‘%p’ expects", "types with different sign \" \"[-Wpointer-sign] [C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\", \"NMAKE : fatal error U1077: 'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE'", "type ‘const Edge*’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" ' 409 | printf(\"]", "\"-Wpointer-sign\", \"project\": \"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\", \"hint\": None, }, { \"context\": \"\", \"file\": \"clang-cl\", \"severity\": \"warning\",", "archive.c:19:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\", \"info\": \"ISO C does", "union type\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange,", "applied. Rerun with option \" \"'--update'. [-Wother]\", \"/source_subfolder/common/socket_utils.cc(43): warning C4312: 'reinterpret_cast': conversion \"", "\"line\": \"158\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"info\": \" Could not find LDAP\", \"context\":", "\" CMAKE_INSTALL_OLDINCLUDEDIR\", \" MAKE_INSTALL_SBINDIR\", \"\", \"\", \"source_subfolder/src/tramp.c:215:52: warning: format \\u2018%ld\\u2019 expects argument of", "\" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\", \"project\": None, \"hint\": ' strcat(mode2,\"b\"); /*", "], id=\"msvc\", ), pytest.param( [ { \"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\":", "None, \"hint\": ' strcat(mode2,\"b\"); /* binary mode */\\n ^', }, { \"file\": \"NMAKE\",", "~~^\\n\" \" | |\\n\" \" | long int *\\n\" \" | %ld\\n\" \"", "\"info\": \"extension used\", \"category\": \"-Wlanguage-extension-token\", \"project\": None, \"hint\": \"\" \"ZEXTERN z_off64_t ZEXPORT gzseek64", "events are defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"line\": \"565\", \"severity\": None,", "found, no SDT events are defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"line\":", "member function \\u2018void Edge::Dump(const char*) const\\u2019:\", \"./src/graph.cc:409:16: warning: format \\u2018%p\\u2019 expects argument of", "284 | #endif\", \" | \", \"WARNING: this is important\", \"warning: Boost.Build engine", "1073 | (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\", \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", \"/source_subfolder/src/constexp.y:35.1-25:", "\" ^\", \"project\": None, }, { \"context\": \"\", \"file\": \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\", \"line\": \"35\", \"column\":", "\" CMAKE_INSTALL_LIBEXECDIR\\n\" \" CMAKE_INSTALL_OLDINCLUDEDIR\\n\" \" MAKE_INSTALL_SBINDIR\", }, ], id=\"cmake\", ), pytest.param( [ {", "{ \"severity_l\": None, \"ref\": \"ninja/1.9.0\", \"name\": \"ninja\", \"version\": \"1.9.0\", \"channel\": None, \"user\": None,", "parser definition files. You can obtain Bison from\", \"*** a GNU mirror site.", "found, no SDT events are defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"CMake", "not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \"C:\\\\src\\\\bzlib.c(161) : note: index 'blockSize100k' range checked", "but argument 8 \" \"has type ‘long unsigned int *’\", \"category\": \"-Wformat=\", \"project\":", "\" | ^~~~~~~~~~~~~~~~~~~~~~~~~ | %define api.prefix \" \"{constexpYY}\", }, { \"context\": \"\", \"file\":", "None, \"info\": \"This conanfile has no build step\", \"severity\": \"WARN\", }, ], id=\"conan\",", "from ../source_subfolder/atk/atk.h:25,\\n\" \" from ../source_subfolder/atk/atktext.c:22:\\n\" \"../source_subfolder/atk/atktext.c: In function \" \"\\u2018atk_text_range_get_type_once\\u2019:\\n\", \"file\": \"../source_subfolder/atk/atktext.c\", \"line\":", "409 | printf(\"] 0x%p\\\\n\", this);\\n' \" | ~^\\n\" \" | |\\n\" \" |", "\" \"\\u2018void*\\u2019, but argument 2 has type \\u2018const Edge*\\u2019 [-Wformat=]\", ' 409 |", "not find LDAP\", \"context\": \"\" \"Call Stack (most recent call first):\\n\" \" CMakeListsOriginal.txt:1351", "\" CMAKE_INSTALL_INCLUDEDIR\", \" CMAKE_INSTALL_LIBDIR\", \" CMAKE_INSTALL_LIBEXECDIR\", \" CMAKE_INSTALL_OLDINCLUDEDIR\", \" MAKE_INSTALL_SBINDIR\", \"\", \"\", \"source_subfolder/src/tramp.c:215:52:", "declaration of function \" \"\\u2018memset\\u2019 [-Wimplicit-function-declaration]\", \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\", \" ^~~~~~\", \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92:", "#endif\", \" | \", \"WARNING: this is important\", \"warning: Boost.Build engine (b2) is", "\"info\": \"/: 'linker' input unused\", \"category\": \"-Wunused-command-line-argument\", \"line\": None, \"column\": None, \"project\": None,", "‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": None, }, { \"context\": \"\", \"file\":", "pytest.param( [ { \"context\": \"src/main/src/Em_FilteringQmFu.c: In function \" \"‘Em_FilteringQmFu_processSensorSignals’:\\n\", \"file\": \"src/main/src/Em_FilteringQmFu.c\", \"line\": \"266\",", "1.1.1l 24 Aug 2021 [-W#pragma-messages]\", \" #pragma message (OPENSSL_VERSION_TEXT POCO_INTERNAL_OPENSSL_BUILD)\", \" ^\", \"source_subfolder/meson.build:1559:2:", "/package/include/glib-2.0/gobject/gobject.h:24,\\n\" \" from /package/include/glib-2.0/gobject/gbinding.h:29,\\n\" \" from /package/include/glib-2.0/glib-object.h:22,\\n\" \" from ../source_subfolder/atk/atkobject.h:27,\\n\" \" from ../source_subfolder/atk/atk.h:25,\\n\"", "argument of type ‘long int *’, but argument 8 \" \"has type ‘long", "unsigned int *\\u2019 [-Wformat=]\", ' 215 | nfields = sscanf (line, \"%lx-%lx %9s", "}, { \"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\": None, \"info\":", "empty translation unit [-Wpedantic]\", \" 284 | #endif\", \" | \", \"WARNING: this", "call first):\", \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\", \" CMakeLists.txt:7 (include)\", \"\", \"\", \"CMake Warning at", "macro `SETUP_STACK_POINTER' with 0 parameters\", \"category\": \"-w+macro-params-legacy\", \"project\": None, \"hint\": None, }, {", "\"overridden by poco/1.11.1 to openssl/1.1.1l\", \"In file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres_fe.h:25,\",", "included from include\\\\crypto/evp.h:11:\\n\" \"In file included from include\\\\internal/refcount.h:21:\\n\" \"In file included from \"", "None, \"hint\": \" #pragma message (OPENSSL_VERSION_TEXT \" \"POCO_INTERNAL_OPENSSL_BUILD)\\n\" \" ^\", }, { \"context\":", "~~~~~~\\n\" \" | |\\n\" \" | long unsigned int *\", }, { \"context\":", "size\", \"C:\\\\source_subfolder\\\\bzlib.c(1418,10): warning C4996: 'strcat': This function or variable \" \"may be unsafe.", "&start, &end, perm, &offset, dev, &inode, file);\", \" | ~~~~~~\", \" | |\",", "greater size\", \"category\": \"C4312\", \"project\": None, \"hint\": None, }, { \"file\": \"C:\\\\source_subfolder\\\\bzlib.c\", \"line\":", "option \" \"'--update'. [-Wother]\", \"/source_subfolder/common/socket_utils.cc(43): warning C4312: 'reinterpret_cast': conversion \" \"from 'int' to", "\"but argument 2 has type ‘const Edge*’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\"", "\"ref\": \"ninja/1.9.0\", \"name\": \"ninja\", \"version\": \"1.9.0\", \"channel\": None, \"user\": None, \"info\": \"This conanfile", "\"In file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres.h:46,\", \" from stringinfo.c:20:\", \"../../src/include/pg_config.h:772:24: warning:", "\"project\": None, \"hint\": None, }, { \"context\": \"\", \"file\": \"C:\\\\src\\\\bzlib.c\", \"line\": \"161\", \"column\":", "a GNU mirror site. (If you are using the official distribution of\", \"***", "sign \" \"[-Wpointer-sign] [C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\", \"NMAKE : fatal error U1077: 'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : \" \"return", "\"#error <stdatomic.h> is not yet supported when compiling as C\\n\" \" ^\", \"project\":", "build PostgreSQL from Git nor\" \"\\n*** change any of the parser definition files.", "%ld %s\",', \" | ~~^\", \" | |\", \" | long int *\",", "instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\", \"project\":", "\"hint\": None, }, ], id=\"msvc\", ), pytest.param( [ { \"context\": None, \"severity\": \"Warning\",", "engine (b2) is 4.8.0\", \"./src/graph.cc: In member function \\u2018void Edge::Dump(const char*) const\\u2019:\", \"./src/graph.cc:409:16:", "0x%p\\\\n\", this);\\n' \" | ~^\\n\" \" | |\\n\" \" | void*\", }, {", "to integer types with different sign\", \"category\": \"-Wpointer-sign\", \"project\": \"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\", \"hint\": None, },", "included from include\\\\internal/refcount.h:21:\\n\" \"In file included from \" \"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\", \"file\": \"C:\\\\Program Files (x86)\\\\Microsoft", "not yet supported when compiling as C\", \"hint\": \"#error <stdatomic.h> is not yet", "^', }, { \"file\": \"NMAKE\", \"line\": None, \"column\": None, \"severity\": \"fatal error\", \"category\":", "None, \"hint\": \"\" \" 1073 | (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\\n\"", "216 | &start, &end, perm, &offset, dev, &inode, file);\", \" | ~~~~~~\", \"", "\"src/port/pg_crc32c_sse42_choose.c\", \"line\": \"41\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"passing 'unsigned int [4]' to", "from archive.c:19:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\",", "yet supported when compiling as C\", \" ^\", \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10): \" \"warning: OpenSSL 1.1.1l", "\"file\": \"/build/source_subfolder/bzip2.c\", \"line\": \"1073\", \"column\": \"11\", \"severity\": \"warning\", \"info\": \"\" \"ignoring return value", "need to worry about this, because the Bison\", \"*** output is pre-generated.)\", \"end\",", "from \" \"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\", \"file\": \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h\", \"line\": \"15\", \"column\": \"2\",", "\"<stdatomic.h> is not yet supported when compiling as C\", \"hint\": \"#error <stdatomic.h> is", "284 | #endif\\n | \", }, { \"context\": \"./src/graph.cc: In member function \"", "Bison from\", \"*** a GNU mirror site. (If you are using the official", "\"MESSAGE\", \"context\": None, \"info\": \" Skipping the LDAP client authentication plugin\", }, {", "by comparison on this line\", \"ebcdic.c:284: warning: ISO C forbids an empty translation", "request): compiler = request.node.callspec.id matches = list( match.groupdict() for match in re.finditer(Regex.get(compiler), \"\\n\".join(output))", "\" \"POCO_INTERNAL_OPENSSL_BUILD)\\n\" \" ^\", }, { \"context\": \"\", \"file\": \"source_subfolder/meson.build\", \"line\": \"1559\", \"column\":", "\"../source_subfolder/atk/atktext.c:1640:52: warning: ISO C prohibits argument conversion to \" \"union type [-Wpedantic]\", \"", "\"hint\": None, }, { \"context\": \"\", \"file\": \"ebcdic.c\", \"line\": \"284\", \"column\": None, \"severity\":", "ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\\n\" \" ^\", }, { \"context\": \"/build/source_subfolder/bzip2.c: In function", "'int *' converts between pointers to integer types with different sign \" \"[-Wpointer-sign]", "\"severity\": \"error\", \"category\": None, \"info\": \"<stdatomic.h> is not yet supported when compiling as", "from crypto\\\\asn1\\\\a_sign.c:22:\", \"In file included from include\\\\crypto/evp.h:11:\", \"In file included from include\\\\internal/refcount.h:21:\", \"In", "\"category\": \"-Wpedantic\", \"project\": None, \"hint\": None, }, { \"context\": \"\", \"file\": \"C:\\\\src\\\\bzlib.c\", \"line\":", "\"name\": \"libjpeg\", \"version\": \"1.2.3\", \"user\": None, \"channel\": None, \"info\": \"package is corrupted\", \"severity\":", "the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \" CMAKE_INSTALL_BINDIR\", \" CMAKE_INSTALL_DATAROOTDIR\", \" CMAKE_INSTALL_INCLUDEDIR\", \" CMAKE_INSTALL_LIBDIR\",", "\"In file included from include\\\\crypto/evp.h:11:\", \"In file included from include\\\\internal/refcount.h:21:\", \"In file included", "request.node.callspec.id matches = list( match.groupdict() for match in re.finditer(Regex.get(compiler), \"\\n\".join(output)) ) assert matches", "cmake/ldap.cmake:158 (MESSAGE):\", \" Could not find LDAP\", \"Call Stack (most recent call first):\",", "\"Problem encountered: Could not determine size of size_t.\", \"project\": None, \"hint\": None, },", "}, { \"context\": \"\", \"file\": \"src/port/pg_crc32c_sse42_choose.c\", \"line\": \"41\", \"column\": \"10\", \"severity\": \"warning\", \"info\":", "\"C4996\", \"severity\": \"warning\", \"info\": \"'strcat': This function or variable may be unsafe. Consider", "parameters [-w+macro-params-legacy]\", \"some text\", \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\", \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52): warning: extension used", "), ] @pytest.mark.parametrize(\"expected\", dataset) def test_warnings_regex(expected, request): compiler = request.node.callspec.id matches = list(", "output = [ \"src/main/src/Em_FilteringQmFu.c: In function \" \"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\", \"src/main/src/Em_FilteringQmFu.c:266:5: warning: implicit declaration of", "const\\u2019:\\n\", \"file\": \"./src/graph.cc\", \"line\": \"409\", \"column\": \"16\", \"severity\": \"warning\", \"info\": \"\" \"format ‘%p’", "\"name\": \"ninja\", \"version\": \"1.9.0\", \"channel\": None, \"user\": None, \"info\": \"This conanfile has no", "used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\" \" CMAKE_INSTALL_BINDIR\\n\" \" CMAKE_INSTALL_DATAROOTDIR\\n\" \" CMAKE_INSTALL_INCLUDEDIR\\n\"", "\" 216 | &start, &end, perm, &offset, dev, &inode, file);\\n\" \" | ~~~~~~\\n\"", "requirement openssl/1.1.1m \" \"overridden by poco/1.11.1 to openssl/1.1.1l\", \"In file included from ../../src/include/c.h:54,\",", "../../src/include/postgres.h:46,\\n\" \" from stringinfo.c:20:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\", \"info\":", "[4]' to parameter of type 'int *' converts \" \"between pointers to integer", "the parser definition files. You can obtain Bison from\", \"*** a GNU mirror", "CMAKE_INSTALL_INCLUDEDIR\\n\" \" CMAKE_INSTALL_LIBDIR\\n\" \" CMAKE_INSTALL_LIBEXECDIR\\n\" \" CMAKE_INSTALL_OLDINCLUDEDIR\\n\" \" MAKE_INSTALL_SBINDIR\", }, ], id=\"cmake\", ),", "\"severity_l\": None, }, { \"ref\": \"libmysqlclient/8.0.25\", \"name\": \"libmysqlclient\", \"version\": \"8.0.25\", \"user\": None, \"channel\":", "\" \"[-Wlanguage-extension-token]\", \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\", \" ^\", \"/build/source_subfolder/bzip2.c: In", "api.prefix \" \"{constexpYY}\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": None, \"column\": None,", "unsafe. Consider using \" \"strcat_s instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See", "\"info\": \"'strcat': This function or variable may be unsafe. Consider using \" \"strcat_s", "GNU mirror site. (If you are using the official distribution of\" \"\\n*** PostgreSQL", "\"line\": None, \"function\": None, \"info\": \" Manually-specified variables were not used by the", "U1077: 'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : \" \"return code '0x1'\", \"clang-cl: warning: /: 'linker' input unused", "None, }, { \"context\": \"\", \"file\": \"C:\\\\src\\\\bzlib.c\", \"line\": \"161\", \"column\": None, \"severity\": \"note\",", "unsafe. Consider using strcat_s instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online", "&inode, file);\\n\" \" | ~~~~~~\\n\" \" | |\\n\" \" | long unsigned int", "| void*\", }, { \"context\": \"\", \"file\": \"src/port/pg_crc32c_sse42_choose.c\", \"line\": \"41\", \"column\": \"10\", \"severity\":", "\"In file included from \" \"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\", \"file\": \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h\", \"line\":", "\"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\\n\" \"", "ISO C does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \"C:\\\\src\\\\bzlib.c(161) : note: index", "warning: ISO C does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \" 772 |", "conversion from 'int' to 'HANDLE' of greater size\", \"category\": \"C4312\", \"project\": None, \"hint\":", "yet supported when compiling as C\", \"#error <stdatomic.h> is not yet supported when", "None, \"severity\": \"warning\", \"info\": \"'reinterpret_cast': conversion from 'int' to 'HANDLE' of greater size\",", "C does not support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": None, },", "Edge*’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" ' 409 | printf(\"] 0x%p\\\\n\", this);\\n'", "file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres_fe.h:25,\\n\" \" from archive.c:19:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\":", "return value of ‘fchown’, declared \" \"with attribute warn_unused_result [-Wunused-result]\", \" 1073 |", "directive: ‘%name-prefix \" '\"constexpYY\"’, use ‘%define api.prefix {constexpYY}’ [-Wdeprecated]', ' 35 | %name-prefix", "\"line\": \"30\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"context\": None, \"info\": \" Skipping the LDAP", "| ~~^\", \" | |\", \" | long int *\", \" | %ld\",", "pytest from conmon.warnings import Regex output = [ \"src/main/src/Em_FilteringQmFu.c: In function \" \"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\",", "\"warning\", \"info\": \"Boost.Build engine (b2) is 4.8.0\", }, ], id=\"build\", ), ] @pytest.mark.parametrize(\"expected\",", "\"1-25\", \"severity\": \"warning\", \"info\": 'deprecated directive: ‘%name-prefix \"constexpYY\"’, use ‘%define ' \"api.prefix {constexpYY}’\",", "\"file\": \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\", \"line\": \"92\", \"column\": None, \"severity\": \"warning\", \"info\": \"\" \"improperly calling multi-line", "does not support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 772", "stringinfo.c:20:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\", \"info\": \"ISO C does", "included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\", \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52): warning: extension used \" \"[-Wlanguage-extension-token]\", \"ZEXTERN z_off64_t ZEXPORT gzseek64", "\"info\": \"No sys/sdt.h found, no SDT events are defined, please install \" \"systemtap-sdt-devel", "from ../../src/include/c.h:54,\", \" from ../../src/include/postgres.h:46,\", \" from stringinfo.c:20:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does", "include\\\\crypto/evp.h:11:\", \"In file included from include\\\\internal/refcount.h:21:\", \"In file included from C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\", \"C:\\\\Program Files", "&end, perm, &offset, dev, &inode, file);\", \" | ~~~~~~\", \" | |\", \"", "&start, &end, perm, &offset, dev, &inode, file);\\n\" \" | ~~~~~~\\n\" \" | |\\n\"", "None, \"function\": None, \"info\": \" Manually-specified variables were not used by the project:\\n\"", "prohibits argument conversion to \" \"union type [-Wpedantic]\", \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange,", "\"union type [-Wpedantic]\", \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\", \" | ^~~~~~~~~~~~~~~~~~~\",", "\"severity\": \"note\", \"category\": None, \"project\": None, \"info\": \"index 'blockSize100k' range checked by comparison", "Visual Studio\\\\include\\\\stdatomic.h\", \"line\": \"15\", \"column\": \"2\", \"severity\": \"error\", \"category\": None, \"info\": \"<stdatomic.h> is", "to 'HANDLE' of greater size\", \"C:\\\\source_subfolder\\\\bzlib.c(1418,10): warning C4996: 'strcat': This function or variable", "id=\"cmake\", ), pytest.param( [ { \"from\": \"Makefile.config\", \"info\": \"No sys/sdt.h found, no SDT", "}, { \"context\": \"\", \"file\": \"clang-cl\", \"severity\": \"warning\", \"info\": \"/: 'linker' input unused\",", "^~~~~~\", \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92: warning: improperly calling \" \"multi-line macro `SETUP_STACK_POINTER' with 0 parameters [-w+macro-params-legacy]\",", "by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", }, { \"file\": \"cmake/ldap.cmake\", \"line\": \"158\", \"severity\":", "' 35 | %name-prefix \"constexpYY\"\\n' \" | ^~~~~~~~~~~~~~~~~~~~~~~~~ | %define api.prefix \" \"{constexpYY}\",", "of size_t.\", \"project\": None, \"hint\": None, }, ], id=\"gnu\", ), pytest.param( [ {", "\"MESSAGE\", \"info\": \" Could not find LDAP\", \"context\": \"\" \"Call Stack (most recent", "at libmysql/authentication_ldap/CMakeLists.txt:30 (MESSAGE):\", \" Skipping the LDAP client authentication plugin\", \"\", \"\", \"In", "warning: format \\u2018%p\\u2019 expects argument of type \" \"\\u2018void*\\u2019, but argument 2 has", "you are using the official distribution of\" \"\\n*** PostgreSQL then you do not", "}, { \"context\": \"\" \"In file included from ../../src/include/postgres.h:47,\\n\" \" from rmtree.c:15:\\n\" \"rmtree.c:", "\"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\", \"line\": \"92\", \"column\": None, \"severity\": \"warning\", \"info\": \"\" \"improperly calling multi-line macro", "\"hint\": \" 284 | #endif\\n | \", }, { \"context\": \"./src/graph.cc: In member", "None, \"line\": None, \"function\": None, \"info\": \" Manually-specified variables were not used by", "\" CMAKE_INSTALL_BINDIR\\n\" \" CMAKE_INSTALL_DATAROOTDIR\\n\" \" CMAKE_INSTALL_INCLUDEDIR\\n\" \" CMAKE_INSTALL_LIBDIR\\n\" \" CMAKE_INSTALL_LIBEXECDIR\\n\" \" CMAKE_INSTALL_OLDINCLUDEDIR\\n\" \"", "is pre-generated.)\", }, ], id=\"autotools\", ), pytest.param( [ { \"ref\": \"libjpeg/1.2.3\", \"name\": \"libjpeg\",", "recent call first):\\n\" \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\\n\" \" CMakeLists.txt:7 (include)\", }, { \"file\": \"libmysql/authentication_ldap/CMakeLists.txt\",", "\"line\": \"1559\", \"column\": \"2\", \"severity\": \"ERROR\", \"category\": None, \"info\": \"Problem encountered: Could not", "expects argument of type ‘void*’, \" \"but argument 2 has type ‘const Edge*’\",", "install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"line\": \"565\", \"severity\": None, }, { \"from\": \"configure\",", "\"'strcat': This function or variable may be unsafe. Consider using \" \"strcat_s instead.", "\"info\": \"package is corrupted\", \"severity\": \"WARN\", \"severity_l\": None, }, { \"ref\": \"libmysqlclient/8.0.25\", \"name\":", "\"/source_subfolder/common/socket_utils.cc(43): warning C4312: 'reinterpret_cast': conversion \" \"from 'int' to 'HANDLE' of greater size\",", "\" \"strcat_s instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help for", "text\", \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\", \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52): warning: extension used \" \"[-Wlanguage-extension-token]\", \"ZEXTERN", "be able to build PostgreSQL from Git nor\", \"*** change any of the", "sizeof(reicevedSignals));\\n\" \" ^~~~~~\", }, { \"context\": \"\", \"file\": \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\", \"line\": \"92\", \"column\": None,", "libmysql/authentication_ldap/CMakeLists.txt:30 (MESSAGE):\", \" Skipping the LDAP client authentication plugin\", \"\", \"\", \"In file", "the official distribution of\" \"\\n*** PostgreSQL then you do not need to worry", "support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 772 | #define", "\"\\u2018atk_text_range_get_type_once\\u2019:\\n\", \"file\": \"../source_subfolder/atk/atktext.c\", \"line\": \"1640\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"ISO C prohibits", "'deprecated directive: ‘%name-prefix \"constexpYY\"’, use ‘%define ' \"api.prefix {constexpYY}’\", \"category\": \"-Wdeprecated\", \"project\": None,", "^~~~~~~~~~~~~~~~~~~\", \"CMake Warning:\", \" Manually-specified variables were not used by the project:\", \"\",", "nor\" \"\\n*** change any of the parser definition files. You can obtain Bison", "' 35 | %name-prefix \"constexpYY\"', \" | ^~~~~~~~~~~~~~~~~~~~~~~~~\" \" | %define api.prefix {constexpYY}\",", "compiler = request.node.callspec.id matches = list( match.groupdict() for match in re.finditer(Regex.get(compiler), \"\\n\".join(output)) )", "../../src/include/c.h:54,\", \" from ../../src/include/postgres.h:46,\", \" from stringinfo.c:20:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not", "| %define api.prefix \" \"{constexpYY}\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": None,", "\"line\": \"1640\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"ISO C prohibits argument conversion to", "range checked by comparison on this line\", \"ebcdic.c:284: warning: ISO C forbids an", "\"column\": None, \"project\": None, \"hint\": None, }, { \"context\": \"In file included from", "from ../source_subfolder/atk/atk.h:25,\", \" from ../source_subfolder/atk/atktext.c:22:\", \"../source_subfolder/atk/atktext.c: In function \\u2018atk_text_range_get_type_once\\u2019:\", \"../source_subfolder/atk/atktext.c:1640:52: warning: ISO C", "\"severity\": \"warning\", \"info\": \"passing 'unsigned int [4]' to parameter of type 'int *'", "used\", \"category\": \"-Wlanguage-extension-token\", \"project\": None, \"hint\": \"\" \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t,", "\"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\", \"line\": \"35\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"OpenSSL 1.1.1l 24 Aug 2021\",", "\"/build/source_subfolder/bzip2.c:1073:11: warning: ignoring return value of ‘fchown’, declared \" \"with attribute warn_unused_result [-Wunused-result]\",", "\" \"with attribute warn_unused_result [-Wunused-result]\", \" 1073 | (void) fchown ( fd, fileMetaInfo.st_uid,", "checked by comparison on this line\", \"ebcdic.c:284: warning: ISO C forbids an empty", "nfields = sscanf (line, \"%lx-%lx %9s %lx %9s %ld %s\",\\n' \" | ~~^\\n\"", "is corrupted\", \"WARN: libmysqlclient/8.0.25: requirement openssl/1.1.1m \" \"overridden by poco/1.11.1 to openssl/1.1.1l\", \"In", "unsigned int *’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" ' 215 | nfields", "\"In file included from include\\\\internal/refcount.h:21:\", \"In file included from C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\", \"C:\\\\Program Files (x86)\\\\Microsoft", "fileMetaInfo.st_uid, fileMetaInfo.st_gid );\", \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", \"/source_subfolder/src/constexp.y:35.1-25: warning: deprecated directive: ‘%name-prefix \" '\"constexpYY\"’,", "sign\", \"category\": \"-Wpointer-sign\", \"project\": \"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\", \"hint\": None, }, { \"context\": \"\", \"file\": \"clang-cl\",", "(most recent call first):\", \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\", \" CMakeLists.txt:7 (include)\", \"\", \"\", \"CMake", "\" from ../source_subfolder/atk/atkobject.h:27,\", \" from ../source_subfolder/atk/atk.h:25,\", \" from ../source_subfolder/atk/atktext.c:22:\", \"../source_subfolder/atk/atktext.c: In function \\u2018atk_text_range_get_type_once\\u2019:\",", "| long unsigned int *\", \"In file included from ../../src/include/postgres.h:47,\", \" from rmtree.c:15:\",", "\" | |\", \" | void*\", \"ninja/1.9.0 (test package): WARN: This conanfile has", "from ../../src/include/postgres.h:46,\\n\" \" from stringinfo.c:20:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\",", "\"warning\", \"info\": \"OpenSSL 1.1.1l 24 Aug 2021\", \"category\": \"-W#pragma-messages\", \"project\": None, \"hint\": \"", "\"‘applySavedFileAttrToOutputFile’:\\n\", \"file\": \"/build/source_subfolder/bzip2.c\", \"line\": \"1073\", \"column\": \"11\", \"severity\": \"warning\", \"info\": \"\" \"ignoring return", "\"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" ' 409 | printf(\"] 0x%p\\\\n\", this);\\n' \"", "\"-Wimplicit-function-declaration\", \"project\": None, \"hint\": \"\" \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\\n\" \" ^~~~~~\", }, {", "\"file\": \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h\", \"line\": \"15\", \"column\": \"2\", \"severity\": \"error\", \"category\":", "`SETUP_STACK_POINTER' with 0 parameters\", \"category\": \"-w+macro-params-legacy\", \"project\": None, \"hint\": None, }, { \"context\":", "supported when compiling as C\\n\" \" ^\", \"project\": None, }, { \"context\": \"\",", "is 4.8.0\", }, ], id=\"build\", ), ] @pytest.mark.parametrize(\"expected\", dataset) def test_warnings_regex(expected, request): compiler", "\"\" ' 35 | %name-prefix \"constexpYY\"\\n' \" | ^~~~~~~~~~~~~~~~~~~~~~~~~ | %define api.prefix \"", "from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres.h:46,\\n\" \" from stringinfo.c:20:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\":", "\"severity\": \"warning\", \"info\": \"\" \"format ‘%p’ expects argument of type ‘void*’, \" \"but", "first):\\n\" \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\\n\" \" CMakeLists.txt:7 (include)\", }, { \"file\": \"libmysql/authentication_ldap/CMakeLists.txt\", \"line\": \"30\",", "\"30\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"context\": None, \"info\": \" Skipping the LDAP client", "type ‘long int *’, but argument 8 \" \"has type ‘long unsigned int", "\"api.prefix {constexpYY}’\", \"category\": \"-Wdeprecated\", \"project\": None, \"hint\": \"\" ' 35 | %name-prefix \"constexpYY\"\\n'", "\"line\": None, \"function\": None, \"info\": \"\" \" Manually-specified variables were not used by", "\"../../src/include/pg_config.h:772:24: warning: ISO C does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \" 772", "(MESSAGE):\", \" Skipping the LDAP client authentication plugin\", \"\", \"\", \"In file included", "\"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" ' 215 | nfields = sscanf (line,", "or variable \" \"may be unsafe. Consider using strcat_s instead. To disable deprecation,", "(void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\", \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", \"/source_subfolder/src/constexp.y:35.1-25: warning: deprecated", "int *\", \"In file included from ../../src/include/postgres.h:47,\", \" from rmtree.c:15:\", \"rmtree.c: In function", "from ../source_subfolder/atk/atktext.c:22:\", \"../source_subfolder/atk/atktext.c: In function \\u2018atk_text_range_get_type_once\\u2019:\", \"../source_subfolder/atk/atktext.c:1640:52: warning: ISO C prohibits argument conversion", "expects argument of type \" \"\\u2018long int *\\u2019, but argument 8 has type", "\" | ^~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"source_subfolder/src/tramp.c\", \"line\": \"215\", \"column\": \"52\",", "\"52\", \"severity\": \"warning\", \"info\": \"format ‘%ld’ expects argument of type ‘long int *’,", "\"WARNING: this is important\", \"warning: Boost.Build engine (b2) is 4.8.0\", \"./src/graph.cc: In member", "\"context\": \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\", \"file\": \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\", \"line\": \"146\", \"column\": \"52\", \"severity\":", "the official distribution of\", \"*** PostgreSQL then you do not need to worry", "\"\" \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\\n\" \" | ^~~~~~~~~~~~~~~~~~~\", }, {", "[ { \"ref\": \"libjpeg/1.2.3\", \"name\": \"libjpeg\", \"version\": \"1.2.3\", \"user\": None, \"channel\": None, \"info\":", "from ../../src/include/postgres_fe.h:25,\\n\" \" from archive.c:19:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\",", "\"line\": None, \"column\": None, \"project\": None, \"hint\": None, }, { \"context\": \"In file", "does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \" 772 | #define PG_INT128_TYPE __int128\",", "\" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\", \" CMakeLists.txt:7 (include)\", \"\", \"\", \"CMake Warning at libmysql/authentication_ldap/CMakeLists.txt:30 (MESSAGE):\",", "prohibits argument conversion to union type\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \"", "' 409 | printf(\"] 0x%p\\\\n\", this);\\n' \" | ~^\\n\" \" | |\\n\" \"", "\" #pragma message (OPENSSL_VERSION_TEXT POCO_INTERNAL_OPENSSL_BUILD)\", \" ^\", \"source_subfolder/meson.build:1559:2: ERROR: Problem encountered: \" \"Could", "C does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \" 772 | #define PG_INT128_TYPE", "\" \"‘applySavedFileAttrToOutputFile’:\\n\", \"file\": \"/build/source_subfolder/bzip2.c\", \"line\": \"1073\", \"column\": \"11\", \"severity\": \"warning\", \"info\": \"\" \"ignoring", "not used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \" CMAKE_INSTALL_BINDIR\", \" CMAKE_INSTALL_DATAROOTDIR\", \"", "not find LDAP\", \"Call Stack (most recent call first):\", \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\", \"", "\" CMakeLists.txt:7 (include)\", \"\", \"\", \"CMake Warning at libmysql/authentication_ldap/CMakeLists.txt:30 (MESSAGE):\", \" Skipping the", "\"hint\": \"#error <stdatomic.h> is not yet supported when compiling as C\\n\" \" ^\",", "be applied. Rerun with option \" \"'--update'. [-Wother]\", \"/source_subfolder/common/socket_utils.cc(43): warning C4312: 'reinterpret_cast': conversion", "this line\", \"ebcdic.c:284: warning: ISO C forbids an empty translation unit [-Wpedantic]\", \"", "\"1.2.3\", \"user\": None, \"channel\": None, \"info\": \"package is corrupted\", \"severity\": \"WARN\", \"severity_l\": None,", "\"-Wlanguage-extension-token\", \"project\": None, \"hint\": \"\" \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\\n\" \"", "'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : \" \"return code '0x1'\", \"clang-cl: warning: /: 'linker' input unused [-Wunused-command-line-argument]\",", "\" \"‘Em_FilteringQmFu_processSensorSignals’:\\n\", \"file\": \"src/main/src/Em_FilteringQmFu.c\", \"line\": \"266\", \"column\": \"5\", \"severity\": \"warning\", \"info\": \"implicit declaration", "\"./src/graph.cc: In member function \" \"\\u2018void Edge::Dump(const char*) const\\u2019:\\n\", \"file\": \"./src/graph.cc\", \"line\": \"409\",", "Consider using \" \"strcat_s instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online", "\" from rmtree.c:15:\\n\" \"rmtree.c: In function ‘rmtree’:\\n\" \"In file included from ../../src/include/c.h:54,\\n\" \"", "use ‘%define api.prefix {constexpYY}’ [-Wdeprecated]', ' 35 | %name-prefix \"constexpYY\"', \" | ^~~~~~~~~~~~~~~~~~~~~~~~~\"", "\"severity\": \"Warning\", \"function\": \"MESSAGE\", \"info\": \" Could not find LDAP\", \"context\": \"\" \"Call", "not determine size of size_t.\", \"\", ] dataset = [ pytest.param( [ {", "\"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h\", \"line\": \"15\", \"column\": \"2\", \"severity\": \"error\", \"category\": None,", "\"-Wunused-result\", \"project\": None, \"hint\": \"\" \" 1073 | (void) fchown ( fd, fileMetaInfo.st_uid,", "' 215 | nfields = sscanf (line, \"%lx-%lx %9s %lx %9s %ld %s\",\\n'", "\"category\": \"-Wdeprecated\", \"project\": None, \"hint\": \"\" ' 35 | %name-prefix \"constexpYY\"\\n' \" |", "\"project\": None, \"hint\": \"\" \" 1073 | (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid", "Studio\\\\include\\\\stdatomic.h(15,2): \" \"error: <stdatomic.h> is not yet supported when compiling as C\", \"#error", "to build PostgreSQL from Git nor\", \"*** change any of the parser definition", "%lx %9s %ld %s\",\\n' \" | ~~^\\n\" \" | |\\n\" \" | long", "\"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\\n\"", "\"161\", \"column\": None, \"severity\": \"note\", \"category\": None, \"project\": None, \"info\": \"index 'blockSize100k' range", "*\\u2019, but argument 8 has type \\u2018long unsigned int *\\u2019 [-Wformat=]\", ' 215", "| #define PG_INT128_TYPE __int128\\n\" \" | ^~~~~~~~\", }, { \"context\": \"\" \"In file", "\"info\": \"\" \"format ‘%p’ expects argument of type ‘void*’, \" \"but argument 2", "{ \"ref\": \"libmysqlclient/8.0.25\", \"name\": \"libmysqlclient\", \"version\": \"8.0.25\", \"user\": None, \"channel\": None, \"severity_l\": \"WARN\",", "int *\\n\" \" | %ld\\n\" \" 216 | &start, &end, perm, &offset, dev,", "defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"CMake Warning:\", \" Manually-specified variables were", "#pragma message (OPENSSL_VERSION_TEXT \" \"POCO_INTERNAL_OPENSSL_BUILD)\\n\" \" ^\", }, { \"context\": \"\", \"file\": \"source_subfolder/meson.build\",", "\"ignoring return value of ‘fchown’, declared with attribute warn_unused_result\", \"category\": \"-Wunused-result\", \"project\": None,", "Skipping the LDAP client authentication plugin\", }, { \"context\": None, \"severity\": \"Warning\", \"file\":", "] @pytest.mark.parametrize(\"expected\", dataset) def test_warnings_regex(expected, request): compiler = request.node.callspec.id matches = list( match.groupdict()", "\" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"CMake Warning:\", \" Manually-specified variables were not used by", "None, \"ref\": \"ninja/1.9.0\", \"name\": \"ninja\", \"version\": \"1.9.0\", \"channel\": None, \"user\": None, \"info\": \"This", "ISO C does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \" 772 | #define", "{ \"context\": \"\", \"file\": \"src/port/pg_crc32c_sse42_choose.c\", \"line\": \"41\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"passing", "\" | %ld\", \" 216 | &start, &end, perm, &offset, dev, &inode, file);\",", "index 'blockSize100k' range checked by comparison on this line\", \"ebcdic.c:284: warning: ISO C", "\" | |\\n\" \" | long unsigned int *\", }, { \"context\": \"\"", "not used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", }, { \"file\": \"cmake/ldap.cmake\", \"line\":", "\"severity\": \"warning\", \"info\": \"extension used\", \"category\": \"-Wlanguage-extension-token\", \"project\": None, \"hint\": \"\" \"ZEXTERN z_off64_t", "[4]' to \" \"parameter of type 'int *' converts between pointers to integer", "variables were not used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\" \" CMAKE_INSTALL_BINDIR\\n\" \"", "\" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\" \" CMAKE_INSTALL_BINDIR\\n\" \" CMAKE_INSTALL_DATAROOTDIR\\n\" \" CMAKE_INSTALL_INCLUDEDIR\\n\" \" CMAKE_INSTALL_LIBDIR\\n\" \" CMAKE_INSTALL_LIBEXECDIR\\n\" \"", "Aug 2021\", \"category\": \"-W#pragma-messages\", \"project\": None, \"hint\": \" #pragma message (OPENSSL_VERSION_TEXT \" \"POCO_INTERNAL_OPENSSL_BUILD)\\n\"", "*\", }, { \"context\": \"\" \"In file included from ../../src/include/postgres.h:47,\\n\" \" from rmtree.c:15:\\n\"", "None, \"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\": None, \"info\": \" Manually-specified variables", "\"configure: WARNING:\", \"*** Without Bison you will not be able to build PostgreSQL", "\"hint\": \"\" \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\\n\" \" | ^~~~~~~~~~~~~~~~~~~\", },", "of type 'int *' converts \" \"between pointers to integer types with different", "at cmake/ldap.cmake:158 (MESSAGE):\", \" Could not find LDAP\", \"Call Stack (most recent call", "\"clang-cl\", \"severity\": \"warning\", \"info\": \"/: 'linker' input unused\", \"category\": \"-Wunused-command-line-argument\", \"line\": None, \"column\":", "| #endif\", \" | \", \"WARNING: this is important\", \"warning: Boost.Build engine (b2)", "\" \"multi-line macro `SETUP_STACK_POINTER' with 0 parameters [-w+macro-params-legacy]\", \"some text\", \"In file included", "= [ pytest.param( [ { \"context\": \"src/main/src/Em_FilteringQmFu.c: In function \" \"‘Em_FilteringQmFu_processSensorSignals’:\\n\", \"file\": \"src/main/src/Em_FilteringQmFu.c\",", "\"format ‘%p’ expects argument of type ‘void*’, \" \"but argument 2 has type", "None, }, { \"context\": \"\", \"file\": \"clang-cl\", \"severity\": \"warning\", \"info\": \"/: 'linker' input", ");\\n\" \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": \"35\", \"column\":", "\"772\", \"column\": \"24\", \"severity\": \"warning\", \"info\": \"ISO C does not support ‘__int128’ types\",", "\"In file included from C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\", \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h(15,2): \" \"error: <stdatomic.h>", "\"warning\", \"info\": \"ISO C does not support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None,", "is important\", \"name\": None, \"ref\": None, \"severity\": None, \"severity_l\": \"WARNING\", \"user\": None, \"version\":", "important\", \"name\": None, \"ref\": None, \"severity\": None, \"severity_l\": \"WARNING\", \"user\": None, \"version\": None,", "variable \" \"may be unsafe. Consider using strcat_s instead. To disable deprecation, use", "\"column\": None, \"severity\": \"warning\", \"info\": \"ISO C forbids an empty translation unit\", \"category\":", "\"\" \" Manually-specified variables were not used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\",", "variables were not used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"\", \"\", \"libjpeg/1.2.3:", "install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"CMake Warning:\", \" Manually-specified variables were not used", "warning: ignoring return value of ‘fchown’, declared \" \"with attribute warn_unused_result [-Wunused-result]\", \"", "\" Manually-specified variables were not used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"\",", "function ‘rmtree’:\\n\" \"In file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres.h:46,\\n\" \" from stringinfo.c:20:\\n\",", "of greater size\", \"category\": \"C4312\", \"project\": None, \"hint\": None, }, { \"file\": \"C:\\\\source_subfolder\\\\bzlib.c\",", "\"info\": \"OpenSSL 1.1.1l 24 Aug 2021\", \"category\": \"-W#pragma-messages\", \"project\": None, \"hint\": \" #pragma", "| #endif\\n | \", }, { \"context\": \"./src/graph.cc: In member function \" \"\\u2018void", "\"\" \" 772 | #define PG_INT128_TYPE __int128\\n\" \" | ^~~~~~~~\", }, { \"context\":", "were not used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\" \" CMAKE_INSTALL_BINDIR\\n\" \" CMAKE_INSTALL_DATAROOTDIR\\n\"", "to union type\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 1640 | G_DEFINE_BOXED_TYPE", "LDAP client authentication plugin\", }, { \"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\":", "\" | ~^\\n\" \" | |\\n\" \" | void*\", }, { \"context\": \"\",", "supported when compiling as C\", \"#error <stdatomic.h> is not yet supported when compiling", "of type \" \"\\u2018long int *\\u2019, but argument 8 has type \\u2018long unsigned", "}, ], id=\"autotools\", ), pytest.param( [ { \"ref\": \"libjpeg/1.2.3\", \"name\": \"libjpeg\", \"version\": \"1.2.3\",", "\"info\": \"ISO C does not support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\":", "\"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": \"35\", \"column\": \"1-25\", \"severity\": \"warning\", \"info\": 'deprecated directive:", "to worry about this, because the Bison\", \"*** output is pre-generated.)\", \"end\", \"CMake", "' 215 | nfields = sscanf (line, \"%lx-%lx %9s %lx %9s %ld %s\",',", "\"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\", \"src/main/src/Em_FilteringQmFu.c:266:5: warning: implicit declaration of function \" \"\\u2018memset\\u2019 [-Wimplicit-function-declaration]\", \" memset(&reicevedSignals, 0,", "improperly calling \" \"multi-line macro `SETUP_STACK_POINTER' with 0 parameters [-w+macro-params-legacy]\", \"some text\", \"In", "find LDAP\", \"Call Stack (most recent call first):\", \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\", \" CMakeLists.txt:7", "(most recent call first):\\n\" \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\\n\" \" CMakeLists.txt:7 (include)\", }, { \"file\":", "char*) const\\u2019:\\n\", \"file\": \"./src/graph.cc\", \"line\": \"409\", \"column\": \"16\", \"severity\": \"warning\", \"info\": \"\" \"format", "\\u2018%p\\u2019 expects argument of type \" \"\\u2018void*\\u2019, but argument 2 has type \\u2018const", "openssl/1.1.1l\", \"In file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres_fe.h:25,\", \" from archive.c:19:\", \"../../src/include/pg_config.h:772:24:", "\"-Wpedantic\", \"project\": None, \"hint\": \" 284 | #endif\\n | \", }, { \"context\":", "<stdatomic.h> is not yet supported when compiling as C\\n\" \" ^\", \"project\": None,", "\" \"'--update'. [-Wother]\", \"/source_subfolder/common/socket_utils.cc(43): warning C4312: 'reinterpret_cast': conversion \" \"from 'int' to 'HANDLE'", "official distribution of\", \"*** PostgreSQL then you do not need to worry about", "poco/1.11.1 to openssl/1.1.1l\", }, { \"channel\": None, \"info\": \"this is important\", \"name\": None,", "^\", \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10): \" \"warning: OpenSSL 1.1.1l 24 Aug 2021 [-W#pragma-messages]\", \" #pragma message", "*' converts \" \"between pointers to integer types with different sign\", \"category\": \"-Wpointer-sign\",", "(include)\", \"\", \"\", \"CMake Warning at libmysql/authentication_ldap/CMakeLists.txt:30 (MESSAGE):\", \" Skipping the LDAP client", "‘memset’\", \"category\": \"-Wimplicit-function-declaration\", \"project\": None, \"hint\": \"\" \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\\n\" \" ^~~~~~\",", "\" \"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\", \"src/main/src/Em_FilteringQmFu.c:266:5: warning: implicit declaration of function \" \"\\u2018memset\\u2019 [-Wimplicit-function-declaration]\", \" memset(&reicevedSignals,", "file included from crypto\\\\asn1\\\\a_sign.c:22:\\n\" \"In file included from include\\\\crypto/evp.h:11:\\n\" \"In file included from", "\"function\": None, \"info\": \"\" \" Manually-specified variables were not used by the project:\\n\"", "%9s %lx %9s %ld %s\",\\n' \" | ~~^\\n\" \" | |\\n\" \" |", "int));\\n\" \" ^\", }, { \"context\": \"/build/source_subfolder/bzip2.c: In function \" \"‘applySavedFileAttrToOutputFile’:\\n\", \"file\": \"/build/source_subfolder/bzip2.c\",", "include\\\\crypto/evp.h:11:\\n\" \"In file included from include\\\\internal/refcount.h:21:\\n\" \"In file included from \" \"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\", \"file\":", "\" | ^~~~~~~~\", \"configure: WARNING:\", \"*** Without Bison you will not be able", "}, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": None, \"column\": None, \"severity\": \"warning\", \"info\":", "}, { \"context\": \"\", \"file\": \"source_subfolder/meson.build\", \"line\": \"1559\", \"column\": \"2\", \"severity\": \"ERROR\", \"category\":", "function \" \"\\u2018memset\\u2019 [-Wimplicit-function-declaration]\", \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\", \" ^~~~~~\", \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92: warning: improperly", "[ { \"file\": \"/source_subfolder/common/socket_utils.cc\", \"line\": \"43\", \"column\": None, \"severity\": \"warning\", \"info\": \"'reinterpret_cast': conversion", "from ../source_subfolder/atk/atktext.c:22:\\n\" \"../source_subfolder/atk/atktext.c: In function \" \"\\u2018atk_text_range_get_type_once\\u2019:\\n\", \"file\": \"../source_subfolder/atk/atktext.c\", \"line\": \"1640\", \"column\": \"52\",", "\"version\": \"1.9.0\", \"channel\": None, \"user\": None, \"info\": \"This conanfile has no build step\",", "\" ^\", \"source_subfolder/meson.build:1559:2: ERROR: Problem encountered: \" \"Could not determine size of size_t.\",", "passing 'unsigned int [4]' to \" \"parameter of type 'int *' converts between", "{ \"context\": \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\", \"file\": \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\", \"line\": \"146\", \"column\": \"52\",", "None, \"column\": None, \"severity\": \"warning\", \"info\": \"fix-its can be applied. Rerun with option", "\"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10): \" \"warning: OpenSSL 1.1.1l 24 Aug 2021 [-W#pragma-messages]\", \" #pragma message (OPENSSL_VERSION_TEXT", "`SETUP_STACK_POINTER' with 0 parameters [-w+macro-params-legacy]\", \"some text\", \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\", \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52):", "\"channel\": None, \"severity_l\": \"WARN\", \"severity\": None, \"info\": \"requirement openssl/1.1.1m overridden by poco/1.11.1 to", "../source_subfolder/atk/atkobject.h:27,\", \" from ../source_subfolder/atk/atk.h:25,\", \" from ../source_subfolder/atk/atktext.c:22:\", \"../source_subfolder/atk/atktext.c: In function \\u2018atk_text_range_get_type_once\\u2019:\", \"../source_subfolder/atk/atktext.c:1640:52: warning:", "{ \"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\": None, \"info\": \"", "worry about this, because the Bison\", \"*** output is pre-generated.)\", \"end\", \"CMake Warning", "‘applySavedFileAttrToOutputFile’:\", \"/build/source_subfolder/bzip2.c:1073:11: warning: ignoring return value of ‘fchown’, declared \" \"with attribute warn_unused_result", "argument conversion to \" \"union type [-Wpedantic]\", \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range,", "\"NMAKE : fatal error U1077: 'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : \" \"return code '0x1'\", \"clang-cl: warning:", "\" #pragma message (OPENSSL_VERSION_TEXT \" \"POCO_INTERNAL_OPENSSL_BUILD)\\n\" \" ^\", }, { \"context\": \"\", \"file\":", "#!/usr/bin/env python # -*- coding: UTF-8 -*- import re import pytest from conmon.warnings", "\" CMAKE_INSTALL_LIBDIR\", \" CMAKE_INSTALL_LIBEXECDIR\", \" CMAKE_INSTALL_OLDINCLUDEDIR\", \" MAKE_INSTALL_SBINDIR\", \"\", \"\", \"source_subfolder/src/tramp.c:215:52: warning: format", "pytest.param( [ { \"from\": \"Makefile.config\", \"info\": \"No sys/sdt.h found, no SDT events are", "help for details.\", \"project\": None, \"hint\": ' strcat(mode2,\"b\"); /* binary mode */\\n ^',", "Stack (most recent call first):\", \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\", \" CMakeLists.txt:7 (include)\", \"\", \"\",", "\" ^\", \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10): \" \"warning: OpenSSL 1.1.1l 24 Aug 2021 [-W#pragma-messages]\", \" #pragma", "\" CMAKE_INSTALL_INCLUDEDIR\\n\" \" CMAKE_INSTALL_LIBDIR\\n\" \" CMAKE_INSTALL_LIBEXECDIR\\n\" \" CMAKE_INSTALL_OLDINCLUDEDIR\\n\" \" MAKE_INSTALL_SBINDIR\", }, ], id=\"cmake\",", "obtain Bison from\", \"*** a GNU mirror site. (If you are using the", "\"*** a GNU mirror site. (If you are using the official distribution of\",", "G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\", \" | ^~~~~~~~~~~~~~~~~~~\", \"CMake Warning:\", \" Manually-specified variables were", "C\", \"#error <stdatomic.h> is not yet supported when compiling as C\", \" ^\",", "(void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\\n\" \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", }, { \"context\":", "from\" \"\\n*** a GNU mirror site. (If you are using the official distribution", "\"Warning\", \"function\": \"MESSAGE\", \"context\": None, \"info\": \" Skipping the LDAP client authentication plugin\",", "file included from include\\\\crypto/evp.h:11:\\n\" \"In file included from include\\\\internal/refcount.h:21:\\n\" \"In file included from", "fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\", \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", \"/source_subfolder/src/constexp.y:35.1-25: warning: deprecated directive: ‘%name-prefix \"", "\"hint\": \"\" ' 215 | nfields = sscanf (line, \"%lx-%lx %9s %lx %9s", "), pytest.param( [ { \"file\": \"/source_subfolder/common/socket_utils.cc\", \"line\": \"43\", \"column\": None, \"severity\": \"warning\", \"info\":", "\"ERROR\", \"category\": None, \"info\": \"Problem encountered: Could not determine size of size_t.\", \"project\":", "\"column\": None, \"severity\": \"warning\", \"info\": \"'reinterpret_cast': conversion from 'int' to 'HANDLE' of greater", "\"line\": \"15\", \"column\": \"2\", \"severity\": \"error\", \"category\": None, \"info\": \"<stdatomic.h> is not yet", "\" from /package/include/glib-2.0/gobject/gbinding.h:29,\", \" from /package/include/glib-2.0/glib-object.h:22,\", \" from ../source_subfolder/atk/atkobject.h:27,\", \" from ../source_subfolder/atk/atk.h:25,\", \"", "from include\\\\crypto/evp.h:11:\\n\" \"In file included from include\\\\internal/refcount.h:21:\\n\" \"In file included from \" \"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\",", "Regex output = [ \"src/main/src/Em_FilteringQmFu.c: In function \" \"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\", \"src/main/src/Em_FilteringQmFu.c:266:5: warning: implicit declaration", "not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \" 772 | #define PG_INT128_TYPE __int128\", \"", "'int *' converts \" \"between pointers to integer types with different sign\", \"category\":", "parameters\", \"category\": \"-w+macro-params-legacy\", \"project\": None, \"hint\": None, }, { \"context\": \"In file included", "message (OPENSSL_VERSION_TEXT POCO_INTERNAL_OPENSSL_BUILD)\", \" ^\", \"source_subfolder/meson.build:1559:2: ERROR: Problem encountered: \" \"Could not determine", "WARN: This conanfile has no build step\", \"src/port/pg_crc32c_sse42_choose.c(41,10): warning : passing 'unsigned int", "not determine size of size_t.\", \"project\": None, \"hint\": None, }, ], id=\"gnu\", ),", "declaration of function ‘memset’\", \"category\": \"-Wimplicit-function-declaration\", \"project\": None, \"hint\": \"\" \" memset(&reicevedSignals, 0,", "\"10\", \"category\": \"C4996\", \"severity\": \"warning\", \"info\": \"'strcat': This function or variable may be", "\"\", \"libjpeg/1.2.3: WARN: package is corrupted\", \"WARN: libmysqlclient/8.0.25: requirement openssl/1.1.1m \" \"overridden by", "plugin\", \"\", \"\", \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\", \" from /package/include/glib-2.0/gobject/gbinding.h:29,\", \" from", "{ \"context\": \"/build/source_subfolder/bzip2.c: In function \" \"‘applySavedFileAttrToOutputFile’:\\n\", \"file\": \"/build/source_subfolder/bzip2.c\", \"line\": \"1073\", \"column\": \"11\",", "parser definition files. You can obtain Bison from\" \"\\n*** a GNU mirror site.", "by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \" CMAKE_INSTALL_BINDIR\", \" CMAKE_INSTALL_DATAROOTDIR\", \" CMAKE_INSTALL_INCLUDEDIR\", \"", "\"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\", \"info\": \"ISO C does not support ‘__int128’", "\"rmtree.c: In function \\u2018rmtree\\u2019:\", \"In file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres.h:46,\", \"", "\"context\": \"\", \"file\": \"ebcdic.c\", \"line\": \"284\", \"column\": None, \"severity\": \"warning\", \"info\": \"ISO C", "*/\\n ^', }, { \"file\": \"NMAKE\", \"line\": None, \"column\": None, \"severity\": \"fatal error\",", "}, ], id=\"cmake\", ), pytest.param( [ { \"from\": \"Makefile.config\", \"info\": \"No sys/sdt.h found,", "\" ^\", \"Makefile.config:565: No sys/sdt.h found, no SDT events are defined, please install", "In function \" \"\\u2018atk_text_range_get_type_once\\u2019:\\n\", \"file\": \"../source_subfolder/atk/atktext.c\", \"line\": \"1640\", \"column\": \"52\", \"severity\": \"warning\", \"info\":", "\"this is important\", \"name\": None, \"ref\": None, \"severity\": None, \"severity_l\": \"WARNING\", \"user\": None,", "[-Wpedantic]\", \" 284 | #endif\", \" | \", \"WARNING: this is important\", \"warning:", "were not used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"\", \"\", \"libjpeg/1.2.3: WARN:", "See online help for details.\", \"project\": None, \"hint\": ' strcat(mode2,\"b\"); /* binary mode", "None, \"severity\": \"WARNING\", \"info\": \"\" \"\\n*** Without Bison you will not be able", "\"info\": \"<stdatomic.h> is not yet supported when compiling as C\", \"hint\": \"#error <stdatomic.h>", "worry about this, because the Bison\" \"\\n*** output is pre-generated.)\", }, ], id=\"autotools\",", "{ \"context\": \"\", \"file\": \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\", \"line\": \"92\", \"column\": None, \"severity\": \"warning\", \"info\": \"\"", "\" MAKE_INSTALL_SBINDIR\", }, ], id=\"cmake\", ), pytest.param( [ { \"from\": \"Makefile.config\", \"info\": \"No", "void*\", }, { \"context\": \"\", \"file\": \"src/port/pg_crc32c_sse42_choose.c\", \"line\": \"41\", \"column\": \"10\", \"severity\": \"warning\",", "‘%define ' \"api.prefix {constexpYY}’\", \"category\": \"-Wdeprecated\", \"project\": None, \"hint\": \"\" ' 35 |", "binary mode */\\n ^', }, { \"file\": \"NMAKE\", \"line\": None, \"column\": None, \"severity\":", "(include)\", }, { \"file\": \"libmysql/authentication_ldap/CMakeLists.txt\", \"line\": \"30\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"context\": None,", "\"category\": \"C4996\", \"severity\": \"warning\", \"info\": \"'strcat': This function or variable may be unsafe.", "to openssl/1.1.1l\", \"In file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres_fe.h:25,\", \" from archive.c:19:\",", "file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\", \"file\": \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\", \"line\": \"146\", \"column\": \"52\", \"severity\": \"warning\", \"info\":", "\"\\u2018void Edge::Dump(const char*) const\\u2019:\\n\", \"file\": \"./src/graph.cc\", \"line\": \"409\", \"column\": \"16\", \"severity\": \"warning\", \"info\":", "UTF-8 -*- import re import pytest from conmon.warnings import Regex output = [", "^\", }, { \"context\": \"\", \"file\": \"source_subfolder/meson.build\", \"line\": \"1559\", \"column\": \"2\", \"severity\": \"ERROR\",", "by poco/1.11.1 to openssl/1.1.1l\", \"In file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres_fe.h:25,\", \"", "\"severity\": \"warning\", \"info\": \"implicit declaration of function ‘memset’\", \"category\": \"-Wimplicit-function-declaration\", \"project\": None, \"hint\":", "pre-generated.)\", }, ], id=\"autotools\", ), pytest.param( [ { \"ref\": \"libjpeg/1.2.3\", \"name\": \"libjpeg\", \"version\":", "be applied. Rerun with option '--update'.\", \"category\": \"-Wother\", \"project\": None, \"hint\": None, },", "\"project\": None, \"hint\": \"\" \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\\n\" \" |", "\"2\", \"severity\": \"ERROR\", \"category\": None, \"info\": \"Problem encountered: Could not determine size of", "\"_CRT_SECURE_NO_WARNINGS. See online help for details.\", \"project\": None, \"hint\": ' strcat(mode2,\"b\"); /* binary", "\"\", \"\", \"source_subfolder/src/tramp.c:215:52: warning: format \\u2018%ld\\u2019 expects argument of type \" \"\\u2018long int", "|\\n\" \" | long unsigned int *\", }, { \"context\": \"\" \"In file", "fatal error U1077: 'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : \" \"return code '0x1'\", \"clang-cl: warning: /: 'linker'", "| %name-prefix \"constexpYY\"', \" | ^~~~~~~~~~~~~~~~~~~~~~~~~\" \" | %define api.prefix {constexpYY}\", \"/source_subfolder/src/constexp.y: warning:", "None, \"function\": None, \"info\": \"\" \" Manually-specified variables were not used by the", "mode */', \" ^\", \"Makefile.config:565: No sys/sdt.h found, no SDT events are defined,", "To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\", ' strcat(mode2,\"b\");", "sys/sdt.h found, no SDT events are defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\",", "PostgreSQL from Git nor\" \"\\n*** change any of the parser definition files. You", "warning: ISO C does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \"C:\\\\src\\\\bzlib.c(161) : note:", "file included from /package/include/glib-2.0/gobject/gobject.h:24,\", \" from /package/include/glib-2.0/gobject/gbinding.h:29,\", \" from /package/include/glib-2.0/glib-object.h:22,\", \" from ../source_subfolder/atk/atkobject.h:27,\",", "None, \"line\": None, \"function\": None, \"info\": \"\" \" Manually-specified variables were not used", "\"./src/graph.cc: In member function \\u2018void Edge::Dump(const char*) const\\u2019:\", \"./src/graph.cc:409:16: warning: format \\u2018%p\\u2019 expects", "\"return code '0x1'\", \"clang-cl: warning: /: 'linker' input unused [-Wunused-command-line-argument]\", \"In file included", "{ \"file\": \"/source_subfolder/common/socket_utils.cc\", \"line\": \"43\", \"column\": None, \"severity\": \"warning\", \"info\": \"'reinterpret_cast': conversion from", "None, \"hint\": None, }, ], id=\"gnu\", ), pytest.param( [ { \"file\": \"/source_subfolder/common/socket_utils.cc\", \"line\":", "to parameter of type 'int *' converts \" \"between pointers to integer types", "\"severity\": None, }, { \"from\": \"configure\", \"line\": None, \"severity\": \"WARNING\", \"info\": \"\" \"\\n***", "conversion to union type\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 1640 |", "long int *\", \" | %ld\", \" 216 | &start, &end, perm, &offset,", "| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", \"/source_subfolder/src/constexp.y:35.1-25: warning: deprecated directive: ‘%name-prefix \" '\"constexpYY\"’, use ‘%define api.prefix {constexpYY}’", "details.\", ' strcat(mode2,\"b\"); /* binary mode */', \" ^\", \"Makefile.config:565: No sys/sdt.h found,", "to \" \"union type [-Wpedantic]\", \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\", \"", "\"function\": None, \"info\": \" Manually-specified variables were not used by the project:\\n\" \"\\n\"", "int *’, but argument 8 \" \"has type ‘long unsigned int *’\", \"category\":", "included from C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\", \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h(15,2): \" \"error: <stdatomic.h> is not", "0, sizeof(reicevedSignals));\\n\" \" ^~~~~~\", }, { \"context\": \"\", \"file\": \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\", \"line\": \"92\", \"column\":", "\"\" \"improperly calling multi-line macro `SETUP_STACK_POINTER' with 0 parameters\", \"category\": \"-w+macro-params-legacy\", \"project\": None,", "supported when compiling as C\", \" ^\", \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10): \" \"warning: OpenSSL 1.1.1l 24", "None, }, { \"context\": \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\\n\" \"In file included from", "id=\"autotools\", ), pytest.param( [ { \"ref\": \"libjpeg/1.2.3\", \"name\": \"libjpeg\", \"version\": \"1.2.3\", \"user\": None,", "important\", \"warning: Boost.Build engine (b2) is 4.8.0\", \"./src/graph.cc: In member function \\u2018void Edge::Dump(const", "\" | ^~~~~~~~~~~~~~~~~~~\", \"CMake Warning:\", \" Manually-specified variables were not used by the", "(b2) is 4.8.0\", }, ], id=\"build\", ), ] @pytest.mark.parametrize(\"expected\", dataset) def test_warnings_regex(expected, request):", "\" CMAKE_INSTALL_LIBDIR\\n\" \" CMAKE_INSTALL_LIBEXECDIR\\n\" \" CMAKE_INSTALL_OLDINCLUDEDIR\\n\" \" MAKE_INSTALL_SBINDIR\", }, ], id=\"cmake\", ), pytest.param(", "fileMetaInfo.st_uid, fileMetaInfo.st_gid );\\n\" \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\":", "\"215\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"format ‘%ld’ expects argument of type ‘long", "project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"\", \"\", \"libjpeg/1.2.3: WARN: package is corrupted\", \"WARN: libmysqlclient/8.0.25:", "can obtain Bison from\", \"*** a GNU mirror site. (If you are using", "format \\u2018%ld\\u2019 expects argument of type \" \"\\u2018long int *\\u2019, but argument 8", "of function \" \"\\u2018memset\\u2019 [-Wimplicit-function-declaration]\", \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\", \" ^~~~~~\", \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92: warning:", "definition files. You can obtain Bison from\" \"\\n*** a GNU mirror site. (If", "pytest.param( [ { \"severity\": \"warning\", \"info\": \"Boost.Build engine (b2) is 4.8.0\", }, ],", "|\\n\" \" | void*\", }, { \"context\": \"\", \"file\": \"src/port/pg_crc32c_sse42_choose.c\", \"line\": \"41\", \"column\":", "\"\" \"format ‘%p’ expects argument of type ‘void*’, \" \"but argument 2 has", "\"line\": None, \"column\": None, \"severity\": \"fatal error\", \"category\": \"U1077\", \"info\": \"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : return", "\"column\": \"52\", \"severity\": \"warning\", \"info\": \"format ‘%ld’ expects argument of type ‘long int", "LDAP\", \"context\": \"\" \"Call Stack (most recent call first):\\n\" \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\\n\" \"", "\" | long unsigned int *\", }, { \"context\": \"\" \"In file included", "able to build PostgreSQL from Git nor\", \"*** change any of the parser", "You can obtain Bison from\" \"\\n*** a GNU mirror site. (If you are", "when compiling as C\", \" ^\", \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10): \" \"warning: OpenSSL 1.1.1l 24 Aug", "Bison you will not be able to build PostgreSQL from Git nor\", \"***", "| |\", \" | long int *\", \" | %ld\", \" 216 |", "You can obtain Bison from\", \"*** a GNU mirror site. (If you are", "Could not find LDAP\", \"Call Stack (most recent call first):\", \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\",", "include\\\\internal/refcount.h:21:\", \"In file included from C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\", \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h(15,2): \" \"error:", "}, { \"context\": \"\" \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\\n\" \" from /package/include/glib-2.0/gobject/gbinding.h:29,\\n\" \"", "\"version\": \"1.2.3\", \"user\": None, \"channel\": None, \"info\": \"package is corrupted\", \"severity\": \"WARN\", \"severity_l\":", "(b2) is 4.8.0\", \"./src/graph.cc: In member function \\u2018void Edge::Dump(const char*) const\\u2019:\", \"./src/graph.cc:409:16: warning:", "option '--update'.\", \"category\": \"-Wother\", \"project\": None, \"hint\": None, }, { \"context\": \"\" \"In", "{ \"ref\": \"libjpeg/1.2.3\", \"name\": \"libjpeg\", \"version\": \"1.2.3\", \"user\": None, \"channel\": None, \"info\": \"package", "\"line\": \"409\", \"column\": \"16\", \"severity\": \"warning\", \"info\": \"\" \"format ‘%p’ expects argument of", "corrupted\", \"WARN: libmysqlclient/8.0.25: requirement openssl/1.1.1m \" \"overridden by poco/1.11.1 to openssl/1.1.1l\", \"In file", "\"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\": None, \"info\": \"\" \"", "printf(\"] 0x%p\\\\n\", this);', \" | ~^\", \" | |\", \" | void*\", \"ninja/1.9.0", "[-Wdeprecated]', ' 35 | %name-prefix \"constexpYY\"', \" | ^~~~~~~~~~~~~~~~~~~~~~~~~\" \" | %define api.prefix", "greater size\", \"C:\\\\source_subfolder\\\\bzlib.c(1418,10): warning C4996: 'strcat': This function or variable \" \"may be", "is not yet supported when compiling as C\", \"#error <stdatomic.h> is not yet", "unused\", \"category\": \"-Wunused-command-line-argument\", \"line\": None, \"column\": None, \"project\": None, \"hint\": None, }, {", "/package/include/glib-2.0/glib-object.h:22,\", \" from ../source_subfolder/atk/atkobject.h:27,\", \" from ../source_subfolder/atk/atk.h:25,\", \" from ../source_subfolder/atk/atktext.c:22:\", \"../source_subfolder/atk/atktext.c: In function", "\"\", \"file\": \"C:\\\\src\\\\bzlib.c\", \"line\": \"161\", \"column\": None, \"severity\": \"note\", \"category\": None, \"project\": None,", "\"warning\", \"info\": \"'strcat': This function or variable may be unsafe. Consider using \"", "\"warning\", \"info\": \"ISO C forbids an empty translation unit\", \"category\": \"-Wpedantic\", \"project\": None,", "from /package/include/glib-2.0/glib-object.h:22,\\n\" \" from ../source_subfolder/atk/atkobject.h:27,\\n\" \" from ../source_subfolder/atk/atk.h:25,\\n\" \" from ../source_subfolder/atk/atktext.c:22:\\n\" \"../source_subfolder/atk/atktext.c: In", "from include\\\\crypto/evp.h:11:\", \"In file included from include\\\\internal/refcount.h:21:\", \"In file included from C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\", \"C:\\\\Program", "\"severity\": \"warning\", \"info\": \"Boost.Build engine (b2) is 4.8.0\", }, ], id=\"build\", ), ]", "~^\\n\" \" | |\\n\" \" | void*\", }, { \"context\": \"\", \"file\": \"src/port/pg_crc32c_sse42_choose.c\",", "\"C:\\\\source_subfolder\\\\bzlib.c(1418,10): warning C4996: 'strcat': This function or variable \" \"may be unsafe. Consider", "'unsigned int [4]' to parameter of type 'int *' converts \" \"between pointers", "\"project\": None, \"hint\": None, }, ], id=\"msvc\", ), pytest.param( [ { \"context\": None,", "<stdatomic.h> is not yet supported when compiling as C\", \"#error <stdatomic.h> is not", "\"function\": \"MESSAGE\", \"context\": None, \"info\": \" Skipping the LDAP client authentication plugin\", },", "forbids an empty translation unit [-Wpedantic]\", \" 284 | #endif\", \" | \",", "\"context\": \"\", \"file\": \"source_subfolder/src/tramp.c\", \"line\": \"215\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"format ‘%ld’", "{ \"file\": \"C:\\\\source_subfolder\\\\bzlib.c\", \"line\": \"1418\", \"column\": \"10\", \"category\": \"C4996\", \"severity\": \"warning\", \"info\": \"'strcat':", "\"line\": \"215\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"format ‘%ld’ expects argument of type", "you are using the official distribution of\", \"*** PostgreSQL then you do not", "| \", }, { \"context\": \"./src/graph.cc: In member function \" \"\\u2018void Edge::Dump(const char*)", "from archive.c:19:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\", \"info\": \"ISO C", "\" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\", \" ^~~~~~\", \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92: warning: improperly calling \" \"multi-line macro", "772 | #define PG_INT128_TYPE __int128\\n\" \" | ^~~~~~~~\", }, { \"context\": \"\" \"In", "yet supported when compiling as C\", \"hint\": \"#error <stdatomic.h> is not yet supported", "CMAKE_INSTALL_LIBEXECDIR\\n\" \" CMAKE_INSTALL_OLDINCLUDEDIR\\n\" \" MAKE_INSTALL_SBINDIR\", }, ], id=\"cmake\", ), pytest.param( [ { \"from\":", "\"info\": \"passing 'unsigned int [4]' to parameter of type 'int *' converts \"", "\"project\": None, \"hint\": \" #pragma message (OPENSSL_VERSION_TEXT \" \"POCO_INTERNAL_OPENSSL_BUILD)\\n\" \" ^\", }, {", "\" from /package/include/glib-2.0/glib-object.h:22,\\n\" \" from ../source_subfolder/atk/atkobject.h:27,\\n\" \" from ../source_subfolder/atk/atk.h:25,\\n\" \" from ../source_subfolder/atk/atktext.c:22:\\n\" \"../source_subfolder/atk/atktext.c:", "(MYSQL_CHECK_LDAP)\", \" CMakeLists.txt:7 (include)\", \"\", \"\", \"CMake Warning at libmysql/authentication_ldap/CMakeLists.txt:30 (MESSAGE):\", \" Skipping", "}, { \"context\": \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\\n\" \"In file included from include\\\\crypto/evp.h:11:\\n\"", "int [4]' to \" \"parameter of type 'int *' converts between pointers to", "\"warning\", \"info\": \"\" \"improperly calling multi-line macro `SETUP_STACK_POINTER' with 0 parameters\", \"category\": \"-w+macro-params-legacy\",", "can be applied. Rerun with option '--update'.\", \"category\": \"-Wother\", \"project\": None, \"hint\": None,", "compiling as C\", \"hint\": \"#error <stdatomic.h> is not yet supported when compiling as", "included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres.h:46,\", \" from stringinfo.c:20:\", \"../../src/include/pg_config.h:772:24: warning: ISO C", "from ../source_subfolder/atk/atkobject.h:27,\\n\" \" from ../source_subfolder/atk/atk.h:25,\\n\" \" from ../source_subfolder/atk/atktext.c:22:\\n\" \"../source_subfolder/atk/atktext.c: In function \" \"\\u2018atk_text_range_get_type_once\\u2019:\\n\",", "None, }, { \"context\": \"\", \"file\": \"ebcdic.c\", \"line\": \"284\", \"column\": None, \"severity\": \"warning\",", "no build step\", \"severity\": \"WARN\", }, ], id=\"conan\", ), pytest.param( [ { \"severity\":", "2021\", \"category\": \"-W#pragma-messages\", \"project\": None, \"hint\": \" #pragma message (OPENSSL_VERSION_TEXT \" \"POCO_INTERNAL_OPENSSL_BUILD)\\n\" \"", "\"column\": None, \"severity\": \"fatal error\", \"category\": \"U1077\", \"info\": \"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : return \" \"code", "\" from /package/include/glib-2.0/glib-object.h:22,\", \" from ../source_subfolder/atk/atkobject.h:27,\", \" from ../source_subfolder/atk/atk.h:25,\", \" from ../source_subfolder/atk/atktext.c:22:\", \"../source_subfolder/atk/atktext.c:", "\"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\", \"line\": \"146\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"extension used\", \"category\": \"-Wlanguage-extension-token\", \"project\":", "\"passing 'unsigned int [4]' to parameter of type 'int *' converts \" \"between", "id=\"conan\", ), pytest.param( [ { \"severity\": \"warning\", \"info\": \"Boost.Build engine (b2) is 4.8.0\",", "\"\", \"file\": \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\", \"line\": \"92\", \"column\": None, \"severity\": \"warning\", \"info\": \"\" \"improperly calling", "type ‘long unsigned int *’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" ' 215", "int *\", }, { \"context\": \"\" \"In file included from ../../src/include/postgres.h:47,\\n\" \" from", "'int' to 'HANDLE' of greater size\", \"C:\\\\source_subfolder\\\\bzlib.c(1418,10): warning C4996: 'strcat': This function or", "\"409\", \"column\": \"16\", \"severity\": \"warning\", \"info\": \"\" \"format ‘%p’ expects argument of type", "None, \"severity\": \"warning\", \"info\": \"\" \"improperly calling multi-line macro `SETUP_STACK_POINTER' with 0 parameters\",", "\"project\": \"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\", \"hint\": None, }, { \"context\": \"\", \"file\": \"clang-cl\", \"severity\": \"warning\", \"info\":", "\" CMakeLists.txt:7 (include)\", }, { \"file\": \"libmysql/authentication_ldap/CMakeLists.txt\", \"line\": \"30\", \"severity\": \"Warning\", \"function\": \"MESSAGE\",", "\"types [-Wpedantic]\", \" 772 | #define PG_INT128_TYPE __int128\", \" | ^~~~~~~~\", \"configure: WARNING:\",", "type [-Wpedantic]\", \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\", \" | ^~~~~~~~~~~~~~~~~~~\", \"CMake", "%lx %9s %ld %s\",', \" | ~~^\", \" | |\", \" | long", "expects argument of type \" \"\\u2018void*\\u2019, but argument 2 has type \\u2018const Edge*\\u2019", "\"-Wformat=\", \"project\": None, \"hint\": \"\" ' 409 | printf(\"] 0x%p\\\\n\", this);\\n' \" |", "\"category\": \"-Wlanguage-extension-token\", \"project\": None, \"hint\": \"\" \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\\n\"", "no SDT events are defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"CMake Warning:\",", "nfields = sscanf (line, \"%lx-%lx %9s %lx %9s %ld %s\",', \" | ~~^\",", "\"file\": \"source_subfolder/meson.build\", \"line\": \"1559\", \"column\": \"2\", \"severity\": \"ERROR\", \"category\": None, \"info\": \"Problem encountered:", "../../src/include/postgres.h:47,\\n\" \" from rmtree.c:15:\\n\" \"rmtree.c: In function ‘rmtree’:\\n\" \"In file included from ../../src/include/c.h:54,\\n\"", "^\", \"/build/source_subfolder/bzip2.c: In function ‘applySavedFileAttrToOutputFile’:\", \"/build/source_subfolder/bzip2.c:1073:11: warning: ignoring return value of ‘fchown’, declared", ": return \" \"code '0x1'\", \"project\": None, \"hint\": None, }, ], id=\"msvc\", ),", "\" Could not find LDAP\", \"Call Stack (most recent call first):\", \" CMakeListsOriginal.txt:1351", "\"severity\": \"warning\", \"info\": \"ISO C forbids an empty translation unit\", \"category\": \"-Wpedantic\", \"project\":", "\"WARNING\", \"user\": None, \"version\": None, }, { \"severity_l\": None, \"ref\": \"ninja/1.9.0\", \"name\": \"ninja\",", "const\\u2019:\", \"./src/graph.cc:409:16: warning: format \\u2018%p\\u2019 expects argument of type \" \"\\u2018void*\\u2019, but argument", "can be applied. Rerun with option \" \"'--update'. [-Wother]\", \"/source_subfolder/common/socket_utils.cc(43): warning C4312: 'reinterpret_cast':", "[ { \"severity\": \"warning\", \"info\": \"Boost.Build engine (b2) is 4.8.0\", }, ], id=\"build\",", "pointers to integer types with different sign \" \"[-Wpointer-sign] [C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\", \"NMAKE : fatal", "\"In file included from ../../src/include/postgres.h:47,\", \" from rmtree.c:15:\", \"rmtree.c: In function \\u2018rmtree\\u2019:\", \"In", "0 parameters [-w+macro-params-legacy]\", \"some text\", \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\", \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52): warning: extension", "\"5\", \"severity\": \"warning\", \"info\": \"implicit declaration of function ‘memset’\", \"category\": \"-Wimplicit-function-declaration\", \"project\": None,", "\"src/port/pg_crc32c_sse42_choose.c(41,10): warning : passing 'unsigned int [4]' to \" \"parameter of type 'int", "\"libjpeg/1.2.3: WARN: package is corrupted\", \"WARN: libmysqlclient/8.0.25: requirement openssl/1.1.1m \" \"overridden by poco/1.11.1", "\" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"line\": \"565\", \"severity\": None, }, { \"from\": \"configure\", \"line\":", "were not used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \" CMAKE_INSTALL_BINDIR\", \" CMAKE_INSTALL_DATAROOTDIR\",", "\"info\": \"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : return \" \"code '0x1'\", \"project\": None, \"hint\": None, }, ],", "unit [-Wpedantic]\", \" 284 | #endif\", \" | \", \"WARNING: this is important\",", "<reponame>flashdagger/conmon #!/usr/bin/env python # -*- coding: UTF-8 -*- import re import pytest from", "\" | |\", \" | long unsigned int *\", \"In file included from", "\"severity\": None, \"severity_l\": \"WARNING\", \"user\": None, \"version\": None, }, { \"severity_l\": None, \"ref\":", "\"project\": None, \"hint\": None, }, { \"context\": \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\", \"file\":", "\"column\": \"10\", \"severity\": \"warning\", \"info\": \"passing 'unsigned int [4]' to parameter of type", "\"ebcdic.c\", \"line\": \"284\", \"column\": None, \"severity\": \"warning\", \"info\": \"ISO C forbids an empty", "\"WARN\", \"severity_l\": None, }, { \"ref\": \"libmysqlclient/8.0.25\", \"name\": \"libmysqlclient\", \"version\": \"8.0.25\", \"user\": None,", "‘long unsigned int *’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" ' 215 |", "\" \"types [-Wpedantic]\", \"C:\\\\src\\\\bzlib.c(161) : note: index 'blockSize100k' range checked by comparison on", "None, }, ], id=\"gnu\", ), pytest.param( [ { \"file\": \"/source_subfolder/common/socket_utils.cc\", \"line\": \"43\", \"column\":", "\"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92: warning: improperly calling \" \"multi-line macro `SETUP_STACK_POINTER' with 0 parameters [-w+macro-params-legacy]\", \"some", "^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", \"/source_subfolder/src/constexp.y:35.1-25: warning: deprecated directive: ‘%name-prefix \" '\"constexpYY\"’, use ‘%define api.prefix {constexpYY}’ [-Wdeprecated]',", "ISO C prohibits argument conversion to \" \"union type [-Wpedantic]\", \" 1640 |", "input unused\", \"category\": \"-Wunused-command-line-argument\", \"line\": None, \"column\": None, \"project\": None, \"hint\": None, },", "), pytest.param( [ { \"from\": \"Makefile.config\", \"info\": \"No sys/sdt.h found, no SDT events", "does not support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": None, }, {", "\"In file included from crypto\\\\asn1\\\\a_sign.c:22:\\n\" \"In file included from include\\\\crypto/evp.h:11:\\n\" \"In file included", "on this line\", \"hint\": None, }, { \"context\": \"\", \"file\": \"ebcdic.c\", \"line\": \"284\",", "\" \"\\u2018void Edge::Dump(const char*) const\\u2019:\\n\", \"file\": \"./src/graph.cc\", \"line\": \"409\", \"column\": \"16\", \"severity\": \"warning\",", "calling \" \"multi-line macro `SETUP_STACK_POINTER' with 0 parameters [-w+macro-params-legacy]\", \"some text\", \"In file", "\"Could not determine size of size_t.\", \"\", ] dataset = [ pytest.param( [", "by poco/1.11.1 to openssl/1.1.1l\", }, { \"channel\": None, \"info\": \"this is important\", \"name\":", "sscanf (line, \"%lx-%lx %9s %lx %9s %ld %s\",\\n' \" | ~~^\\n\" \" |", "\" 216 | &start, &end, perm, &offset, dev, &inode, file);\", \" | ~~~~~~\",", "argument of type ‘void*’, \" \"but argument 2 has type ‘const Edge*’\", \"category\":", "], id=\"gnu\", ), pytest.param( [ { \"file\": \"/source_subfolder/common/socket_utils.cc\", \"line\": \"43\", \"column\": None, \"severity\":", "is important\", \"warning: Boost.Build engine (b2) is 4.8.0\", \"./src/graph.cc: In member function \\u2018void", "PostgreSQL from Git nor\", \"*** change any of the parser definition files. You", "None, \"severity_l\": \"WARNING\", \"user\": None, \"version\": None, }, { \"severity_l\": None, \"ref\": \"ninja/1.9.0\",", "None, \"hint\": \"\" \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\\n\" \" ^~~~~~\", }, { \"context\": \"\",", "id=\"build\", ), ] @pytest.mark.parametrize(\"expected\", dataset) def test_warnings_regex(expected, request): compiler = request.node.callspec.id matches =", "client authentication plugin\", }, { \"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\": None,", "POCO_INTERNAL_OPENSSL_BUILD)\", \" ^\", \"source_subfolder/meson.build:1559:2: ERROR: Problem encountered: \" \"Could not determine size of", "\"CMake Warning:\", \" Manually-specified variables were not used by the project:\", \"\", \"", "\"\", \"file\": \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\", \"line\": \"35\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"OpenSSL 1.1.1l 24", "\" 284 | #endif\\n | \", }, { \"context\": \"./src/graph.cc: In member function", "\"libjpeg\", \"version\": \"1.2.3\", \"user\": None, \"channel\": None, \"info\": \"package is corrupted\", \"severity\": \"WARN\",", "(OPENSSL_VERSION_TEXT POCO_INTERNAL_OPENSSL_BUILD)\", \" ^\", \"source_subfolder/meson.build:1559:2: ERROR: Problem encountered: \" \"Could not determine size", "checked by comparison on this line\", \"hint\": None, }, { \"context\": \"\", \"file\":", "from include\\\\internal/refcount.h:21:\\n\" \"In file included from \" \"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\", \"file\": \"C:\\\\Program Files (x86)\\\\Microsoft Visual", "when compiling as C\\n\" \" ^\", \"project\": None, }, { \"context\": \"\", \"file\":", "be able to build PostgreSQL from Git nor\" \"\\n*** change any of the", "return \" \"code '0x1'\", \"project\": None, \"hint\": None, }, ], id=\"msvc\", ), pytest.param(", "| (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\", \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", \"/source_subfolder/src/constexp.y:35.1-25: warning:", "\"ISO C prohibits argument conversion to union type\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\":", "%s\",', \" | ~~^\", \" | |\", \" | long int *\", \"", "None, \"hint\": None, }, { \"context\": \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\", \"file\": \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\",", "integer types with different sign \" \"[-Wpointer-sign] [C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\", \"NMAKE : fatal error U1077:", "include\\\\internal/refcount.h:21:\\n\" \"In file included from \" \"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\", \"file\": \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h\",", "*' converts between pointers to integer types with different sign \" \"[-Wpointer-sign] [C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\",", "by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\" \" CMAKE_INSTALL_BINDIR\\n\" \" CMAKE_INSTALL_DATAROOTDIR\\n\" \" CMAKE_INSTALL_INCLUDEDIR\\n\" \"", "Bison you will not be able to build PostgreSQL from Git nor\" \"\\n***", "using the official distribution of\", \"*** PostgreSQL then you do not need to", "openssl/1.1.1l\", }, { \"channel\": None, \"info\": \"this is important\", \"name\": None, \"ref\": None,", "types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 772 | #define PG_INT128_TYPE __int128\\n\"", "with option '--update'.\", \"category\": \"-Wother\", \"project\": None, \"hint\": None, }, { \"context\": \"\"", "\"with attribute warn_unused_result [-Wunused-result]\", \" 1073 | (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid", "converts between pointers to integer types with different sign \" \"[-Wpointer-sign] [C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\", \"NMAKE", "determine size of size_t.\", \"project\": None, \"hint\": None, }, ], id=\"gnu\", ), pytest.param(", "{ \"severity\": \"warning\", \"info\": \"Boost.Build engine (b2) is 4.8.0\", }, ], id=\"build\", ),", "int *\", \" | %ld\", \" 216 | &start, &end, perm, &offset, dev,", "systemtap-sdt-dev\", \"CMake Warning:\", \" Manually-specified variables were not used by the project:\", \"\",", "\"hint\": \" #pragma message (OPENSSL_VERSION_TEXT \" \"POCO_INTERNAL_OPENSSL_BUILD)\\n\" \" ^\", }, { \"context\": \"\",", "@pytest.mark.parametrize(\"expected\", dataset) def test_warnings_regex(expected, request): compiler = request.node.callspec.id matches = list( match.groupdict() for", "strcat_s instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\",", "Edge::Dump(const char*) const\\u2019:\", \"./src/graph.cc:409:16: warning: format \\u2018%p\\u2019 expects argument of type \" \"\\u2018void*\\u2019,", "C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\", \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h(15,2): \" \"error: <stdatomic.h> is not yet supported", "not yet supported when compiling as C\", \" ^\", \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10): \" \"warning: OpenSSL", "integer types with different sign\", \"category\": \"-Wpointer-sign\", \"project\": \"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\", \"hint\": None, }, {", "Rerun with option '--update'.\", \"category\": \"-Wother\", \"project\": None, \"hint\": None, }, { \"context\":", "[ { \"from\": \"Makefile.config\", \"info\": \"No sys/sdt.h found, no SDT events are defined,", "unsigned int *\", }, { \"context\": \"\" \"In file included from ../../src/include/postgres.h:47,\\n\" \"", "type \\u2018long unsigned int *\\u2019 [-Wformat=]\", ' 215 | nfields = sscanf (line,", "\"context\": \"\", \"file\": \"clang-cl\", \"severity\": \"warning\", \"info\": \"/: 'linker' input unused\", \"category\": \"-Wunused-command-line-argument\",", "matches = list( match.groupdict() for match in re.finditer(Regex.get(compiler), \"\\n\".join(output)) ) assert matches ==", "\" \"types [-Wpedantic]\", \" 772 | #define PG_INT128_TYPE __int128\", \" | ^~~~~~~~\", \"configure:", "\" from ../source_subfolder/atk/atk.h:25,\", \" from ../source_subfolder/atk/atktext.c:22:\", \"../source_subfolder/atk/atktext.c: In function \\u2018atk_text_range_get_type_once\\u2019:\", \"../source_subfolder/atk/atktext.c:1640:52: warning: ISO", "Could not determine size of size_t.\", \"project\": None, \"hint\": None, }, ], id=\"gnu\",", "%9s %ld %s\",', \" | ~~^\", \" | |\", \" | long int", "(line, \"%lx-%lx %9s %lx %9s %ld %s\",', \" | ~~^\", \" | |\",", "~~^\", \" | |\", \" | long int *\", \" | %ld\", \"", "\"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\", \"info\": \"ISO C does not support", "\"info\": \"index 'blockSize100k' range checked by comparison on this line\", \"hint\": None, },", "online help for details.\", \"project\": None, \"hint\": ' strcat(mode2,\"b\"); /* binary mode */\\n", "None, \"hint\": \"\" \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\\n\" \" | ^~~~~~~~~~~~~~~~~~~\",", "[-Wformat=]\", ' 215 | nfields = sscanf (line, \"%lx-%lx %9s %lx %9s %ld", "\"\" \"In file included from ../../src/include/postgres.h:47,\\n\" \" from rmtree.c:15:\\n\" \"rmtree.c: In function ‘rmtree’:\\n\"", "| ~~~~~~\\n\" \" | |\\n\" \" | long unsigned int *\", }, {", "function \" \"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\", \"src/main/src/Em_FilteringQmFu.c:266:5: warning: implicit declaration of function \" \"\\u2018memset\\u2019 [-Wimplicit-function-declaration]\", \"", "%9s %lx %9s %ld %s\",', \" | ~~^\", \" | |\", \" |", "\"info\": \"\" \"improperly calling multi-line macro `SETUP_STACK_POINTER' with 0 parameters\", \"category\": \"-w+macro-params-legacy\", \"project\":", "\"src/main/src/Em_FilteringQmFu.c: In function \" \"\\u2018Em_FilteringQmFu_processSensorSignals\\u2019:\", \"src/main/src/Em_FilteringQmFu.c:266:5: warning: implicit declaration of function \" \"\\u2018memset\\u2019", "| void*\", \"ninja/1.9.0 (test package): WARN: This conanfile has no build step\", \"src/port/pg_crc32c_sse42_choose.c(41,10):", "ERROR: Problem encountered: \" \"Could not determine size of size_t.\", \"\", ] dataset", "= sscanf (line, \"%lx-%lx %9s %lx %9s %ld %s\",', \" | ~~^\", \"", "from /package/include/glib-2.0/gobject/gobject.h:24,\\n\" \" from /package/include/glib-2.0/gobject/gbinding.h:29,\\n\" \" from /package/include/glib-2.0/glib-object.h:22,\\n\" \" from ../source_subfolder/atk/atkobject.h:27,\\n\" \" from", "declared \" \"with attribute warn_unused_result [-Wunused-result]\", \" 1073 | (void) fchown ( fd,", "/package/include/glib-2.0/gobject/gbinding.h:29,\", \" from /package/include/glib-2.0/glib-object.h:22,\", \" from ../source_subfolder/atk/atkobject.h:27,\", \" from ../source_subfolder/atk/atk.h:25,\", \" from ../source_subfolder/atk/atktext.c:22:\",", "change any of the parser definition files. You can obtain Bison from\" \"\\n***", "\"hint\": None, }, { \"context\": \"\", \"file\": \"C:\\\\src\\\\bzlib.c\", \"line\": \"161\", \"column\": None, \"severity\":", "| %ld\\n\" \" 216 | &start, &end, perm, &offset, dev, &inode, file);\\n\" \"", "\"\\n*** change any of the parser definition files. You can obtain Bison from\"", "for details.\", ' strcat(mode2,\"b\"); /* binary mode */', \" ^\", \"Makefile.config:565: No sys/sdt.h", "{ \"context\": \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\\n\" \"In file included from include\\\\crypto/evp.h:11:\\n\" \"In", "\"hint\": \"\" ' 409 | printf(\"] 0x%p\\\\n\", this);\\n' \" | ~^\\n\" \" |", "crypto\\\\asn1\\\\a_sign.c:22:\\n\" \"In file included from include\\\\crypto/evp.h:11:\\n\" \"In file included from include\\\\internal/refcount.h:21:\\n\" \"In file", "with attribute warn_unused_result\", \"category\": \"-Wunused-result\", \"project\": None, \"hint\": \"\" \" 1073 | (void)", "| \", \"WARNING: this is important\", \"warning: Boost.Build engine (b2) is 4.8.0\", \"./src/graph.cc:", "defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"line\": \"565\", \"severity\": None, }, {", "\" ^~~~~~\", }, { \"context\": \"\", \"file\": \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\", \"line\": \"92\", \"column\": None, \"severity\":", "‘%name-prefix \"constexpYY\"’, use ‘%define ' \"api.prefix {constexpYY}’\", \"category\": \"-Wdeprecated\", \"project\": None, \"hint\": \"\"", "\"POCO_INTERNAL_OPENSSL_BUILD)\\n\" \" ^\", }, { \"context\": \"\", \"file\": \"source_subfolder/meson.build\", \"line\": \"1559\", \"column\": \"2\",", "\"/source_subfolder/src/constexp.y:35.1-25: warning: deprecated directive: ‘%name-prefix \" '\"constexpYY\"’, use ‘%define api.prefix {constexpYY}’ [-Wdeprecated]', '", "\"version\": \"8.0.25\", \"user\": None, \"channel\": None, \"severity_l\": \"WARN\", \"severity\": None, \"info\": \"requirement openssl/1.1.1m", "size of size_t.\", \"\", ] dataset = [ pytest.param( [ { \"context\": \"src/main/src/Em_FilteringQmFu.c:", "or systemtap-sdt-dev\", \"line\": \"565\", \"severity\": None, }, { \"from\": \"configure\", \"line\": None, \"severity\":", "#pragma message (OPENSSL_VERSION_TEXT POCO_INTERNAL_OPENSSL_BUILD)\", \" ^\", \"source_subfolder/meson.build:1559:2: ERROR: Problem encountered: \" \"Could not", "'\"constexpYY\"’, use ‘%define api.prefix {constexpYY}’ [-Wdeprecated]', ' 35 | %name-prefix \"constexpYY\"', \" |", "the Bison\" \"\\n*** output is pre-generated.)\", }, ], id=\"autotools\", ), pytest.param( [ {", "\"context\": \"\", \"file\": \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\", \"line\": \"35\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"OpenSSL 1.1.1l", "None, \"hint\": None, }, { \"context\": \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\\n\" \"In file", "}, { \"file\": \"C:\\\\source_subfolder\\\\bzlib.c\", \"line\": \"1418\", \"column\": \"10\", \"category\": \"C4996\", \"severity\": \"warning\", \"info\":", "\"\\n*** Without Bison you will not be able to build PostgreSQL from Git", "encountered: Could not determine size of size_t.\", \"project\": None, \"hint\": None, }, ],", "‘%define api.prefix {constexpYY}’ [-Wdeprecated]', ' 35 | %name-prefix \"constexpYY\"', \" | ^~~~~~~~~~~~~~~~~~~~~~~~~\" \"", "Skipping the LDAP client authentication plugin\", \"\", \"\", \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\",", "this);\\n' \" | ~^\\n\" \" | |\\n\" \" | void*\", }, { \"context\":", "the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\" \" CMAKE_INSTALL_BINDIR\\n\" \" CMAKE_INSTALL_DATAROOTDIR\\n\" \" CMAKE_INSTALL_INCLUDEDIR\\n\" \" CMAKE_INSTALL_LIBDIR\\n\"", "variables were not used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \" CMAKE_INSTALL_BINDIR\", \"", "/* binary mode */\\n ^', }, { \"file\": \"NMAKE\", \"line\": None, \"column\": None,", "unused [-Wunused-command-line-argument]\", \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\", \"In file included from include\\\\crypto/evp.h:11:\", \"In", "\"line\": \"565\", \"severity\": None, }, { \"from\": \"configure\", \"line\": None, \"severity\": \"WARNING\", \"info\":", "../../src/include/postgres_fe.h:25,\\n\" \" from archive.c:19:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\", \"info\":", "../../src/include/c.h:54,\", \" from ../../src/include/postgres_fe.h:25,\", \" from archive.c:19:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not", "../../src/include/postgres.h:46,\", \" from stringinfo.c:20:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not support \\u2018__int128\\u2019 \"", "(x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h(15,2): \" \"error: <stdatomic.h> is not yet supported when compiling as", "\"line\": \"161\", \"column\": None, \"severity\": \"note\", \"category\": None, \"project\": None, \"info\": \"index 'blockSize100k'", "\"column\": \"10\", \"category\": \"C4996\", \"severity\": \"warning\", \"info\": \"'strcat': This function or variable may", "\"U1077\", \"info\": \"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : return \" \"code '0x1'\", \"project\": None, \"hint\": None, },", "\"context\": \"./src/graph.cc: In member function \" \"\\u2018void Edge::Dump(const char*) const\\u2019:\\n\", \"file\": \"./src/graph.cc\", \"line\":", "\"column\": \"11\", \"severity\": \"warning\", \"info\": \"\" \"ignoring return value of ‘fchown’, declared with", "In function \\u2018rmtree\\u2019:\", \"In file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres.h:46,\", \" from", "| printf(\"] 0x%p\\\\n\", this);\\n' \" | ~^\\n\" \" | |\\n\" \" | void*\",", "type\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range,", "\" \"union type [-Wpedantic]\", \" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\", \" |", "from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres_fe.h:25,\\n\" \" from archive.c:19:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\":", "\"\" \"ignoring return value of ‘fchown’, declared with attribute warn_unused_result\", \"category\": \"-Wunused-result\", \"project\":", "[-Wpedantic]\", \" 772 | #define PG_INT128_TYPE __int128\", \" | ^~~~~~~~\", \"configure: WARNING:\", \"***", "\"\", \"file\": \"ebcdic.c\", \"line\": \"284\", \"column\": None, \"severity\": \"warning\", \"info\": \"ISO C forbids", "\" '\"constexpYY\"’, use ‘%define api.prefix {constexpYY}’ [-Wdeprecated]', ' 35 | %name-prefix \"constexpYY\"', \"", "\" | ~^\", \" | |\", \" | void*\", \"ninja/1.9.0 (test package): WARN:", "../source_subfolder/atk/atk.h:25,\", \" from ../source_subfolder/atk/atktext.c:22:\", \"../source_subfolder/atk/atktext.c: In function \\u2018atk_text_range_get_type_once\\u2019:\", \"../source_subfolder/atk/atktext.c:1640:52: warning: ISO C prohibits", "\\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \"C:\\\\src\\\\bzlib.c(161) : note: index 'blockSize100k' range checked by comparison", "[-W#pragma-messages]\", \" #pragma message (OPENSSL_VERSION_TEXT POCO_INTERNAL_OPENSSL_BUILD)\", \" ^\", \"source_subfolder/meson.build:1559:2: ERROR: Problem encountered: \"", "\"category\": \"-Wunused-result\", \"project\": None, \"hint\": \"\" \" 1073 | (void) fchown ( fd,", "C\", \" ^\", \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10): \" \"warning: OpenSSL 1.1.1l 24 Aug 2021 [-W#pragma-messages]\", \"", "not used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"\", \"\", \"libjpeg/1.2.3: WARN: package", "support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \" 772 | #define PG_INT128_TYPE __int128\", \" |", "argument 8 has type \\u2018long unsigned int *\\u2019 [-Wformat=]\", ' 215 | nfields", "has type \\u2018long unsigned int *\\u2019 [-Wformat=]\", ' 215 | nfields = sscanf", "a GNU mirror site. (If you are using the official distribution of\" \"\\n***", "\"hint\": \"\" \" 772 | #define PG_INT128_TYPE __int128\\n\" \" | ^~~~~~~~\", }, {", "the Bison\", \"*** output is pre-generated.)\", \"end\", \"CMake Warning at cmake/ldap.cmake:158 (MESSAGE):\", \"", "\"hint\": None, }, { \"context\": \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\", \"file\": \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\", \"line\":", "\"C4312\", \"project\": None, \"hint\": None, }, { \"file\": \"C:\\\\source_subfolder\\\\bzlib.c\", \"line\": \"1418\", \"column\": \"10\",", "^\", \"Makefile.config:565: No sys/sdt.h found, no SDT events are defined, please install \"", "215 | nfields = sscanf (line, \"%lx-%lx %9s %lx %9s %ld %s\",\\n' \"", "conanfile has no build step\", \"severity\": \"WARN\", }, ], id=\"conan\", ), pytest.param( [", "build step\", \"severity\": \"WARN\", }, ], id=\"conan\", ), pytest.param( [ { \"severity\": \"warning\",", "\"/build/source_subfolder/bzip2.c\", \"line\": \"1073\", \"column\": \"11\", \"severity\": \"warning\", \"info\": \"\" \"ignoring return value of", "size\", \"category\": \"C4312\", \"project\": None, \"hint\": None, }, { \"file\": \"C:\\\\source_subfolder\\\\bzlib.c\", \"line\": \"1418\",", "included from /package/include/glib-2.0/gobject/gobject.h:24,\", \" from /package/include/glib-2.0/gobject/gbinding.h:29,\", \" from /package/include/glib-2.0/glib-object.h:22,\", \" from ../source_subfolder/atk/atkobject.h:27,\", \"", "Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h\", \"line\": \"15\", \"column\": \"2\", \"severity\": \"error\", \"category\": None, \"info\":", "Bison from\" \"\\n*** a GNU mirror site. (If you are using the official", "None, \"hint\": None, }, ], id=\"msvc\", ), pytest.param( [ { \"context\": None, \"severity\":", "\"C:\\\\source_subfolder\\\\bzlib.c\", \"line\": \"1418\", \"column\": \"10\", \"category\": \"C4996\", \"severity\": \"warning\", \"info\": \"'strcat': This function", "are defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"CMake Warning:\", \" Manually-specified variables", "from ../../src/include/postgres.h:46,\", \" from stringinfo.c:20:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not support \\u2018__int128\\u2019", "\"16\", \"severity\": \"warning\", \"info\": \"\" \"format ‘%p’ expects argument of type ‘void*’, \"", "not yet supported when compiling as C\\n\" \" ^\", \"project\": None, }, {", "\" 284 | #endif\", \" | \", \"WARNING: this is important\", \"warning: Boost.Build", "| ^~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"source_subfolder/src/tramp.c\", \"line\": \"215\", \"column\": \"52\", \"severity\":", "C forbids an empty translation unit\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \" 284", "CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\\n\" \" CMakeLists.txt:7 (include)\", }, { \"file\": \"libmysql/authentication_ldap/CMakeLists.txt\", \"line\": \"30\", \"severity\": \"Warning\",", "}, { \"context\": \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\", \"file\": \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\", \"line\": \"146\", \"column\":", "&offset, dev, &inode, file);\", \" | ~~~~~~\", \" | |\", \" | long", "| #define PG_INT128_TYPE __int128\", \" | ^~~~~~~~\", \"configure: WARNING:\", \"*** Without Bison you", "= list( match.groupdict() for match in re.finditer(Regex.get(compiler), \"\\n\".join(output)) ) assert matches == expected", "\"ref\": None, \"severity\": None, \"severity_l\": \"WARNING\", \"user\": None, \"version\": None, }, { \"severity_l\":", "dataset = [ pytest.param( [ { \"context\": \"src/main/src/Em_FilteringQmFu.c: In function \" \"‘Em_FilteringQmFu_processSensorSignals’:\\n\", \"file\":", "\"line\": \"1073\", \"column\": \"11\", \"severity\": \"warning\", \"info\": \"\" \"ignoring return value of ‘fchown’,", "\"has type ‘long unsigned int *’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" '", "directive: ‘%name-prefix \"constexpYY\"’, use ‘%define ' \"api.prefix {constexpYY}’\", \"category\": \"-Wdeprecated\", \"project\": None, \"hint\":", "rmtree.c:15:\", \"rmtree.c: In function \\u2018rmtree\\u2019:\", \"In file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres.h:46,\",", "to worry about this, because the Bison\" \"\\n*** output is pre-generated.)\", }, ],", "from ../source_subfolder/atk/atkobject.h:27,\", \" from ../source_subfolder/atk/atk.h:25,\", \" from ../source_subfolder/atk/atktext.c:22:\", \"../source_subfolder/atk/atktext.c: In function \\u2018atk_text_range_get_type_once\\u2019:\", \"../source_subfolder/atk/atktext.c:1640:52:", "included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres_fe.h:25,\", \" from archive.c:19:\", \"../../src/include/pg_config.h:772:24: warning: ISO C", "\"src/main/src/Em_FilteringQmFu.c:266:5: warning: implicit declaration of function \" \"\\u2018memset\\u2019 [-Wimplicit-function-declaration]\", \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\",", "note: index 'blockSize100k' range checked by comparison on this line\", \"ebcdic.c:284: warning: ISO", "\" Could not find LDAP\", \"context\": \"\" \"Call Stack (most recent call first):\\n\"", "WARNING:\", \"*** Without Bison you will not be able to build PostgreSQL from", "perm, &offset, dev, &inode, file);\", \" | ~~~~~~\", \" | |\", \" |", "None, \"column\": None, \"severity\": \"fatal error\", \"category\": \"U1077\", \"info\": \"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : return \"", "C4312: 'reinterpret_cast': conversion \" \"from 'int' to 'HANDLE' of greater size\", \"C:\\\\source_subfolder\\\\bzlib.c(1418,10): warning", "size of size_t.\", \"project\": None, \"hint\": None, }, ], id=\"gnu\", ), pytest.param( [", "\"\", \"CMake Warning at libmysql/authentication_ldap/CMakeLists.txt:30 (MESSAGE):\", \" Skipping the LDAP client authentication plugin\",", "file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres_fe.h:25,\", \" from archive.c:19:\", \"../../src/include/pg_config.h:772:24: warning: ISO", "function ‘memset’\", \"category\": \"-Wimplicit-function-declaration\", \"project\": None, \"hint\": \"\" \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\\n\" \"", "\"In file included from crypto\\\\asn1\\\\a_sign.c:22:\", \"In file included from include\\\\crypto/evp.h:11:\", \"In file included", "warning : passing 'unsigned int [4]' to \" \"parameter of type 'int *'", "(AtkTextRange, atk_text_range, atk_text_range_copy,\\n\" \" | ^~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"source_subfolder/src/tramp.c\", \"line\":", "\"column\": \"24\", \"severity\": \"warning\", \"info\": \"ISO C does not support ‘__int128’ types\", \"category\":", "deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\", \"project\": None, \"hint\": '", "be unsafe. Consider using strcat_s instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See", "is not yet supported when compiling as C\\n\" \" ^\", \"project\": None, },", "build PostgreSQL from Git nor\", \"*** change any of the parser definition files.", "the parser definition files. You can obtain Bison from\" \"\\n*** a GNU mirror", "], id=\"build\", ), ] @pytest.mark.parametrize(\"expected\", dataset) def test_warnings_regex(expected, request): compiler = request.node.callspec.id matches", "‘%p’ expects argument of type ‘void*’, \" \"but argument 2 has type ‘const", "\"project\": None, \"hint\": None, }, ], id=\"gnu\", ), pytest.param( [ { \"file\": \"/source_subfolder/common/socket_utils.cc\",", "\"note\", \"category\": None, \"project\": None, \"info\": \"index 'blockSize100k' range checked by comparison on", "\" from ../source_subfolder/atk/atktext.c:22:\\n\" \"../source_subfolder/atk/atktext.c: In function \" \"\\u2018atk_text_range_get_type_once\\u2019:\\n\", \"file\": \"../source_subfolder/atk/atktext.c\", \"line\": \"1640\", \"column\":", "\"clang-cl: warning: /: 'linker' input unused [-Wunused-command-line-argument]\", \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\", \"In", "you will not be able to build PostgreSQL from Git nor\", \"*** change", "In function \" \"‘applySavedFileAttrToOutputFile’:\\n\", \"file\": \"/build/source_subfolder/bzip2.c\", \"line\": \"1073\", \"column\": \"11\", \"severity\": \"warning\", \"info\":", "], id=\"conan\", ), pytest.param( [ { \"severity\": \"warning\", \"info\": \"Boost.Build engine (b2) is", "\"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 772 | #define PG_INT128_TYPE __int128\\n\" \"", "dataset) def test_warnings_regex(expected, request): compiler = request.node.callspec.id matches = list( match.groupdict() for match", "\"project\": None, \"hint\": ' strcat(mode2,\"b\"); /* binary mode */\\n ^', }, { \"file\":", "\"source_subfolder/src/tramp.c:215:52: warning: format \\u2018%ld\\u2019 expects argument of type \" \"\\u2018long int *\\u2019, but", "\" from stringinfo.c:20:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\": \"warning\", \"info\": \"ISO", "\" | ^~~~~~~~~~~~~~~~~~~~~~~~~\" \" | %define api.prefix {constexpYY}\", \"/source_subfolder/src/constexp.y: warning: fix-its can be", "included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\", \"file\": \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\", \"line\": \"146\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"extension", "\"line\": \"284\", \"column\": None, \"severity\": \"warning\", \"info\": \"ISO C forbids an empty translation", "}, { \"context\": \"\", \"file\": \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp\", \"line\": \"35\", \"column\": \"10\", \"severity\": \"warning\", \"info\":", "None, \"info\": \"Problem encountered: Could not determine size of size_t.\", \"project\": None, \"hint\":", "Manually-specified variables were not used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \" CMAKE_INSTALL_BINDIR\",", "warning: extension used \" \"[-Wlanguage-extension-token]\", \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\", \"", "\" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": \"35\", \"column\": \"1-25\",", "of ‘fchown’, declared with attribute warn_unused_result\", \"category\": \"-Wunused-result\", \"project\": None, \"hint\": \"\" \"", "\" CMAKE_INSTALL_DATAROOTDIR\", \" CMAKE_INSTALL_INCLUDEDIR\", \" CMAKE_INSTALL_LIBDIR\", \" CMAKE_INSTALL_LIBEXECDIR\", \" CMAKE_INSTALL_OLDINCLUDEDIR\", \" MAKE_INSTALL_SBINDIR\", \"\",", "}, { \"context\": \"\", \"file\": \"ebcdic.c\", \"line\": \"284\", \"column\": None, \"severity\": \"warning\", \"info\":", "\"systemtap-sdt-devel or systemtap-sdt-dev\", \"line\": \"565\", \"severity\": None, }, { \"from\": \"configure\", \"line\": None,", "| ^~~~~~~~\", \"configure: WARNING:\", \"*** Without Bison you will not be able to", "\" \"code '0x1'\", \"project\": None, \"hint\": None, }, ], id=\"msvc\", ), pytest.param( [", "| ^~~~~~~~~~~~~~~~~~~~~~~~~ | %define api.prefix \" \"{constexpYY}\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\",", "or variable may be unsafe. Consider using \" \"strcat_s instead. To disable deprecation,", "be unsafe. Consider using \" \"strcat_s instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS.", "id=\"gnu\", ), pytest.param( [ { \"file\": \"/source_subfolder/common/socket_utils.cc\", \"line\": \"43\", \"column\": None, \"severity\": \"warning\",", "\"43\", \"column\": None, \"severity\": \"warning\", \"info\": \"'reinterpret_cast': conversion from 'int' to 'HANDLE' of", "%name-prefix \"constexpYY\"\\n' \" | ^~~~~~~~~~~~~~~~~~~~~~~~~ | %define api.prefix \" \"{constexpYY}\", }, { \"context\":", "\"severity\": \"warning\", \"info\": \"fix-its can be applied. Rerun with option '--update'.\", \"category\": \"-Wother\",", "OF((gzFile, z_off64_t, int));\\n\" \" ^\", }, { \"context\": \"/build/source_subfolder/bzip2.c: In function \" \"‘applySavedFileAttrToOutputFile’:\\n\",", "file);\", \" | ~~~~~~\", \" | |\", \" | long unsigned int *\",", "included from crypto\\\\asn1\\\\a_sign.c:22:\", \"In file included from include\\\\crypto/evp.h:11:\", \"In file included from include\\\\internal/refcount.h:21:\",", "\"\", \"source_subfolder/src/tramp.c:215:52: warning: format \\u2018%ld\\u2019 expects argument of type \" \"\\u2018long int *\\u2019,", "argument 2 has type \\u2018const Edge*\\u2019 [-Wformat=]\", ' 409 | printf(\"] 0x%p\\\\n\", this);',", "‘const Edge*’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\": \"\" ' 409 | printf(\"] 0x%p\\\\n\",", "\"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\\n\" \" from /package/include/glib-2.0/gobject/gbinding.h:29,\\n\" \" from /package/include/glib-2.0/glib-object.h:22,\\n\" \" from", "\" | ~~^\\n\" \" | |\\n\" \" | long int *\\n\" \" |", "\"10\", \"severity\": \"warning\", \"info\": \"OpenSSL 1.1.1l 24 Aug 2021\", \"category\": \"-W#pragma-messages\", \"project\": None,", "None, }, { \"context\": \"\" \"In file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres_fe.h:25,\\n\"", "\" \"from 'int' to 'HANDLE' of greater size\", \"C:\\\\source_subfolder\\\\bzlib.c(1418,10): warning C4996: 'strcat': This", "PG_INT128_TYPE __int128\\n\" \" | ^~~~~~~~\", }, { \"context\": \"\" \"In file included from", "will not be able to build PostgreSQL from Git nor\", \"*** change any", "None, }, { \"ref\": \"libmysqlclient/8.0.25\", \"name\": \"libmysqlclient\", \"version\": \"8.0.25\", \"user\": None, \"channel\": None,", "| (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\\n\" \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", }, {", "rmtree.c:15:\\n\" \"rmtree.c: In function ‘rmtree’:\\n\" \"In file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres.h:46,\\n\"", "of function ‘memset’\", \"category\": \"-Wimplicit-function-declaration\", \"project\": None, \"hint\": \"\" \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\\n\"", "\"requirement openssl/1.1.1m overridden by poco/1.11.1 to openssl/1.1.1l\", }, { \"channel\": None, \"info\": \"this", "type \" \"\\u2018void*\\u2019, but argument 2 has type \\u2018const Edge*\\u2019 [-Wformat=]\", ' 409", "parameter of type 'int *' converts \" \"between pointers to integer types with", "{ \"context\": \"./src/graph.cc: In member function \" \"\\u2018void Edge::Dump(const char*) const\\u2019:\\n\", \"file\": \"./src/graph.cc\",", "\"multi-line macro `SETUP_STACK_POINTER' with 0 parameters [-w+macro-params-legacy]\", \"some text\", \"In file included from", ": note: index 'blockSize100k' range checked by comparison on this line\", \"ebcdic.c:284: warning:", "used \" \"[-Wlanguage-extension-token]\", \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\", \" ^\", \"/build/source_subfolder/bzip2.c:", "crypto\\\\asn1\\\\a_sign.c:22:\", \"In file included from include\\\\crypto/evp.h:11:\", \"In file included from include\\\\internal/refcount.h:21:\", \"In file", "\"line\": \"266\", \"column\": \"5\", \"severity\": \"warning\", \"info\": \"implicit declaration of function ‘memset’\", \"category\":", "None, \"severity\": \"fatal error\", \"category\": \"U1077\", \"info\": \"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : return \" \"code '0x1'\",", "\"file\": \"/source_subfolder/src/constexp.y\", \"line\": \"35\", \"column\": \"1-25\", \"severity\": \"warning\", \"info\": 'deprecated directive: ‘%name-prefix \"constexpYY\"’,", "file included from \" \"C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\\n\", \"file\": \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h\", \"line\": \"15\",", "\"Call Stack (most recent call first):\\n\" \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\\n\" \" CMakeLists.txt:7 (include)\", },", "\"severity\": \"warning\", \"info\": \"\" \"ignoring return value of ‘fchown’, declared with attribute warn_unused_result\",", "In function ‘rmtree’:\\n\" \"In file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres.h:46,\\n\" \" from", "\"ebcdic.c:284: warning: ISO C forbids an empty translation unit [-Wpedantic]\", \" 284 |", "\"8.0.25\", \"user\": None, \"channel\": None, \"severity_l\": \"WARN\", \"severity\": None, \"info\": \"requirement openssl/1.1.1m overridden", "\" \"\\u2018memset\\u2019 [-Wimplicit-function-declaration]\", \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\", \" ^~~~~~\", \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92: warning: improperly calling", "CMAKE_INSTALL_OLDINCLUDEDIR\", \" MAKE_INSTALL_SBINDIR\", \"\", \"\", \"source_subfolder/src/tramp.c:215:52: warning: format \\u2018%ld\\u2019 expects argument of type", "~^\", \" | |\", \" | void*\", \"ninja/1.9.0 (test package): WARN: This conanfile", "\" \"but argument 2 has type ‘const Edge*’\", \"category\": \"-Wformat=\", \"project\": None, \"hint\":", "\"project\": None, \"hint\": \"\" ' 35 | %name-prefix \"constexpYY\"\\n' \" | ^~~~~~~~~~~~~~~~~~~~~~~~~ |", "2 has type \\u2018const Edge*\\u2019 [-Wformat=]\", ' 409 | printf(\"] 0x%p\\\\n\", this);', \"", "unsigned int *\", \"In file included from ../../src/include/postgres.h:47,\", \" from rmtree.c:15:\", \"rmtree.c: In", "\"category\": \"-Wunused-command-line-argument\", \"line\": None, \"column\": None, \"project\": None, \"hint\": None, }, { \"context\":", "Bison\" \"\\n*** output is pre-generated.)\", }, ], id=\"autotools\", ), pytest.param( [ { \"ref\":", "printf(\"] 0x%p\\\\n\", this);\\n' \" | ~^\\n\" \" | |\\n\" \" | void*\", },", "project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \" CMAKE_INSTALL_BINDIR\", \" CMAKE_INSTALL_DATAROOTDIR\", \" CMAKE_INSTALL_INCLUDEDIR\", \" CMAKE_INSTALL_LIBDIR\", \"", "), pytest.param( [ { \"ref\": \"libjpeg/1.2.3\", \"name\": \"libjpeg\", \"version\": \"1.2.3\", \"user\": None, \"channel\":", "}, ], id=\"msvc\", ), pytest.param( [ { \"context\": None, \"severity\": \"Warning\", \"file\": None,", "\" from stringinfo.c:20:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not support \\u2018__int128\\u2019 \" \"types", "'blockSize100k' range checked by comparison on this line\", \"ebcdic.c:284: warning: ISO C forbids", "\" \"between pointers to integer types with different sign\", \"category\": \"-Wpointer-sign\", \"project\": \"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\",", "long unsigned int *\", }, { \"context\": \"\" \"In file included from ../../src/include/postgres.h:47,\\n\"", "\\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \" 772 | #define PG_INT128_TYPE __int128\", \" | ^~~~~~~~\",", "C\", \"hint\": \"#error <stdatomic.h> is not yet supported when compiling as C\\n\" \"", "format \\u2018%p\\u2019 expects argument of type \" \"\\u2018void*\\u2019, but argument 2 has type", "\"WARN\", }, ], id=\"conan\", ), pytest.param( [ { \"severity\": \"warning\", \"info\": \"Boost.Build engine", "\"severity\": \"warning\", \"info\": \"'strcat': This function or variable may be unsafe. Consider using", "atk_text_range, atk_text_range_copy,\", \" | ^~~~~~~~~~~~~~~~~~~\", \"CMake Warning:\", \" Manually-specified variables were not used", "In function \" \"‘Em_FilteringQmFu_processSensorSignals’:\\n\", \"file\": \"src/main/src/Em_FilteringQmFu.c\", \"line\": \"266\", \"column\": \"5\", \"severity\": \"warning\", \"info\":", "dev, &inode, file);\\n\" \" | ~~~~~~\\n\" \" | |\\n\" \" | long unsigned", "1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\", \" | ^~~~~~~~~~~~~~~~~~~\", \"CMake Warning:\", \" Manually-specified", "\"user\": None, \"channel\": None, \"severity_l\": \"WARN\", \"severity\": None, \"info\": \"requirement openssl/1.1.1m overridden by", "\"24\", \"severity\": \"warning\", \"info\": \"ISO C does not support ‘__int128’ types\", \"category\": \"-Wpedantic\",", "\"Warning\", \"file\": None, \"line\": None, \"function\": None, \"info\": \" Manually-specified variables were not", "../source_subfolder/atk/atkobject.h:27,\\n\" \" from ../source_subfolder/atk/atk.h:25,\\n\" \" from ../source_subfolder/atk/atktext.c:22:\\n\" \"../source_subfolder/atk/atktext.c: In function \" \"\\u2018atk_text_range_get_type_once\\u2019:\\n\", \"file\":", "of the parser definition files. You can obtain Bison from\", \"*** a GNU", "gzseek64 OF((gzFile, z_off64_t, int));\\n\" \" ^\", }, { \"context\": \"/build/source_subfolder/bzip2.c: In function \"", "deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\", ' strcat(mode2,\"b\"); /* binary", "using \" \"strcat_s instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help", "or systemtap-sdt-dev\", \"CMake Warning:\", \" Manually-specified variables were not used by the project:\",", "\"category\": \"-Wpedantic\", \"project\": None, \"hint\": \" 284 | #endif\\n | \", }, {", "\"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52): warning: extension used \" \"[-Wlanguage-extension-token]\", \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\",", "then you do not need to worry about this, because the Bison\" \"\\n***", "}, { \"context\": \"\", \"file\": \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\", \"line\": \"92\", \"column\": None, \"severity\": \"warning\", \"info\":", "\"some text\", \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\", \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52): warning: extension used \" \"[-Wlanguage-extension-token]\",", "CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\" \" CMAKE_INSTALL_BINDIR\\n\" \" CMAKE_INSTALL_DATAROOTDIR\\n\" \" CMAKE_INSTALL_INCLUDEDIR\\n\" \" CMAKE_INSTALL_LIBDIR\\n\" \" CMAKE_INSTALL_LIBEXECDIR\\n\" \" CMAKE_INSTALL_OLDINCLUDEDIR\\n\"", "None, \"column\": None, \"project\": None, \"hint\": None, }, { \"context\": \"In file included", "' \"api.prefix {constexpYY}’\", \"category\": \"-Wdeprecated\", \"project\": None, \"hint\": \"\" ' 35 | %name-prefix", "\"info\": \"format ‘%ld’ expects argument of type ‘long int *’, but argument 8", "warning: /: 'linker' input unused [-Wunused-command-line-argument]\", \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\", \"In file", "\"context\": \"\" \"In file included from ../../src/include/postgres.h:47,\\n\" \" from rmtree.c:15:\\n\" \"rmtree.c: In function", "\"WARNING\", \"info\": \"\" \"\\n*** Without Bison you will not be able to build", "long unsigned int *\", \"In file included from ../../src/include/postgres.h:47,\", \" from rmtree.c:15:\", \"rmtree.c:", "None, \"hint\": None, }, { \"context\": \"\" \"In file included from ../../src/include/c.h:54,\\n\" \"", "\"category\": \"-Wpointer-sign\", \"project\": \"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\", \"hint\": None, }, { \"context\": \"\", \"file\": \"clang-cl\", \"severity\":", "[ { \"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\": None, \"info\":", "sizeof(reicevedSignals));\", \" ^~~~~~\", \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92: warning: improperly calling \" \"multi-line macro `SETUP_STACK_POINTER' with 0", "\"/: 'linker' input unused\", \"category\": \"-Wunused-command-line-argument\", \"line\": None, \"column\": None, \"project\": None, \"hint\":", "not support ‘__int128’ types\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": None, }, { \"context\":", "\" CMAKE_INSTALL_BINDIR\", \" CMAKE_INSTALL_DATAROOTDIR\", \" CMAKE_INSTALL_INCLUDEDIR\", \" CMAKE_INSTALL_LIBDIR\", \" CMAKE_INSTALL_LIBEXECDIR\", \" CMAKE_INSTALL_OLDINCLUDEDIR\", \"", "site. (If you are using the official distribution of\" \"\\n*** PostgreSQL then you", "C forbids an empty translation unit [-Wpedantic]\", \" 284 | #endif\", \" |", "\"\" \"\\n*** Without Bison you will not be able to build PostgreSQL from", "\"src/main/src/Em_FilteringQmFu.c: In function \" \"‘Em_FilteringQmFu_processSensorSignals’:\\n\", \"file\": \"src/main/src/Em_FilteringQmFu.c\", \"line\": \"266\", \"column\": \"5\", \"severity\": \"warning\",", "\"context\": \"\", \"file\": \"source_subfolder/meson.build\", \"line\": \"1559\", \"column\": \"2\", \"severity\": \"ERROR\", \"category\": None, \"info\":", "409 | printf(\"] 0x%p\\\\n\", this);', \" | ~^\", \" | |\", \" |", "pytest.param( [ { \"file\": \"/source_subfolder/common/socket_utils.cc\", \"line\": \"43\", \"column\": None, \"severity\": \"warning\", \"info\": \"'reinterpret_cast':", "216 | &start, &end, perm, &offset, dev, &inode, file);\\n\" \" | ~~~~~~\\n\" \"", "\"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\\n\" \" ^\", }, { \"context\": \"/build/source_subfolder/bzip2.c:", "None, \"info\": \"this is important\", \"name\": None, \"ref\": None, \"severity\": None, \"severity_l\": \"WARNING\",", "| ^~~~~~~~~~~~~~~~~~~\", \"CMake Warning:\", \" Manually-specified variables were not used by the project:\",", "4.8.0\", \"./src/graph.cc: In member function \\u2018void Edge::Dump(const char*) const\\u2019:\", \"./src/graph.cc:409:16: warning: format \\u2018%p\\u2019", "\" from ../source_subfolder/atk/atk.h:25,\\n\" \" from ../source_subfolder/atk/atktext.c:22:\\n\" \"../source_subfolder/atk/atktext.c: In function \" \"\\u2018atk_text_range_get_type_once\\u2019:\\n\", \"file\": \"../source_subfolder/atk/atktext.c\",", "\" ^\", }, { \"context\": \"\", \"file\": \"source_subfolder/meson.build\", \"line\": \"1559\", \"column\": \"2\", \"severity\":", "\"-Wunused-command-line-argument\", \"line\": None, \"column\": None, \"project\": None, \"hint\": None, }, { \"context\": \"In", "obtain Bison from\" \"\\n*** a GNU mirror site. (If you are using the", "error\", \"category\": \"U1077\", \"info\": \"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : return \" \"code '0x1'\", \"project\": None, \"hint\":", "{ \"context\": \"\", \"file\": \"ebcdic.c\", \"line\": \"284\", \"column\": None, \"severity\": \"warning\", \"info\": \"ISO", "Git nor\", \"*** change any of the parser definition files. You can obtain", "(test package): WARN: This conanfile has no build step\", \"src/port/pg_crc32c_sse42_choose.c(41,10): warning : passing", "included from include\\\\internal/refcount.h:21:\", \"In file included from C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\", \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h(15,2):", "In function ‘applySavedFileAttrToOutputFile’:\", \"/build/source_subfolder/bzip2.c:1073:11: warning: ignoring return value of ‘fchown’, declared \" \"with", "\"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\": None, \"info\": \"\" \" Manually-specified variables", "mode */\\n ^', }, { \"file\": \"NMAKE\", \"line\": None, \"column\": None, \"severity\": \"fatal", "\"warning: Boost.Build engine (b2) is 4.8.0\", \"./src/graph.cc: In member function \\u2018void Edge::Dump(const char*)", "member function \" \"\\u2018void Edge::Dump(const char*) const\\u2019:\\n\", \"file\": \"./src/graph.cc\", \"line\": \"409\", \"column\": \"16\",", "of ‘fchown’, declared \" \"with attribute warn_unused_result [-Wunused-result]\", \" 1073 | (void) fchown", "atk_text_range, atk_text_range_copy,\\n\" \" | ^~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"source_subfolder/src/tramp.c\", \"line\": \"215\",", "\"severity\": \"fatal error\", \"category\": \"U1077\", \"info\": \"'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : return \" \"code '0x1'\", \"project\":", "(MYSQL_CHECK_LDAP)\\n\" \" CMakeLists.txt:7 (include)\", }, { \"file\": \"libmysql/authentication_ldap/CMakeLists.txt\", \"line\": \"30\", \"severity\": \"Warning\", \"function\":", ": passing 'unsigned int [4]' to \" \"parameter of type 'int *' converts", "openssl/1.1.1m \" \"overridden by poco/1.11.1 to openssl/1.1.1l\", \"In file included from ../../src/include/c.h:54,\", \"", "\\u2018rmtree\\u2019:\", \"In file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres.h:46,\", \" from stringinfo.c:20:\", \"../../src/include/pg_config.h:772:24:", "}, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": \"35\", \"column\": \"1-25\", \"severity\": \"warning\", \"info\":", "files. You can obtain Bison from\" \"\\n*** a GNU mirror site. (If you", "1073 | (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\\n\" \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", },", "\"version\": None, }, { \"severity_l\": None, \"ref\": \"ninja/1.9.0\", \"name\": \"ninja\", \"version\": \"1.9.0\", \"channel\":", "\"../source_subfolder/atk/atktext.c\", \"line\": \"1640\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"ISO C prohibits argument conversion", "argument conversion to union type\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"\" \" 1640", "\" \"parameter of type 'int *' converts between pointers to integer types with", "\"1.9.0\", \"channel\": None, \"user\": None, \"info\": \"This conanfile has no build step\", \"severity\":", "fix-its can be applied. Rerun with option \" \"'--update'. [-Wother]\", \"/source_subfolder/common/socket_utils.cc(43): warning C4312:", "\"channel\": None, \"info\": \"this is important\", \"name\": None, \"ref\": None, \"severity\": None, \"severity_l\":", "\"file\": \"clang-cl\", \"severity\": \"warning\", \"info\": \"/: 'linker' input unused\", \"category\": \"-Wunused-command-line-argument\", \"line\": None,", "first):\", \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\", \" CMakeLists.txt:7 (include)\", \"\", \"\", \"CMake Warning at libmysql/authentication_ldap/CMakeLists.txt:30", "\"end\", \"CMake Warning at cmake/ldap.cmake:158 (MESSAGE):\", \" Could not find LDAP\", \"Call Stack", "\"158\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"info\": \" Could not find LDAP\", \"context\": \"\"", "\"ISO C forbids an empty translation unit\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\": \"", "warn_unused_result\", \"category\": \"-Wunused-result\", \"project\": None, \"hint\": \"\" \" 1073 | (void) fchown (", "Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h(15,2): \" \"error: <stdatomic.h> is not yet supported when compiling", "\"In file included from ../../src/include/postgres.h:47,\\n\" \" from rmtree.c:15:\\n\" \"rmtree.c: In function ‘rmtree’:\\n\" \"In", "use \" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\", \"project\": None, \"hint\": ' strcat(mode2,\"b\");", "\" \"\\u2018atk_text_range_get_type_once\\u2019:\\n\", \"file\": \"../source_subfolder/atk/atktext.c\", \"line\": \"1640\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"ISO C", "\"\" \"Call Stack (most recent call first):\\n\" \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\\n\" \" CMakeLists.txt:7 (include)\",", "\"severity\": \"warning\", \"info\": 'deprecated directive: ‘%name-prefix \"constexpYY\"’, use ‘%define ' \"api.prefix {constexpYY}’\", \"category\":", "warning: ISO C prohibits argument conversion to \" \"union type [-Wpedantic]\", \" 1640", "'HANDLE' of greater size\", \"category\": \"C4312\", \"project\": None, \"hint\": None, }, { \"file\":", "function \\u2018atk_text_range_get_type_once\\u2019:\", \"../source_subfolder/atk/atktext.c:1640:52: warning: ISO C prohibits argument conversion to \" \"union type", "Without Bison you will not be able to build PostgreSQL from Git nor\"", "\"user\": None, \"version\": None, }, { \"severity_l\": None, \"ref\": \"ninja/1.9.0\", \"name\": \"ninja\", \"version\":", "{ \"context\": \"\" \"In file included from ../../src/include/postgres.h:47,\\n\" \" from rmtree.c:15:\\n\" \"rmtree.c: In", "\"[-Wpointer-sign] [C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\", \"NMAKE : fatal error U1077: 'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : \" \"return code '0x1'\",", "function or variable \" \"may be unsafe. Consider using strcat_s instead. To disable", "'linker' input unused\", \"category\": \"-Wunused-command-line-argument\", \"line\": None, \"column\": None, \"project\": None, \"hint\": None,", "client authentication plugin\", \"\", \"\", \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\", \" from /package/include/glib-2.0/gobject/gbinding.h:29,\",", "from\", \"*** a GNU mirror site. (If you are using the official distribution", "\"WARN\", \"severity\": None, \"info\": \"requirement openssl/1.1.1m overridden by poco/1.11.1 to openssl/1.1.1l\", }, {", "Manually-specified variables were not used by the project:\", \"\", \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"\", \"\",", "\" 1640 | G_DEFINE_BOXED_TYPE (AtkTextRange, atk_text_range, atk_text_range_copy,\", \" | ^~~~~~~~~~~~~~~~~~~\", \"CMake Warning:\", \"", "when compiling as C\", \"#error <stdatomic.h> is not yet supported when compiling as", "{ \"file\": \"NMAKE\", \"line\": None, \"column\": None, \"severity\": \"fatal error\", \"category\": \"U1077\", \"info\":", "support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \"C:\\\\src\\\\bzlib.c(161) : note: index 'blockSize100k' range checked by", "[C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\", \"NMAKE : fatal error U1077: 'C:\\\\Users\\\\marcel\\\\applications\\\\LLVM\\\\bin\\\\clang-cl.EXE' : \" \"return code '0x1'\", \"clang-cl:", "}, { \"context\": \"\", \"file\": \"source_subfolder/src/tramp.c\", \"line\": \"215\", \"column\": \"52\", \"severity\": \"warning\", \"info\":", "with different sign\", \"category\": \"-Wpointer-sign\", \"project\": \"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\", \"hint\": None, }, { \"context\": \"\",", "}, { \"severity_l\": None, \"ref\": \"ninja/1.9.0\", \"name\": \"ninja\", \"version\": \"1.9.0\", \"channel\": None, \"user\":", "compiling as C\", \" ^\", \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10): \" \"warning: OpenSSL 1.1.1l 24 Aug 2021", "are defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"line\": \"565\", \"severity\": None, },", "This conanfile has no build step\", \"src/port/pg_crc32c_sse42_choose.c(41,10): warning : passing 'unsigned int [4]'", "\"may be unsafe. Consider using strcat_s instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS.", "function \" \"\\u2018void Edge::Dump(const char*) const\\u2019:\\n\", \"file\": \"./src/graph.cc\", \"line\": \"409\", \"column\": \"16\", \"severity\":", "variable may be unsafe. Consider using \" \"strcat_s instead. To disable deprecation, use", "python # -*- coding: UTF-8 -*- import re import pytest from conmon.warnings import", "\"[-Wlanguage-extension-token]\", \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\", \" ^\", \"/build/source_subfolder/bzip2.c: In function", "\\u2018%ld\\u2019 expects argument of type \" \"\\u2018long int *\\u2019, but argument 8 has", "z_off64_t, int));\\n\" \" ^\", }, { \"context\": \"/build/source_subfolder/bzip2.c: In function \" \"‘applySavedFileAttrToOutputFile’:\\n\", \"file\":", "\"severity\": \"warning\", \"info\": \"\" \"improperly calling multi-line macro `SETUP_STACK_POINTER' with 0 parameters\", \"category\":", "\"\" \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\\n\" \" ^\", }, { \"context\":", "not need to worry about this, because the Bison\" \"\\n*** output is pre-generated.)\",", "conanfile has no build step\", \"src/port/pg_crc32c_sse42_choose.c(41,10): warning : passing 'unsigned int [4]' to", "from Git nor\", \"*** change any of the parser definition files. You can", "\"extension used\", \"category\": \"-Wlanguage-extension-token\", \"project\": None, \"hint\": \"\" \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile,", "^\", }, { \"context\": \"/build/source_subfolder/bzip2.c: In function \" \"‘applySavedFileAttrToOutputFile’:\\n\", \"file\": \"/build/source_subfolder/bzip2.c\", \"line\": \"1073\",", "type ‘void*’, \" \"but argument 2 has type ‘const Edge*’\", \"category\": \"-Wformat=\", \"project\":", "able to build PostgreSQL from Git nor\" \"\\n*** change any of the parser", "‘%ld’ expects argument of type ‘long int *’, but argument 8 \" \"has", "expects argument of type ‘long int *’, but argument 8 \" \"has type", "/: 'linker' input unused [-Wunused-command-line-argument]\", \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\", \"In file included", "\"\\u2018long int *\\u2019, but argument 8 has type \\u2018long unsigned int *\\u2019 [-Wformat=]\",", "\"between pointers to integer types with different sign\", \"category\": \"-Wpointer-sign\", \"project\": \"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\", \"hint\":", "\"cmake/ldap.cmake\", \"line\": \"158\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"info\": \" Could not find LDAP\",", "\"file\": \"/source_subfolder/common/socket_utils.cc\", \"line\": \"43\", \"column\": None, \"severity\": \"warning\", \"info\": \"'reinterpret_cast': conversion from 'int'", "(AtkTextRange, atk_text_range, atk_text_range_copy,\", \" | ^~~~~~~~~~~~~~~~~~~\", \"CMake Warning:\", \" Manually-specified variables were not", "' strcat(mode2,\"b\"); /* binary mode */', \" ^\", \"Makefile.config:565: No sys/sdt.h found, no", "WARN: package is corrupted\", \"WARN: libmysqlclient/8.0.25: requirement openssl/1.1.1m \" \"overridden by poco/1.11.1 to", "between pointers to integer types with different sign \" \"[-Wpointer-sign] [C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\", \"NMAKE :", "deprecated directive: ‘%name-prefix \" '\"constexpYY\"’, use ‘%define api.prefix {constexpYY}’ [-Wdeprecated]', ' 35 |", "None, \"version\": None, }, { \"severity_l\": None, \"ref\": \"ninja/1.9.0\", \"name\": \"ninja\", \"version\": \"1.9.0\",", "'blockSize100k' range checked by comparison on this line\", \"hint\": None, }, { \"context\":", "\"file\": \"/source_subfolder/src/constexp.y\", \"line\": None, \"column\": None, \"severity\": \"warning\", \"info\": \"fix-its can be applied.", "CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", \"\", \"\", \"libjpeg/1.2.3: WARN: package is corrupted\", \"WARN: libmysqlclient/8.0.25: requirement openssl/1.1.1m \"", "../../src/include/postgres_fe.h:25,\", \" from archive.c:19:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not support \\u2018__int128\\u2019 \"", "\" \"_CRT_SECURE_NO_WARNINGS. See online help for details.\", ' strcat(mode2,\"b\"); /* binary mode */',", "\"parameter of type 'int *' converts between pointers to integer types with different", "*\", \" | %ld\", \" 216 | &start, &end, perm, &offset, dev, &inode,", "memset(&reicevedSignals, 0, sizeof(reicevedSignals));\", \" ^~~~~~\", \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92: warning: improperly calling \" \"multi-line macro `SETUP_STACK_POINTER'", "function \" \"\\u2018atk_text_range_get_type_once\\u2019:\\n\", \"file\": \"../source_subfolder/atk/atktext.c\", \"line\": \"1640\", \"column\": \"52\", \"severity\": \"warning\", \"info\": \"ISO", "| long int *\\n\" \" | %ld\\n\" \" 216 | &start, &end, perm,", "#endif\\n | \", }, { \"context\": \"./src/graph.cc: In member function \" \"\\u2018void Edge::Dump(const", "details.\", \"project\": None, \"hint\": ' strcat(mode2,\"b\"); /* binary mode */\\n ^', }, {", "events are defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"CMake Warning:\", \" Manually-specified", "\" ^\", \"/build/source_subfolder/bzip2.c: In function ‘applySavedFileAttrToOutputFile’:\", \"/build/source_subfolder/bzip2.c:1073:11: warning: ignoring return value of ‘fchown’,", "\" 1073 | (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid );\\n\" \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\",", "included from include\\\\crypto/evp.h:11:\", \"In file included from include\\\\internal/refcount.h:21:\", \"In file included from C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\",", "from stringinfo.c:20:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\",", "of size_t.\", \"\", ] dataset = [ pytest.param( [ { \"context\": \"src/main/src/Em_FilteringQmFu.c: In", "\"1559\", \"column\": \"2\", \"severity\": \"ERROR\", \"category\": None, \"info\": \"Problem encountered: Could not determine", "), pytest.param( [ { \"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\":", "plugin\", }, { \"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\": None,", "\", }, { \"context\": \"./src/graph.cc: In member function \" \"\\u2018void Edge::Dump(const char*) const\\u2019:\\n\",", "function \\u2018rmtree\\u2019:\", \"In file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres.h:46,\", \" from stringinfo.c:20:\",", "\"file\": \"cmake/ldap.cmake\", \"line\": \"158\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"info\": \" Could not find", "This function or variable may be unsafe. Consider using \" \"strcat_s instead. To", "\"52\", \"severity\": \"warning\", \"info\": \"ISO C prohibits argument conversion to union type\", \"category\":", "CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", }, { \"file\": \"cmake/ldap.cmake\", \"line\": \"158\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"info\": \"", "archive.c:19:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not support \\u2018__int128\\u2019 \" \"types [-Wpedantic]\", \"", "\" ^~~~~~\", \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92: warning: improperly calling \" \"multi-line macro `SETUP_STACK_POINTER' with 0 parameters", "\"41\", \"column\": \"10\", \"severity\": \"warning\", \"info\": \"passing 'unsigned int [4]' to parameter of", "\"C:\\\\src\\\\bzlib.c\", \"line\": \"161\", \"column\": None, \"severity\": \"note\", \"category\": None, \"project\": None, \"info\": \"index", "\" | %ld\\n\" \" 216 | &start, &end, perm, &offset, dev, &inode, file);\\n\"", "from 'int' to 'HANDLE' of greater size\", \"category\": \"C4312\", \"project\": None, \"hint\": None,", "calling multi-line macro `SETUP_STACK_POINTER' with 0 parameters\", \"category\": \"-w+macro-params-legacy\", \"project\": None, \"hint\": None,", "\"11\", \"severity\": \"warning\", \"info\": \"\" \"ignoring return value of ‘fchown’, declared with attribute", "multi-line macro `SETUP_STACK_POINTER' with 0 parameters\", \"category\": \"-w+macro-params-legacy\", \"project\": None, \"hint\": None, },", "\"info\": \"ISO C forbids an empty translation unit\", \"category\": \"-Wpedantic\", \"project\": None, \"hint\":", "\"severity\": None, \"info\": \"requirement openssl/1.1.1m overridden by poco/1.11.1 to openssl/1.1.1l\", }, { \"channel\":", "\" from /package/include/glib-2.0/gobject/gbinding.h:29,\\n\" \" from /package/include/glib-2.0/glib-object.h:22,\\n\" \" from ../source_subfolder/atk/atkobject.h:27,\\n\" \" from ../source_subfolder/atk/atk.h:25,\\n\" \"", "../source_subfolder/atk/atktext.c:22:\", \"../source_subfolder/atk/atktext.c: In function \\u2018atk_text_range_get_type_once\\u2019:\", \"../source_subfolder/atk/atktext.c:1640:52: warning: ISO C prohibits argument conversion to", "not be able to build PostgreSQL from Git nor\", \"*** change any of", "\"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\\n\", \"file\": \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h\", \"line\": \"146\", \"column\": \"52\", \"severity\": \"warning\",", "\" Manually-specified variables were not used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\\n\" \"", "\"/source_subfolder/common/socket_utils.cc\", \"line\": \"43\", \"column\": None, \"severity\": \"warning\", \"info\": \"'reinterpret_cast': conversion from 'int' to", "compiling as C\", \"#error <stdatomic.h> is not yet supported when compiling as C\",", "^~~~~~~~~~~~~~~~~~~~~~~~~ | %define api.prefix \" \"{constexpYY}\", }, { \"context\": \"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\":", "SDT events are defined, please install \" \"systemtap-sdt-devel or systemtap-sdt-dev\", \"CMake Warning:\", \"", "\"line\": \"35\", \"column\": \"1-25\", \"severity\": \"warning\", \"info\": 'deprecated directive: ‘%name-prefix \"constexpYY\"’, use ‘%define", "'reinterpret_cast': conversion \" \"from 'int' to 'HANDLE' of greater size\", \"C:\\\\source_subfolder\\\\bzlib.c(1418,10): warning C4996:", "| %ld\", \" 216 | &start, &end, perm, &offset, dev, &inode, file);\", \"", "for details.\", \"project\": None, \"hint\": ' strcat(mode2,\"b\"); /* binary mode */\\n ^', },", "CMAKE_INSTALL_LIBEXECDIR\", \" CMAKE_INSTALL_OLDINCLUDEDIR\", \" MAKE_INSTALL_SBINDIR\", \"\", \"\", \"source_subfolder/src/tramp.c:215:52: warning: format \\u2018%ld\\u2019 expects argument", "None, \"project\": None, \"hint\": None, }, { \"context\": \"In file included from crypto\\\\asn1\\\\a_sign.c:22:\\n\"", "(If you are using the official distribution of\" \"\\n*** PostgreSQL then you do", "overridden by poco/1.11.1 to openssl/1.1.1l\", }, { \"channel\": None, \"info\": \"this is important\",", "\"\", \"\", \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\", \" from /package/include/glib-2.0/gobject/gbinding.h:29,\", \" from /package/include/glib-2.0/glib-object.h:22,\",", "\"severity_l\": \"WARN\", \"severity\": None, \"info\": \"requirement openssl/1.1.1m overridden by poco/1.11.1 to openssl/1.1.1l\", },", "-*- coding: UTF-8 -*- import re import pytest from conmon.warnings import Regex output", "re import pytest from conmon.warnings import Regex output = [ \"src/main/src/Em_FilteringQmFu.c: In function", "\"line\": \"92\", \"column\": None, \"severity\": \"warning\", \"info\": \"\" \"improperly calling multi-line macro `SETUP_STACK_POINTER'", "\"In file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres_fe.h:25,\\n\" \" from archive.c:19:\\n\", \"file\": \"../../src/include/pg_config.h\",", "file);\\n\" \" | ~~~~~~\\n\" \" | |\\n\" \" | long unsigned int *\",", "\"-Wdeprecated\", \"project\": None, \"hint\": \"\" ' 35 | %name-prefix \"constexpYY\"\\n' \" | ^~~~~~~~~~~~~~~~~~~~~~~~~", "\"565\", \"severity\": None, }, { \"from\": \"configure\", \"line\": None, \"severity\": \"WARNING\", \"info\": \"\"", "\" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\\n\" \" CMakeLists.txt:7 (include)\", }, { \"file\": \"libmysql/authentication_ldap/CMakeLists.txt\", \"line\": \"30\", \"severity\":", "file included from include\\\\internal/refcount.h:21:\", \"In file included from C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\", \"C:\\\\Program Files (x86)\\\\Microsoft Visual", "None, \"hint\": None, }, { \"file\": \"C:\\\\source_subfolder\\\\bzlib.c\", \"line\": \"1418\", \"column\": \"10\", \"category\": \"C4996\",", "\"\" \"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\\n\" \" from /package/include/glib-2.0/gobject/gbinding.h:29,\\n\" \" from /package/include/glib-2.0/glib-object.h:22,\\n\" \"", "\"from 'int' to 'HANDLE' of greater size\", \"C:\\\\source_subfolder\\\\bzlib.c(1418,10): warning C4996: 'strcat': This function", "CMAKE_INSTALL_DATAROOTDIR\", \" CMAKE_INSTALL_INCLUDEDIR\", \" CMAKE_INSTALL_LIBDIR\", \" CMAKE_INSTALL_LIBEXECDIR\", \" CMAKE_INSTALL_OLDINCLUDEDIR\", \" MAKE_INSTALL_SBINDIR\", \"\", \"\",", "\"severity\": \"WARNING\", \"info\": \"\" \"\\n*** Without Bison you will not be able to", "\"\" ' 409 | printf(\"] 0x%p\\\\n\", this);\\n' \" | ~^\\n\" \" | |\\n\"", "\"info\": \"This conanfile has no build step\", \"severity\": \"WARN\", }, ], id=\"conan\", ),", "\" from archive.c:19:\", \"../../src/include/pg_config.h:772:24: warning: ISO C does not support \\u2018__int128\\u2019 \" \"types", "pre-generated.)\", \"end\", \"CMake Warning at cmake/ldap.cmake:158 (MESSAGE):\", \" Could not find LDAP\", \"Call", "recent call first):\", \" CMakeListsOriginal.txt:1351 (MYSQL_CHECK_LDAP)\", \" CMakeLists.txt:7 (include)\", \"\", \"\", \"CMake Warning", "\"\\n*** a GNU mirror site. (If you are using the official distribution of\"", "to 'HANDLE' of greater size\", \"category\": \"C4312\", \"project\": None, \"hint\": None, }, {", "this is important\", \"warning: Boost.Build engine (b2) is 4.8.0\", \"./src/graph.cc: In member function", "\"\", \"file\": \"/source_subfolder/src/constexp.y\", \"line\": None, \"column\": None, \"severity\": \"warning\", \"info\": \"fix-its can be", "None, \"severity\": \"note\", \"category\": None, \"project\": None, \"info\": \"index 'blockSize100k' range checked by", "\"info\": \"Problem encountered: Could not determine size of size_t.\", \"project\": None, \"hint\": None,", "\"channel\": None, \"user\": None, \"info\": \"This conanfile has no build step\", \"severity\": \"WARN\",", "}, { \"context\": \"\" \"In file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres_fe.h:25,\\n\" \"", "\"info\": \"'reinterpret_cast': conversion from 'int' to 'HANDLE' of greater size\", \"category\": \"C4312\", \"project\":", "file included from C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\", \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h(15,2): \" \"error: <stdatomic.h> is", "[-w+macro-params-legacy]\", \"some text\", \"In file included from C:\\\\conan\\\\data\\\\source_subfolder\\\\zutil.c:10:\", \"C:\\\\conan\\\\data\\\\source_subfolder/gzguts.h(146,52): warning: extension used \"", "distribution of\", \"*** PostgreSQL then you do not need to worry about this,", "\" 772 | #define PG_INT128_TYPE __int128\", \" | ^~~~~~~~\", \"configure: WARNING:\", \"*** Without", "extension used \" \"[-Wlanguage-extension-token]\", \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\", \" ^\",", "\"category\": None, \"project\": None, \"info\": \"index 'blockSize100k' range checked by comparison on this", "warning: fix-its can be applied. Rerun with option \" \"'--update'. [-Wother]\", \"/source_subfolder/common/socket_utils.cc(43): warning", "to integer types with different sign \" \"[-Wpointer-sign] [C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj]\", \"NMAKE : fatal error", "\"In file included from /package/include/glib-2.0/gobject/gobject.h:24,\", \" from /package/include/glib-2.0/gobject/gbinding.h:29,\", \" from /package/include/glib-2.0/glib-object.h:22,\", \" from", "\"column\": \"1-25\", \"severity\": \"warning\", \"info\": 'deprecated directive: ‘%name-prefix \"constexpYY\"’, use ‘%define ' \"api.prefix", "\"column\": \"10\", \"severity\": \"warning\", \"info\": \"OpenSSL 1.1.1l 24 Aug 2021\", \"category\": \"-W#pragma-messages\", \"project\":", "\"/source_subfolder/src/constexp.y\", \"line\": None, \"column\": None, \"severity\": \"warning\", \"info\": \"fix-its can be applied. Rerun", "from include\\\\internal/refcount.h:21:\", \"In file included from C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\", \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h(15,2): \"", "file included from ../../src/include/postgres.h:47,\\n\" \" from rmtree.c:15:\\n\" \"rmtree.c: In function ‘rmtree’:\\n\" \"In file", "as C\", \" ^\", \"C:\\\\conan\\\\source_subfolder\\\\Crypto\\\\src\\\\OpenSSLInitializer.cpp(35,10): \" \"warning: OpenSSL 1.1.1l 24 Aug 2021 [-W#pragma-messages]\",", "\"\" ' 215 | nfields = sscanf (line, \"%lx-%lx %9s %lx %9s %ld", "\"implicit declaration of function ‘memset’\", \"category\": \"-Wimplicit-function-declaration\", \"project\": None, \"hint\": \"\" \" memset(&reicevedSignals,", "None, \"hint\": \"\" \"ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\\n\" \" ^\", },", "no build step\", \"src/port/pg_crc32c_sse42_choose.c(41,10): warning : passing 'unsigned int [4]' to \" \"parameter", "None, \"info\": \" Skipping the LDAP client authentication plugin\", }, { \"context\": None,", "atk_text_range_copy,\\n\" \" | ^~~~~~~~~~~~~~~~~~~\", }, { \"context\": \"\", \"file\": \"source_subfolder/src/tramp.c\", \"line\": \"215\", \"column\":", "were not used by the project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", }, { \"file\": \"cmake/ldap.cmake\",", "{ \"from\": \"configure\", \"line\": None, \"severity\": \"WARNING\", \"info\": \"\" \"\\n*** Without Bison you", "{ \"context\": \"\", \"file\": \"source_subfolder/meson.build\", \"line\": \"1559\", \"column\": \"2\", \"severity\": \"ERROR\", \"category\": None,", "None, \"channel\": None, \"info\": \"package is corrupted\", \"severity\": \"WARN\", \"severity_l\": None, }, {", "to openssl/1.1.1l\", }, { \"channel\": None, \"info\": \"this is important\", \"name\": None, \"ref\":", "Consider using strcat_s instead. To disable deprecation, use \" \"_CRT_SECURE_NO_WARNINGS. See online help", "\"\", \"\", \"libjpeg/1.2.3: WARN: package is corrupted\", \"WARN: libmysqlclient/8.0.25: requirement openssl/1.1.1m \" \"overridden", "'0x1'\", \"project\": None, \"hint\": None, }, ], id=\"msvc\", ), pytest.param( [ { \"context\":", "return value of ‘fchown’, declared with attribute warn_unused_result\", \"category\": \"-Wunused-result\", \"project\": None, \"hint\":", "different sign\", \"category\": \"-Wpointer-sign\", \"project\": \"C:\\\\conan\\\\source_subfolder\\\\libpgport.vcxproj\", \"hint\": None, }, { \"context\": \"\", \"file\":", "| ~~^\\n\" \" | |\\n\" \" | long int *\\n\" \" | %ld\\n\"", "None, \"project\": None, \"info\": \"index 'blockSize100k' range checked by comparison on this line\",", "project:\\n\" \"\\n\" \" CMAKE_EXPORT_NO_PACKAGE_REGISTRY\", }, { \"file\": \"cmake/ldap.cmake\", \"line\": \"158\", \"severity\": \"Warning\", \"function\":", "' 409 | printf(\"] 0x%p\\\\n\", this);', \" | ~^\", \" | |\", \"", "applied. Rerun with option '--update'.\", \"category\": \"-Wother\", \"project\": None, \"hint\": None, }, {", "| |\\n\" \" | void*\", }, { \"context\": \"\", \"file\": \"src/port/pg_crc32c_sse42_choose.c\", \"line\": \"41\",", "{ \"context\": None, \"severity\": \"Warning\", \"file\": None, \"line\": None, \"function\": None, \"info\": \"\"", "\" from ../../src/include/postgres.h:46,\\n\" \" from stringinfo.c:20:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\":", "GNU mirror site. (If you are using the official distribution of\", \"*** PostgreSQL", "{constexpYY}\", \"/source_subfolder/src/constexp.y: warning: fix-its can be applied. Rerun with option \" \"'--update'. [-Wother]\",", "\"info\": \"ISO C prohibits argument conversion to union type\", \"category\": \"-Wpedantic\", \"project\": None,", "\"context\": \"\", \"file\": \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm\", \"line\": \"92\", \"column\": None, \"severity\": \"warning\", \"info\": \"\" \"improperly", "\"name\": \"libmysqlclient\", \"version\": \"8.0.25\", \"user\": None, \"channel\": None, \"severity_l\": \"WARN\", \"severity\": None, \"info\":", "\"WARN: libmysqlclient/8.0.25: requirement openssl/1.1.1m \" \"overridden by poco/1.11.1 to openssl/1.1.1l\", \"In file included", "\"\\u2018void*\\u2019, but argument 2 has type \\u2018const Edge*\\u2019 [-Wformat=]\", ' 409 | printf(\"]", "‘%name-prefix \" '\"constexpYY\"’, use ‘%define api.prefix {constexpYY}’ [-Wdeprecated]', ' 35 | %name-prefix \"constexpYY\"',", "|\", \" | long unsigned int *\", \"In file included from ../../src/include/postgres.h:47,\", \"", "CMakeLists.txt:7 (include)\", \"\", \"\", \"CMake Warning at libmysql/authentication_ldap/CMakeLists.txt:30 (MESSAGE):\", \" Skipping the LDAP", "\" Skipping the LDAP client authentication plugin\", }, { \"context\": None, \"severity\": \"Warning\",", "\"_CRT_SECURE_NO_WARNINGS. See online help for details.\", ' strcat(mode2,\"b\"); /* binary mode */', \"", "from C:\\\\Users\\\\LLVM\\\\lib\\\\clang\\\\13.0.1\\\\include\\\\stdatomic.h:17:\", \"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h(15,2): \" \"error: <stdatomic.h> is not yet", "\"\\u2018memset\\u2019 [-Wimplicit-function-declaration]\", \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\", \" ^~~~~~\", \"C:\\\\source_subfolder\\\\source\\\\common\\\\x86\\\\seaintegral.asm:92: warning: improperly calling \"", "None, \"info\": \"\" \" Manually-specified variables were not used by the project:\\n\" \"\\n\"", "\"libjpeg/1.2.3\", \"name\": \"libjpeg\", \"version\": \"1.2.3\", \"user\": None, \"channel\": None, \"info\": \"package is corrupted\",", "use ‘%define ' \"api.prefix {constexpYY}’\", \"category\": \"-Wdeprecated\", \"project\": None, \"hint\": \"\" ' 35", "test_warnings_regex(expected, request): compiler = request.node.callspec.id matches = list( match.groupdict() for match in re.finditer(Regex.get(compiler),", "int [4]' to parameter of type 'int *' converts \" \"between pointers to", "{ \"channel\": None, \"info\": \"this is important\", \"name\": None, \"ref\": None, \"severity\": None,", "\"user\": None, \"info\": \"This conanfile has no build step\", \"severity\": \"WARN\", }, ],", "| &start, &end, perm, &offset, dev, &inode, file);\\n\" \" | ~~~~~~\\n\" \" |", "| |\", \" | void*\", \"ninja/1.9.0 (test package): WARN: This conanfile has no", "\"C:\\\\Program Files (x86)\\\\Microsoft Visual Studio\\\\include\\\\stdatomic.h(15,2): \" \"error: <stdatomic.h> is not yet supported when", "of greater size\", \"C:\\\\source_subfolder\\\\bzlib.c(1418,10): warning C4996: 'strcat': This function or variable \" \"may", "PostgreSQL then you do not need to worry about this, because the Bison\"", "def test_warnings_regex(expected, request): compiler = request.node.callspec.id matches = list( match.groupdict() for match in", "\"Makefile.config\", \"info\": \"No sys/sdt.h found, no SDT events are defined, please install \"", "from /package/include/glib-2.0/gobject/gobject.h:24,\", \" from /package/include/glib-2.0/gobject/gbinding.h:29,\", \" from /package/include/glib-2.0/glib-object.h:22,\", \" from ../source_subfolder/atk/atkobject.h:27,\", \" from", "\"source_subfolder/meson.build:1559:2: ERROR: Problem encountered: \" \"Could not determine size of size_t.\", \"\", ]", "do not need to worry about this, because the Bison\" \"\\n*** output is", "\"severity\": \"warning\", \"info\": \"OpenSSL 1.1.1l 24 Aug 2021\", \"category\": \"-W#pragma-messages\", \"project\": None, \"hint\":", "\"category\": \"-Wimplicit-function-declaration\", \"project\": None, \"hint\": \"\" \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\\n\" \" ^~~~~~\", },", "\"rmtree.c: In function ‘rmtree’:\\n\" \"In file included from ../../src/include/c.h:54,\\n\" \" from ../../src/include/postgres.h:46,\\n\" \"", "api.prefix {constexpYY}\", \"/source_subfolder/src/constexp.y: warning: fix-its can be applied. Rerun with option \" \"'--update'.", "\" from ../../src/include/postgres_fe.h:25,\\n\" \" from archive.c:19:\\n\", \"file\": \"../../src/include/pg_config.h\", \"line\": \"772\", \"column\": \"24\", \"severity\":", "\"warning\", \"info\": \"'reinterpret_cast': conversion from 'int' to 'HANDLE' of greater size\", \"category\": \"C4312\",", "of\", \"*** PostgreSQL then you do not need to worry about this, because", "\"file\": \"C:\\\\src\\\\bzlib.c\", \"line\": \"161\", \"column\": None, \"severity\": \"note\", \"category\": None, \"project\": None, \"info\":", "\"file\": None, \"line\": None, \"function\": None, \"info\": \" Manually-specified variables were not used", "}, { \"file\": \"cmake/ldap.cmake\", \"line\": \"158\", \"severity\": \"Warning\", \"function\": \"MESSAGE\", \"info\": \" Could", "None, \"hint\": \"\" ' 409 | printf(\"] 0x%p\\\\n\", this);\\n' \" | ~^\\n\" \"", "from crypto\\\\asn1\\\\a_sign.c:22:\\n\" \"In file included from include\\\\crypto/evp.h:11:\\n\" \"In file included from include\\\\internal/refcount.h:21:\\n\" \"In", "\"source_subfolder/meson.build\", \"line\": \"1559\", \"column\": \"2\", \"severity\": \"ERROR\", \"category\": None, \"info\": \"Problem encountered: Could", "None, \"hint\": \" 284 | #endif\\n | \", }, { \"context\": \"./src/graph.cc: In", "function or variable may be unsafe. Consider using \" \"strcat_s instead. To disable", "None, }, { \"from\": \"configure\", \"line\": None, \"severity\": \"WARNING\", \"info\": \"\" \"\\n*** Without", "implicit declaration of function \" \"\\u2018memset\\u2019 [-Wimplicit-function-declaration]\", \" memset(&reicevedSignals, 0, sizeof(reicevedSignals));\", \" ^~~~~~\",", "fileMetaInfo.st_gid );\", \" | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\", \"/source_subfolder/src/constexp.y:35.1-25: warning: deprecated directive: ‘%name-prefix \" '\"constexpYY\"’, use", "= sscanf (line, \"%lx-%lx %9s %lx %9s %ld %s\",\\n' \" | ~~^\\n\" \"", "\"‘Em_FilteringQmFu_processSensorSignals’:\\n\", \"file\": \"src/main/src/Em_FilteringQmFu.c\", \"line\": \"266\", \"column\": \"5\", \"severity\": \"warning\", \"info\": \"implicit declaration of", "\"libmysqlclient\", \"version\": \"8.0.25\", \"user\": None, \"channel\": None, \"severity_l\": \"WARN\", \"severity\": None, \"info\": \"requirement", "\"error: <stdatomic.h> is not yet supported when compiling as C\", \"#error <stdatomic.h> is", "with 0 parameters\", \"category\": \"-w+macro-params-legacy\", \"project\": None, \"hint\": None, }, { \"context\": \"In", "file included from ../../src/include/c.h:54,\", \" from ../../src/include/postgres.h:46,\", \" from stringinfo.c:20:\", \"../../src/include/pg_config.h:772:24: warning: ISO" ]
[ "that this request can be trusted signed_field_names = request.POST.get(\"signed_field_names\") if not signed_field_names: raise", "request.POST.get(\"signed_field_names\") if not signed_field_names: raise SuspiciousOperation(\"Request has no fields to verify\") signed_field_names =", "verify\") signed_field_names = signed_field_names.split(\",\") signature_given = request.POST[\"signature\"].encode(\"utf-8\") signature_calc = self.sign(request.POST, signed_field_names) return signature_given", "hashlib import hmac import base64 class SecureAcceptanceSigner(object): def __init__(self, secret_key): self.secret_key = secret_key", "signed_field_names) return signature_given == signature_calc def _build_message(self, data, signed_fields): parts = [] for", "msg_raw = self._build_message(data, signed_fields).encode(\"utf-8\") msg_hmac = hmac.new(key, msg_raw, hashlib.sha256) return base64.b64encode(msg_hmac.digest()) def verify_request(self,", "= request.POST[\"signature\"].encode(\"utf-8\") signature_calc = self.sign(request.POST, signed_field_names) return signature_given == signature_calc def _build_message(self, data,", "signed_field_names.split(\",\") signature_given = request.POST[\"signature\"].encode(\"utf-8\") signature_calc = self.sign(request.POST, signed_field_names) return signature_given == signature_calc def", "signature_given == signature_calc def _build_message(self, data, signed_fields): parts = [] for field in", "msg_hmac = hmac.new(key, msg_raw, hashlib.sha256) return base64.b64encode(msg_hmac.digest()) def verify_request(self, request): # Ensure the", "sign(self, data, signed_fields): key = self.secret_key.encode(\"utf-8\") msg_raw = self._build_message(data, signed_fields).encode(\"utf-8\") msg_hmac = hmac.new(key,", "data, signed_fields): key = self.secret_key.encode(\"utf-8\") msg_raw = self._build_message(data, signed_fields).encode(\"utf-8\") msg_hmac = hmac.new(key, msg_raw,", "def _build_message(self, data, signed_fields): parts = [] for field in signed_fields: parts.append(\"%s=%s\" %", "self.sign(request.POST, signed_field_names) return signature_given == signature_calc def _build_message(self, data, signed_fields): parts = []", "signed_fields): parts = [] for field in signed_fields: parts.append(\"%s=%s\" % (field, data.get(field, \"\")))", "SuspiciousOperation import hashlib import hmac import base64 class SecureAcceptanceSigner(object): def __init__(self, secret_key): self.secret_key", "signature_calc = self.sign(request.POST, signed_field_names) return signature_given == signature_calc def _build_message(self, data, signed_fields): parts", "parts = [] for field in signed_fields: parts.append(\"%s=%s\" % (field, data.get(field, \"\"))) return", "request): # Ensure the signature is valid and that this request can be", "= signed_field_names.split(\",\") signature_given = request.POST[\"signature\"].encode(\"utf-8\") signature_calc = self.sign(request.POST, signed_field_names) return signature_given == signature_calc", "def __init__(self, secret_key): self.secret_key = secret_key def sign(self, data, signed_fields): key = self.secret_key.encode(\"utf-8\")", "be trusted signed_field_names = request.POST.get(\"signed_field_names\") if not signed_field_names: raise SuspiciousOperation(\"Request has no fields", "signed_field_names: raise SuspiciousOperation(\"Request has no fields to verify\") signed_field_names = signed_field_names.split(\",\") signature_given =", "base64.b64encode(msg_hmac.digest()) def verify_request(self, request): # Ensure the signature is valid and that this", "raise SuspiciousOperation(\"Request has no fields to verify\") signed_field_names = signed_field_names.split(\",\") signature_given = request.POST[\"signature\"].encode(\"utf-8\")", "return signature_given == signature_calc def _build_message(self, data, signed_fields): parts = [] for field", "not signed_field_names: raise SuspiciousOperation(\"Request has no fields to verify\") signed_field_names = signed_field_names.split(\",\") signature_given", "= self.sign(request.POST, signed_field_names) return signature_given == signature_calc def _build_message(self, data, signed_fields): parts =", "return base64.b64encode(msg_hmac.digest()) def verify_request(self, request): # Ensure the signature is valid and that", "request.POST[\"signature\"].encode(\"utf-8\") signature_calc = self.sign(request.POST, signed_field_names) return signature_given == signature_calc def _build_message(self, data, signed_fields):", "has no fields to verify\") signed_field_names = signed_field_names.split(\",\") signature_given = request.POST[\"signature\"].encode(\"utf-8\") signature_calc =", "to verify\") signed_field_names = signed_field_names.split(\",\") signature_given = request.POST[\"signature\"].encode(\"utf-8\") signature_calc = self.sign(request.POST, signed_field_names) return", "def sign(self, data, signed_fields): key = self.secret_key.encode(\"utf-8\") msg_raw = self._build_message(data, signed_fields).encode(\"utf-8\") msg_hmac =", "no fields to verify\") signed_field_names = signed_field_names.split(\",\") signature_given = request.POST[\"signature\"].encode(\"utf-8\") signature_calc = self.sign(request.POST,", "from django.core.exceptions import SuspiciousOperation import hashlib import hmac import base64 class SecureAcceptanceSigner(object): def", "import base64 class SecureAcceptanceSigner(object): def __init__(self, secret_key): self.secret_key = secret_key def sign(self, data,", "__init__(self, secret_key): self.secret_key = secret_key def sign(self, data, signed_fields): key = self.secret_key.encode(\"utf-8\") msg_raw", "data, signed_fields): parts = [] for field in signed_fields: parts.append(\"%s=%s\" % (field, data.get(field,", "if not signed_field_names: raise SuspiciousOperation(\"Request has no fields to verify\") signed_field_names = signed_field_names.split(\",\")", "SuspiciousOperation(\"Request has no fields to verify\") signed_field_names = signed_field_names.split(\",\") signature_given = request.POST[\"signature\"].encode(\"utf-8\") signature_calc", "import hashlib import hmac import base64 class SecureAcceptanceSigner(object): def __init__(self, secret_key): self.secret_key =", "key = self.secret_key.encode(\"utf-8\") msg_raw = self._build_message(data, signed_fields).encode(\"utf-8\") msg_hmac = hmac.new(key, msg_raw, hashlib.sha256) return", "signature_calc def _build_message(self, data, signed_fields): parts = [] for field in signed_fields: parts.append(\"%s=%s\"", "django.core.exceptions import SuspiciousOperation import hashlib import hmac import base64 class SecureAcceptanceSigner(object): def __init__(self,", "hmac import base64 class SecureAcceptanceSigner(object): def __init__(self, secret_key): self.secret_key = secret_key def sign(self,", "= request.POST.get(\"signed_field_names\") if not signed_field_names: raise SuspiciousOperation(\"Request has no fields to verify\") signed_field_names", "request can be trusted signed_field_names = request.POST.get(\"signed_field_names\") if not signed_field_names: raise SuspiciousOperation(\"Request has", "SecureAcceptanceSigner(object): def __init__(self, secret_key): self.secret_key = secret_key def sign(self, data, signed_fields): key =", "import hmac import base64 class SecureAcceptanceSigner(object): def __init__(self, secret_key): self.secret_key = secret_key def", "and that this request can be trusted signed_field_names = request.POST.get(\"signed_field_names\") if not signed_field_names:", "signed_field_names = request.POST.get(\"signed_field_names\") if not signed_field_names: raise SuspiciousOperation(\"Request has no fields to verify\")", "class SecureAcceptanceSigner(object): def __init__(self, secret_key): self.secret_key = secret_key def sign(self, data, signed_fields): key", "the signature is valid and that this request can be trusted signed_field_names =", "hashlib.sha256) return base64.b64encode(msg_hmac.digest()) def verify_request(self, request): # Ensure the signature is valid and", "import SuspiciousOperation import hashlib import hmac import base64 class SecureAcceptanceSigner(object): def __init__(self, secret_key):", "= self.secret_key.encode(\"utf-8\") msg_raw = self._build_message(data, signed_fields).encode(\"utf-8\") msg_hmac = hmac.new(key, msg_raw, hashlib.sha256) return base64.b64encode(msg_hmac.digest())", "== signature_calc def _build_message(self, data, signed_fields): parts = [] for field in signed_fields:", "this request can be trusted signed_field_names = request.POST.get(\"signed_field_names\") if not signed_field_names: raise SuspiciousOperation(\"Request", "can be trusted signed_field_names = request.POST.get(\"signed_field_names\") if not signed_field_names: raise SuspiciousOperation(\"Request has no", "trusted signed_field_names = request.POST.get(\"signed_field_names\") if not signed_field_names: raise SuspiciousOperation(\"Request has no fields to", "# Ensure the signature is valid and that this request can be trusted", "signed_field_names = signed_field_names.split(\",\") signature_given = request.POST[\"signature\"].encode(\"utf-8\") signature_calc = self.sign(request.POST, signed_field_names) return signature_given ==", "signature_given = request.POST[\"signature\"].encode(\"utf-8\") signature_calc = self.sign(request.POST, signed_field_names) return signature_given == signature_calc def _build_message(self,", "self.secret_key.encode(\"utf-8\") msg_raw = self._build_message(data, signed_fields).encode(\"utf-8\") msg_hmac = hmac.new(key, msg_raw, hashlib.sha256) return base64.b64encode(msg_hmac.digest()) def", "verify_request(self, request): # Ensure the signature is valid and that this request can", "fields to verify\") signed_field_names = signed_field_names.split(\",\") signature_given = request.POST[\"signature\"].encode(\"utf-8\") signature_calc = self.sign(request.POST, signed_field_names)", "= self._build_message(data, signed_fields).encode(\"utf-8\") msg_hmac = hmac.new(key, msg_raw, hashlib.sha256) return base64.b64encode(msg_hmac.digest()) def verify_request(self, request):", "_build_message(self, data, signed_fields): parts = [] for field in signed_fields: parts.append(\"%s=%s\" % (field,", "signed_fields).encode(\"utf-8\") msg_hmac = hmac.new(key, msg_raw, hashlib.sha256) return base64.b64encode(msg_hmac.digest()) def verify_request(self, request): # Ensure", "msg_raw, hashlib.sha256) return base64.b64encode(msg_hmac.digest()) def verify_request(self, request): # Ensure the signature is valid", "= [] for field in signed_fields: parts.append(\"%s=%s\" % (field, data.get(field, \"\"))) return \",\".join(parts)", "Ensure the signature is valid and that this request can be trusted signed_field_names", "def verify_request(self, request): # Ensure the signature is valid and that this request", "hmac.new(key, msg_raw, hashlib.sha256) return base64.b64encode(msg_hmac.digest()) def verify_request(self, request): # Ensure the signature is", "valid and that this request can be trusted signed_field_names = request.POST.get(\"signed_field_names\") if not", "self.secret_key = secret_key def sign(self, data, signed_fields): key = self.secret_key.encode(\"utf-8\") msg_raw = self._build_message(data,", "is valid and that this request can be trusted signed_field_names = request.POST.get(\"signed_field_names\") if", "secret_key): self.secret_key = secret_key def sign(self, data, signed_fields): key = self.secret_key.encode(\"utf-8\") msg_raw =", "signature is valid and that this request can be trusted signed_field_names = request.POST.get(\"signed_field_names\")", "base64 class SecureAcceptanceSigner(object): def __init__(self, secret_key): self.secret_key = secret_key def sign(self, data, signed_fields):", "= secret_key def sign(self, data, signed_fields): key = self.secret_key.encode(\"utf-8\") msg_raw = self._build_message(data, signed_fields).encode(\"utf-8\")", "self._build_message(data, signed_fields).encode(\"utf-8\") msg_hmac = hmac.new(key, msg_raw, hashlib.sha256) return base64.b64encode(msg_hmac.digest()) def verify_request(self, request): #", "= hmac.new(key, msg_raw, hashlib.sha256) return base64.b64encode(msg_hmac.digest()) def verify_request(self, request): # Ensure the signature", "signed_fields): key = self.secret_key.encode(\"utf-8\") msg_raw = self._build_message(data, signed_fields).encode(\"utf-8\") msg_hmac = hmac.new(key, msg_raw, hashlib.sha256)", "secret_key def sign(self, data, signed_fields): key = self.secret_key.encode(\"utf-8\") msg_raw = self._build_message(data, signed_fields).encode(\"utf-8\") msg_hmac" ]
[ "permutation(stringA, stringB): listA = list(stringA) listB = list(stringB) listA.sort() listB.sort() if(listA != listB):", "list(stringA) listB = list(stringB) listA.sort() listB.sort() if(listA != listB): return False else: return", "stringB): listA = list(stringA) listB = list(stringB) listA.sort() listB.sort() if(listA != listB): return", "listA = list(stringA) listB = list(stringB) listA.sort() listB.sort() if(listA != listB): return False", "listB = list(stringB) listA.sort() listB.sort() if(listA != listB): return False else: return True", "def permutation(stringA, stringB): listA = list(stringA) listB = list(stringB) listA.sort() listB.sort() if(listA !=", "= list(stringA) listB = list(stringB) listA.sort() listB.sort() if(listA != listB): return False else:", "<reponame>lorderikir/Cracking-the-Coding-Interview def permutation(stringA, stringB): listA = list(stringA) listB = list(stringB) listA.sort() listB.sort() if(listA" ]
[ "browser.execute_script(\"return window.screen.height;\") # get the screen height of the web i = 1", "restaurants = browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]') print(f'resto found till now: {len(restaurants)}') # Break the loop when", "elif o in (\"-h\", \"--help\"): usage() sys.exit() elif o in (\"-o\", \"--output\"): output", "infinite scroll can be normally stop when the scrolled more than remain scrollHeight", "return sorted_set def usage(): print('Usage: ./ancv_html_scraper.py -c <city> -o <output-file>') def main(): try:", "(\"-h\", \"--help\"): usage() sys.exit() elif o in (\"-o\", \"--output\"): output = a elif", "= Options() options.add_argument('--headless') options.add_argument(\"--no-sandbox\") options.add_argument(\"--disable-dev-shm-usage\") browser = webdriver.Chrome(options=options) # total restaurants total_resto =", "the results...') sorted_set = sorted(resto_set) print('Done') print(f'Restaurants found: {len(sorted_set)}') return sorted_set def usage():", "help information and exit: print(err) # will print something like \"option -a not", "html.fromstring(page.content) total_resto_number = tree.xpath('//*[@id=\"spanNbResult\"]/text()') if total_resto_number == None or len(total_resto_number) == 0: return", "open(output,\"w\") as file: for t in set_items: str = ''.join(t) file.writelines(str + '\\n')", "list of sorted items in file def store(set_items, output): if output == None:", "will print something like \"option -a not recognized\" usage() sys.exit(2) output = None", "= None verbose = False silent_mode = False for o, a in opts:", "to do not open the browser options = Options() options.add_argument('--headless') options.add_argument(\"--no-sandbox\") options.add_argument(\"--disable-dev-shm-usage\") browser", "in (\"-o\", \"--output\"): output = a elif o in (\"-c\", \"--city\"): city =", "scrolls screen_height = browser.execute_script(\"return window.screen.height;\") # get the screen height of the web", "when the user scrolls the page, this made their website much more usable.", "restaurants to the set for r in restaurants: print(f'Restaurant name: {r.text}') t =", "something like \"option -a not recognized\" usage() sys.exit(2) output = None city =", "to avoid infinite loop. time.sleep(2) # Allow 2 seconds for the web page", "= f if city == None : print('city is a mandatory parameter') exit(1)", "# I will add a safety timer to avoid infinite loop. time.sleep(2) #", "restaurant found') return else: print(f'restaurants {len(restaurants)} found') # Add restaurants to the set", "for r in restaurants: print(f'Restaurant name: {r.text}') t = r.text.replace(\"\\'\", \"\") resto_set.add(t) print('Removing", "Options #old_address = lambda n,city: f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}' address = lambda city: f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration' # Write", "more than remain scrollHeight # for some reason in this website thescrollHeight attribute", "to stop the loop we found all the restaurants. # I will add", "True elif o in (\"-h\", \"--help\"): usage() sys.exit() elif o in (\"-o\", \"--output\"):", "else: print(f'Total number of restaurants: {total_resto_number[0]}') return int(total_resto_number[0]) def restoLookup(city): print('Start...') total_resto =", "made their website much more usable. # The infinite scroll can be normally", "None : print('city is a mandatory parameter') exit(1) if output == None :", "page to open scroll_pause_time = 4 # set pause time between scrolls screen_height", "= r.text.replace(\"\\'\", \"\") resto_set.add(t) print('Removing duplicates and sorting the results...') sorted_set = sorted(resto_set)", "total_resto = getTotalNumberOfRestaurants(browser, city) if total_resto == 0: print(f'no restaurant found') return #", "main(): try: opts, args = getopt.getopt(sys.argv[1:], \"ho:v:c:s\", [\"help\", \"output=\", \"city=\", \"silent-mode\"]) except getopt.GetoptError", "restaurants: print(f'Restaurant name: {r.text}') t = r.text.replace(\"\\'\", \"\") resto_set.add(t) print('Removing duplicates and sorting", "print(f'no restaurant found') return else: print(f'restaurants {len(restaurants)} found') # Add restaurants to the", "verbose = True elif o in (\"-h\", \"--help\"): usage() sys.exit() elif o in", "usage() sys.exit(2) output = None city = None verbose = False silent_mode =", "duplicates and sorting the results...') sorted_set = sorted(resto_set) print('Done') print(f'Restaurants found: {len(sorted_set)}') return", "False, \"unhandled option\" if silent_mode == True: f = open(os.devnull, 'w') sys.stdout =", "{screen_height}*{i}*10);\".format(screen_height=screen_height, i=i)) i += 1 time.sleep(scroll_pause_time) # update scroll height each time after", "number of restaurants page = requests.get(address(city)) browser.get(address(city)) if page.status_code != 200: print(f'cannot connect", "each time after scrolled, as the scroll height can change after we scrolled", "scroll_height: # Warning: stopping when we found all the restaturants if len(restaurants) >=", "add a safety timer to avoid infinite loop. time.sleep(2) # Allow 2 seconds", "def store(set_items, output): if output == None: print('output name is mandatory') exit(1) else:", "Add restaurants to the set for r in restaurants: print(f'Restaurant name: {r.text}') t", "scroll can be normally stop when the scrolled more than remain scrollHeight #", "height each time browser.execute_script(\"window.scrollTo(0, {screen_height}*{i}*10);\".format(screen_height=screen_height, i=i)) i += 1 time.sleep(scroll_pause_time) # update scroll", "None city = None verbose = False silent_mode = False for o, a", "in (\"-c\", \"--city\"): city = a elif o in (\"-s\", \"--silent-mode\"): silent_mode =", "'w') sys.stdout = f if city == None : print('city is a mandatory", "= webdriver.Chrome(options=options) # total restaurants total_resto = getTotalNumberOfRestaurants(browser, city) if total_resto == 0:", "= True else: assert False, \"unhandled option\" if silent_mode == True: f =", "if output == None : output = 'restaurants_cv.txt' restaurants = restoLookup(city) store(restaurants, output)", "total number of restaurants page = requests.get(address(city)) browser.get(address(city)) if page.status_code != 200: print(f'cannot", "the screen height of the web i = 1 while True: # scroll", "browser.execute_script(\"window.scrollTo(0, {screen_height}*{i}*10);\".format(screen_height=screen_height, i=i)) i += 1 time.sleep(scroll_pause_time) # update scroll height each time", "re import time from selenium import webdriver from selenium.webdriver.chrome.options import Options #old_address =", "Options() options.add_argument('--headless') options.add_argument(\"--no-sandbox\") options.add_argument(\"--disable-dev-shm-usage\") browser = webdriver.Chrome(options=options) # total restaurants total_resto = getTotalNumberOfRestaurants(browser,", "scrolled the page #scroll_height = browser.execute_script(\"return document.body.scrollHeight;\") restaurants = browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]') print(f'resto found till", "{len(sorted_set)}') return sorted_set def usage(): print('Usage: ./ancv_html_scraper.py -c <city> -o <output-file>') def main():", "found') # Add restaurants to the set for r in restaurants: print(f'Restaurant name:", "restaurant found') return # collect all the restaurants name restaurants = [] #", "in (\"-h\", \"--help\"): usage() sys.exit() elif o in (\"-o\", \"--output\"): output = a", "import requests import urllib import getopt, sys, os import re import time from", "site, the list of restaurants is loaded dinamically # when the user scrolls", "'\\n') def getTotalNumberOfRestaurants(browser, city): # Get the total number of restaurants page =", "page, this made their website much more usable. # The infinite scroll can", "== 0: return 0 else: print(f'Total number of restaurants: {total_resto_number[0]}') return int(total_resto_number[0]) def", "print(f'resto found till now: {len(restaurants)}') # Break the loop when the height we", "parameter') exit(1) if output == None : output = 'restaurants_cv.txt' restaurants = restoLookup(city)", "#old_address = lambda n,city: f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}' address = lambda city: f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration' # Write the", "o in (\"-o\", \"--output\"): output = a elif o in (\"-c\", \"--city\"): city", "html import requests import urllib import getopt, sys, os import re import time", "update scroll height each time after scrolled, as the scroll height can change", "= browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]') print(f'resto found till now: {len(restaurants)}') # Break the loop when the", "Warning: stopping when we found all the restaturants if len(restaurants) >= total_resto: break", "== None or len(total_resto_number) == 0: return 0 else: print(f'Total number of restaurants:", "we found all the restaturants if len(restaurants) >= total_resto: break if len(restaurants) ==", "mandatory parameter') exit(1) if output == None : output = 'restaurants_cv.txt' restaurants =", "usage() sys.exit() elif o in (\"-o\", \"--output\"): output = a elif o in", "scroll height each time after scrolled, as the scroll height can change after", "a elif o in (\"-c\", \"--city\"): city = a elif o in (\"-s\",", ">= total_resto: break if len(restaurants) == 0: print(f'no restaurant found') return else: print(f'restaurants", "browser.get(address(city)) if page.status_code != 200: print(f'cannot connect to ancv website') sys.exit(1) tree =", "and exit: print(err) # will print something like \"option -a not recognized\" usage()", "page #scroll_height = browser.execute_script(\"return document.body.scrollHeight;\") restaurants = browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]') print(f'resto found till now: {len(restaurants)}')", "restaurants: {total_resto_number[0]}') return int(total_resto_number[0]) def restoLookup(city): print('Start...') total_resto = 0 resto_set = set()", "= a elif o in (\"-c\", \"--city\"): city = a elif o in", "scroll height #if (screen_height) * i > scroll_height: # Warning: stopping when we", "\"--silent-mode\"): silent_mode = True else: assert False, \"unhandled option\" if silent_mode == True:", "output = None city = None verbose = False silent_mode = False for", "getopt, sys, os import re import time from selenium import webdriver from selenium.webdriver.chrome.options", "== None: print('output name is mandatory') exit(1) else: with open(output,\"w\") as file: for", "= html.fromstring(page.content) total_resto_number = tree.xpath('//*[@id=\"spanNbResult\"]/text()') if total_resto_number == None or len(total_resto_number) == 0:", "to is larger than the total scroll height #if (screen_height) * i >", "if len(restaurants) >= total_resto: break if len(restaurants) == 0: print(f'no restaurant found') return", "= set() # Set option to do not open the browser options =", "document.body.scrollHeight;\") restaurants = browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]') print(f'resto found till now: {len(restaurants)}') # Break the loop", "Get the total number of restaurants page = requests.get(address(city)) browser.get(address(city)) if page.status_code !=", "makedirs, path from lxml import html import requests import urllib import getopt, sys,", "time between scrolls screen_height = browser.execute_script(\"return window.screen.height;\") # get the screen height of", "print(f'no restaurant found') return # collect all the restaurants name restaurants = []", "is loaded dinamically # when the user scrolls the page, this made their", "after each scroll. # The workaround was to stop the loop we found", "if output == None: print('output name is mandatory') exit(1) else: with open(output,\"w\") as", "# total restaurants total_resto = getTotalNumberOfRestaurants(browser, city) if total_resto == 0: print(f'no restaurant", "city = a elif o in (\"-s\", \"--silent-mode\"): silent_mode = True else: assert", "browser options = Options() options.add_argument('--headless') options.add_argument(\"--no-sandbox\") options.add_argument(\"--disable-dev-shm-usage\") browser = webdriver.Chrome(options=options) # total restaurants", "collect all the restaurants name restaurants = [] # With the latest version", "err: # print help information and exit: print(err) # will print something like", "urllib import getopt, sys, os import re import time from selenium import webdriver", "ancv website') sys.exit(1) tree = html.fromstring(page.content) total_resto_number = tree.xpath('//*[@id=\"spanNbResult\"]/text()') if total_resto_number == None", "{len(restaurants)} found') # Add restaurants to the set for r in restaurants: print(f'Restaurant", "sys.exit(1) tree = html.fromstring(page.content) total_resto_number = tree.xpath('//*[@id=\"spanNbResult\"]/text()') if total_resto_number == None or len(total_resto_number)", "some reason in this website thescrollHeight attribute is not updated after each scroll.", "found all the restaurants. # I will add a safety timer to avoid", "= True elif o in (\"-h\", \"--help\"): usage() sys.exit() elif o in (\"-o\",", "The infinite scroll can be normally stop when the scrolled more than remain", "len(restaurants) >= total_resto: break if len(restaurants) == 0: print(f'no restaurant found') return else:", "f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration' # Write the list of sorted items in file def store(set_items, output):", "== 0: print(f'no restaurant found') return # collect all the restaurants name restaurants", "be normally stop when the scrolled more than remain scrollHeight # for some", "the browser options = Options() options.add_argument('--headless') options.add_argument(\"--no-sandbox\") options.add_argument(\"--disable-dev-shm-usage\") browser = webdriver.Chrome(options=options) # total", "of the web i = 1 while True: # scroll one screen height", "None or len(total_resto_number) == 0: return 0 else: print(f'Total number of restaurants: {total_resto_number[0]}')", "= False for o, a in opts: if o == \"-v\": verbose =", "timer to avoid infinite loop. time.sleep(2) # Allow 2 seconds for the web", "requests import urllib import getopt, sys, os import re import time from selenium", "stop the loop we found all the restaurants. # I will add a", "window.screen.height;\") # get the screen height of the web i = 1 while", "tree.xpath('//*[@id=\"spanNbResult\"]/text()') if total_resto_number == None or len(total_resto_number) == 0: return 0 else: print(f'Total", "while True: # scroll one screen height each time browser.execute_script(\"window.scrollTo(0, {screen_height}*{i}*10);\".format(screen_height=screen_height, i=i)) i", "when the height we need to scroll to is larger than the total", "# Warning: stopping when we found all the restaturants if len(restaurants) >= total_resto:", "f = open(os.devnull, 'w') sys.stdout = f if city == None : print('city", "The workaround was to stop the loop we found all the restaurants. #", "the web i = 1 while True: # scroll one screen height each", "the list of sorted items in file def store(set_items, output): if output ==", "import urllib import getopt, sys, os import re import time from selenium import", "user scrolls the page, this made their website much more usable. # The", "if silent_mode == True: f = open(os.devnull, 'w') sys.stdout = f if city", "screen_height = browser.execute_script(\"return window.screen.height;\") # get the screen height of the web i", "#if (screen_height) * i > scroll_height: # Warning: stopping when we found all", "2 seconds for the web page to open scroll_pause_time = 4 # set", "sys.exit() elif o in (\"-o\", \"--output\"): output = a elif o in (\"-c\",", "./ancv_html_scraper.py -c <city> -o <output-file>') def main(): try: opts, args = getopt.getopt(sys.argv[1:], \"ho:v:c:s\",", "getopt.getopt(sys.argv[1:], \"ho:v:c:s\", [\"help\", \"output=\", \"city=\", \"silent-mode\"]) except getopt.GetoptError as err: # print help", "the page #scroll_height = browser.execute_script(\"return document.body.scrollHeight;\") restaurants = browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]') print(f'resto found till now:", "sorting the results...') sorted_set = sorted(resto_set) print('Done') print(f'Restaurants found: {len(sorted_set)}') return sorted_set def", "os import re import time from selenium import webdriver from selenium.webdriver.chrome.options import Options", "Allow 2 seconds for the web page to open scroll_pause_time = 4 #", "found all the restaturants if len(restaurants) >= total_resto: break if len(restaurants) == 0:", "the user scrolls the page, this made their website much more usable. #", "restaurants is loaded dinamically # when the user scrolls the page, this made", "# Break the loop when the height we need to scroll to is", "of restaurants is loaded dinamically # when the user scrolls the page, this", "\"unhandled option\" if silent_mode == True: f = open(os.devnull, 'w') sys.stdout = f", "remain scrollHeight # for some reason in this website thescrollHeight attribute is not", "# for some reason in this website thescrollHeight attribute is not updated after", "== None : output = 'restaurants_cv.txt' restaurants = restoLookup(city) store(restaurants, output) if __name__", "this website thescrollHeight attribute is not updated after each scroll. # The workaround", "in (\"-s\", \"--silent-mode\"): silent_mode = True else: assert False, \"unhandled option\" if silent_mode", "scrollHeight # for some reason in this website thescrollHeight attribute is not updated", "return # collect all the restaurants name restaurants = [] # With the", "= browser.execute_script(\"return window.screen.height;\") # get the screen height of the web i =", "print(f'cannot connect to ancv website') sys.exit(1) tree = html.fromstring(page.content) total_resto_number = tree.xpath('//*[@id=\"spanNbResult\"]/text()') if", "scroll to is larger than the total scroll height #if (screen_height) * i", "website much more usable. # The infinite scroll can be normally stop when", "the set for r in restaurants: print(f'Restaurant name: {r.text}') t = r.text.replace(\"\\'\", \"\")", "to scroll to is larger than the total scroll height #if (screen_height) *", "from selenium.webdriver.chrome.options import Options #old_address = lambda n,city: f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}' address = lambda city:", "output = a elif o in (\"-c\", \"--city\"): city = a elif o", "time.sleep(scroll_pause_time) # update scroll height each time after scrolled, as the scroll height", "of sorted items in file def store(set_items, output): if output == None: print('output", "all the restaurants. # I will add a safety timer to avoid infinite", "200: print(f'cannot connect to ancv website') sys.exit(1) tree = html.fromstring(page.content) total_resto_number = tree.xpath('//*[@id=\"spanNbResult\"]/text()')", "their website much more usable. # The infinite scroll can be normally stop", "if city == None : print('city is a mandatory parameter') exit(1) if output", "# get the screen height of the web i = 1 while True:", "page.status_code != 200: print(f'cannot connect to ancv website') sys.exit(1) tree = html.fromstring(page.content) total_resto_number", "not open the browser options = Options() options.add_argument('--headless') options.add_argument(\"--no-sandbox\") options.add_argument(\"--disable-dev-shm-usage\") browser = webdriver.Chrome(options=options)", "opts, args = getopt.getopt(sys.argv[1:], \"ho:v:c:s\", [\"help\", \"output=\", \"city=\", \"silent-mode\"]) except getopt.GetoptError as err:", "o in (\"-c\", \"--city\"): city = a elif o in (\"-s\", \"--silent-mode\"): silent_mode", "getTotalNumberOfRestaurants(browser, city) if total_resto == 0: print(f'no restaurant found') return # collect all", "# collect all the restaurants name restaurants = [] # With the latest", "= browser.execute_script(\"return document.body.scrollHeight;\") restaurants = browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]') print(f'resto found till now: {len(restaurants)}') # Break", "for some reason in this website thescrollHeight attribute is not updated after each", "found') return else: print(f'restaurants {len(restaurants)} found') # Add restaurants to the set for", "usage(): print('Usage: ./ancv_html_scraper.py -c <city> -o <output-file>') def main(): try: opts, args =", "scrolled more than remain scrollHeight # for some reason in this website thescrollHeight", "webdriver.Chrome(options=options) # total restaurants total_resto = getTotalNumberOfRestaurants(browser, city) if total_resto == 0: print(f'no", "except getopt.GetoptError as err: # print help information and exit: print(err) # will", "connect to ancv website') sys.exit(1) tree = html.fromstring(page.content) total_resto_number = tree.xpath('//*[@id=\"spanNbResult\"]/text()') if total_resto_number", "mandatory') exit(1) else: with open(output,\"w\") as file: for t in set_items: str =", "usable. # The infinite scroll can be normally stop when the scrolled more", "if total_resto_number == None or len(total_resto_number) == 0: return 0 else: print(f'Total number", "\"-v\": verbose = True elif o in (\"-h\", \"--help\"): usage() sys.exit() elif o", "reason in this website thescrollHeight attribute is not updated after each scroll. #", "results...') sorted_set = sorted(resto_set) print('Done') print(f'Restaurants found: {len(sorted_set)}') return sorted_set def usage(): print('Usage:", "and sorting the results...') sorted_set = sorted(resto_set) print('Done') print(f'Restaurants found: {len(sorted_set)}') return sorted_set", "!= 200: print(f'cannot connect to ancv website') sys.exit(1) tree = html.fromstring(page.content) total_resto_number =", "webdriver from selenium.webdriver.chrome.options import Options #old_address = lambda n,city: f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}' address = lambda", "number of restaurants: {total_resto_number[0]}') return int(total_resto_number[0]) def restoLookup(city): print('Start...') total_resto = 0 resto_set", "''.join(t) file.writelines(str + '\\n') def getTotalNumberOfRestaurants(browser, city): # Get the total number of", "None: print('output name is mandatory') exit(1) else: with open(output,\"w\") as file: for t", "normally stop when the scrolled more than remain scrollHeight # for some reason", "found till now: {len(restaurants)}') # Break the loop when the height we need", "do not open the browser options = Options() options.add_argument('--headless') options.add_argument(\"--no-sandbox\") options.add_argument(\"--disable-dev-shm-usage\") browser =", "\"silent-mode\"]) except getopt.GetoptError as err: # print help information and exit: print(err) #", "pause time between scrolls screen_height = browser.execute_script(\"return window.screen.height;\") # get the screen height", "for t in set_items: str = ''.join(t) file.writelines(str + '\\n') def getTotalNumberOfRestaurants(browser, city):", "= requests.get(address(city)) browser.get(address(city)) if page.status_code != 200: print(f'cannot connect to ancv website') sys.exit(1)", "print('city is a mandatory parameter') exit(1) if output == None : output =", "not updated after each scroll. # The workaround was to stop the loop", "time.sleep(2) # Allow 2 seconds for the web page to open scroll_pause_time =", "1 while True: # scroll one screen height each time browser.execute_script(\"window.scrollTo(0, {screen_height}*{i}*10);\".format(screen_height=screen_height, i=i))", "# Write the list of sorted items in file def store(set_items, output): if", "{len(restaurants)}') # Break the loop when the height we need to scroll to", "found') return # collect all the restaurants name restaurants = [] # With", "we scrolled the page #scroll_height = browser.execute_script(\"return document.body.scrollHeight;\") restaurants = browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]') print(f'resto found", "open(os.devnull, 'w') sys.stdout = f if city == None : print('city is a", "information and exit: print(err) # will print something like \"option -a not recognized\"", "file def store(set_items, output): if output == None: print('output name is mandatory') exit(1)", "# scroll one screen height each time browser.execute_script(\"window.scrollTo(0, {screen_height}*{i}*10);\".format(screen_height=screen_height, i=i)) i += 1", "= None city = None verbose = False silent_mode = False for o,", "updated after each scroll. # The workaround was to stop the loop we", "file.writelines(str + '\\n') def getTotalNumberOfRestaurants(browser, city): # Get the total number of restaurants", "thescrollHeight attribute is not updated after each scroll. # The workaround was to", "for o, a in opts: if o == \"-v\": verbose = True elif", "found: {len(sorted_set)}') return sorted_set def usage(): print('Usage: ./ancv_html_scraper.py -c <city> -o <output-file>') def", "restaturants if len(restaurants) >= total_resto: break if len(restaurants) == 0: print(f'no restaurant found')", "seconds for the web page to open scroll_pause_time = 4 # set pause", "for the web page to open scroll_pause_time = 4 # set pause time", "# With the latest version of the site, the list of restaurants is", "dinamically # when the user scrolls the page, this made their website much", "-c <city> -o <output-file>') def main(): try: opts, args = getopt.getopt(sys.argv[1:], \"ho:v:c:s\", [\"help\",", "need to scroll to is larger than the total scroll height #if (screen_height)", "Write the list of sorted items in file def store(set_items, output): if output", "store(set_items, output): if output == None: print('output name is mandatory') exit(1) else: with", "the site, the list of restaurants is loaded dinamically # when the user", "\"\") resto_set.add(t) print('Removing duplicates and sorting the results...') sorted_set = sorted(resto_set) print('Done') print(f'Restaurants", "the restaturants if len(restaurants) >= total_resto: break if len(restaurants) == 0: print(f'no restaurant", "i > scroll_height: # Warning: stopping when we found all the restaturants if", "0: print(f'no restaurant found') return # collect all the restaurants name restaurants =", "the scroll height can change after we scrolled the page #scroll_height = browser.execute_script(\"return", "Break the loop when the height we need to scroll to is larger", "# The infinite scroll can be normally stop when the scrolled more than", "a in opts: if o == \"-v\": verbose = True elif o in", "i += 1 time.sleep(scroll_pause_time) # update scroll height each time after scrolled, as", "scroll one screen height each time browser.execute_script(\"window.scrollTo(0, {screen_height}*{i}*10);\".format(screen_height=screen_height, i=i)) i += 1 time.sleep(scroll_pause_time)", "import getopt, sys, os import re import time from selenium import webdriver from", "get the screen height of the web i = 1 while True: #", "avoid infinite loop. time.sleep(2) # Allow 2 seconds for the web page to", "def usage(): print('Usage: ./ancv_html_scraper.py -c <city> -o <output-file>') def main(): try: opts, args", "elif o in (\"-c\", \"--city\"): city = a elif o in (\"-s\", \"--silent-mode\"):", "-a not recognized\" usage() sys.exit(2) output = None city = None verbose =", "much more usable. # The infinite scroll can be normally stop when the", "was to stop the loop we found all the restaurants. # I will", "loop we found all the restaurants. # I will add a safety timer", "we found all the restaurants. # I will add a safety timer to", "browser = webdriver.Chrome(options=options) # total restaurants total_resto = getTotalNumberOfRestaurants(browser, city) if total_resto ==", "of restaurants: {total_resto_number[0]}') return int(total_resto_number[0]) def restoLookup(city): print('Start...') total_resto = 0 resto_set =", "a elif o in (\"-s\", \"--silent-mode\"): silent_mode = True else: assert False, \"unhandled", "browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]') print(f'resto found till now: {len(restaurants)}') # Break the loop when the height", "will add a safety timer to avoid infinite loop. time.sleep(2) # Allow 2", "exit(1) else: with open(output,\"w\") as file: for t in set_items: str = ''.join(t)", "(\"-s\", \"--silent-mode\"): silent_mode = True else: assert False, \"unhandled option\" if silent_mode ==", "== None : print('city is a mandatory parameter') exit(1) if output == None", "scroll. # The workaround was to stop the loop we found all the", "sorted_set def usage(): print('Usage: ./ancv_html_scraper.py -c <city> -o <output-file>') def main(): try: opts,", "getopt.GetoptError as err: # print help information and exit: print(err) # will print", "name restaurants = [] # With the latest version of the site, the", "<output-file>') def main(): try: opts, args = getopt.getopt(sys.argv[1:], \"ho:v:c:s\", [\"help\", \"output=\", \"city=\", \"silent-mode\"])", "silent_mode = False for o, a in opts: if o == \"-v\": verbose", "== \"-v\": verbose = True elif o in (\"-h\", \"--help\"): usage() sys.exit() elif", "we need to scroll to is larger than the total scroll height #if", "restaurants name restaurants = [] # With the latest version of the site,", "= False silent_mode = False for o, a in opts: if o ==", "is larger than the total scroll height #if (screen_height) * i > scroll_height:", "print('Start...') total_resto = 0 resto_set = set() # Set option to do not", "height each time after scrolled, as the scroll height can change after we", "sorted_set = sorted(resto_set) print('Done') print(f'Restaurants found: {len(sorted_set)}') return sorted_set def usage(): print('Usage: ./ancv_html_scraper.py", "# set pause time between scrolls screen_height = browser.execute_script(\"return window.screen.height;\") # get the", "import html import requests import urllib import getopt, sys, os import re import", "# will print something like \"option -a not recognized\" usage() sys.exit(2) output =", "resto_set.add(t) print('Removing duplicates and sorting the results...') sorted_set = sorted(resto_set) print('Done') print(f'Restaurants found:", "print something like \"option -a not recognized\" usage() sys.exit(2) output = None city", "set_items: str = ''.join(t) file.writelines(str + '\\n') def getTotalNumberOfRestaurants(browser, city): # Get the", "city = None verbose = False silent_mode = False for o, a in", "False silent_mode = False for o, a in opts: if o == \"-v\":", "silent_mode == True: f = open(os.devnull, 'w') sys.stdout = f if city ==", "True: # scroll one screen height each time browser.execute_script(\"window.scrollTo(0, {screen_height}*{i}*10);\".format(screen_height=screen_height, i=i)) i +=", "the loop when the height we need to scroll to is larger than", "-o <output-file>') def main(): try: opts, args = getopt.getopt(sys.argv[1:], \"ho:v:c:s\", [\"help\", \"output=\", \"city=\",", "is not updated after each scroll. # The workaround was to stop the", "each scroll. # The workaround was to stop the loop we found all", "1 time.sleep(scroll_pause_time) # update scroll height each time after scrolled, as the scroll", "print(err) # will print something like \"option -a not recognized\" usage() sys.exit(2) output", "the web page to open scroll_pause_time = 4 # set pause time between", "safety timer to avoid infinite loop. time.sleep(2) # Allow 2 seconds for the", "\"output=\", \"city=\", \"silent-mode\"]) except getopt.GetoptError as err: # print help information and exit:", "def getTotalNumberOfRestaurants(browser, city): # Get the total number of restaurants page = requests.get(address(city))", "or len(total_resto_number) == 0: return 0 else: print(f'Total number of restaurants: {total_resto_number[0]}') return", "the height we need to scroll to is larger than the total scroll", "total_resto = 0 resto_set = set() # Set option to do not open", "after we scrolled the page #scroll_height = browser.execute_script(\"return document.body.scrollHeight;\") restaurants = browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]') print(f'resto", "resto_set = set() # Set option to do not open the browser options", "sys.stdout = f if city == None : print('city is a mandatory parameter')", "time browser.execute_script(\"window.scrollTo(0, {screen_height}*{i}*10);\".format(screen_height=screen_height, i=i)) i += 1 time.sleep(scroll_pause_time) # update scroll height each", "= getopt.getopt(sys.argv[1:], \"ho:v:c:s\", [\"help\", \"output=\", \"city=\", \"silent-mode\"]) except getopt.GetoptError as err: # print", "(\"-c\", \"--city\"): city = a elif o in (\"-s\", \"--silent-mode\"): silent_mode = True", "can change after we scrolled the page #scroll_height = browser.execute_script(\"return document.body.scrollHeight;\") restaurants =", "till now: {len(restaurants)}') # Break the loop when the height we need to", "if page.status_code != 200: print(f'cannot connect to ancv website') sys.exit(1) tree = html.fromstring(page.content)", "time after scrolled, as the scroll height can change after we scrolled the", "items in file def store(set_items, output): if output == None: print('output name is", "requests.get(address(city)) browser.get(address(city)) if page.status_code != 200: print(f'cannot connect to ancv website') sys.exit(1) tree", "open scroll_pause_time = 4 # set pause time between scrolls screen_height = browser.execute_script(\"return", "\"ho:v:c:s\", [\"help\", \"output=\", \"city=\", \"silent-mode\"]) except getopt.GetoptError as err: # print help information", "+ '\\n') def getTotalNumberOfRestaurants(browser, city): # Get the total number of restaurants page", "path from lxml import html import requests import urllib import getopt, sys, os", "city) if total_resto == 0: print(f'no restaurant found') return # collect all the", "os import makedirs, path from lxml import html import requests import urllib import", "print('Done') print(f'Restaurants found: {len(sorted_set)}') return sorted_set def usage(): print('Usage: ./ancv_html_scraper.py -c <city> -o", "# update scroll height each time after scrolled, as the scroll height can", "all the restaurants name restaurants = [] # With the latest version of", "height #if (screen_height) * i > scroll_height: # Warning: stopping when we found", "\"--city\"): city = a elif o in (\"-s\", \"--silent-mode\"): silent_mode = True else:", "elif o in (\"-s\", \"--silent-mode\"): silent_mode = True else: assert False, \"unhandled option\"", "# when the user scrolls the page, this made their website much more", "in file def store(set_items, output): if output == None: print('output name is mandatory')", "is mandatory') exit(1) else: with open(output,\"w\") as file: for t in set_items: str", "= ''.join(t) file.writelines(str + '\\n') def getTotalNumberOfRestaurants(browser, city): # Get the total number", "getTotalNumberOfRestaurants(browser, city): # Get the total number of restaurants page = requests.get(address(city)) browser.get(address(city))", "= sorted(resto_set) print('Done') print(f'Restaurants found: {len(sorted_set)}') return sorted_set def usage(): print('Usage: ./ancv_html_scraper.py -c", "file: for t in set_items: str = ''.join(t) file.writelines(str + '\\n') def getTotalNumberOfRestaurants(browser,", "all the restaturants if len(restaurants) >= total_resto: break if len(restaurants) == 0: print(f'no", "I will add a safety timer to avoid infinite loop. time.sleep(2) # Allow", "options.add_argument(\"--no-sandbox\") options.add_argument(\"--disable-dev-shm-usage\") browser = webdriver.Chrome(options=options) # total restaurants total_resto = getTotalNumberOfRestaurants(browser, city) if", "= [] # With the latest version of the site, the list of", "infinite loop. time.sleep(2) # Allow 2 seconds for the web page to open", "str = ''.join(t) file.writelines(str + '\\n') def getTotalNumberOfRestaurants(browser, city): # Get the total", "= lambda city: f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration' # Write the list of sorted items in file", "# Add restaurants to the set for r in restaurants: print(f'Restaurant name: {r.text}')", "stopping when we found all the restaturants if len(restaurants) >= total_resto: break if", "output == None: print('output name is mandatory') exit(1) else: with open(output,\"w\") as file:", "this made their website much more usable. # The infinite scroll can be", "city: f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration' # Write the list of sorted items in file def store(set_items,", "website thescrollHeight attribute is not updated after each scroll. # The workaround was", "a safety timer to avoid infinite loop. time.sleep(2) # Allow 2 seconds for", "0: print(f'no restaurant found') return else: print(f'restaurants {len(restaurants)} found') # Add restaurants to", "options.add_argument('--headless') options.add_argument(\"--no-sandbox\") options.add_argument(\"--disable-dev-shm-usage\") browser = webdriver.Chrome(options=options) # total restaurants total_resto = getTotalNumberOfRestaurants(browser, city)", "False for o, a in opts: if o == \"-v\": verbose = True", "0 else: print(f'Total number of restaurants: {total_resto_number[0]}') return int(total_resto_number[0]) def restoLookup(city): print('Start...') total_resto", "= open(os.devnull, 'w') sys.stdout = f if city == None : print('city is", "of restaurants page = requests.get(address(city)) browser.get(address(city)) if page.status_code != 200: print(f'cannot connect to", "+= 1 time.sleep(scroll_pause_time) # update scroll height each time after scrolled, as the", "the scrolled more than remain scrollHeight # for some reason in this website", "total restaurants total_resto = getTotalNumberOfRestaurants(browser, city) if total_resto == 0: print(f'no restaurant found')", "the latest version of the site, the list of restaurants is loaded dinamically", "selenium import webdriver from selenium.webdriver.chrome.options import Options #old_address = lambda n,city: f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}' address", "sorted(resto_set) print('Done') print(f'Restaurants found: {len(sorted_set)}') return sorted_set def usage(): print('Usage: ./ancv_html_scraper.py -c <city>", "recognized\" usage() sys.exit(2) output = None city = None verbose = False silent_mode", "= tree.xpath('//*[@id=\"spanNbResult\"]/text()') if total_resto_number == None or len(total_resto_number) == 0: return 0 else:", ": output = 'restaurants_cv.txt' restaurants = restoLookup(city) store(restaurants, output) if __name__ == \"__main__\":", "import re import time from selenium import webdriver from selenium.webdriver.chrome.options import Options #old_address", "None : output = 'restaurants_cv.txt' restaurants = restoLookup(city) store(restaurants, output) if __name__ ==", "r.text.replace(\"\\'\", \"\") resto_set.add(t) print('Removing duplicates and sorting the results...') sorted_set = sorted(resto_set) print('Done')", "return else: print(f'restaurants {len(restaurants)} found') # Add restaurants to the set for r", "city == None : print('city is a mandatory parameter') exit(1) if output ==", "as err: # print help information and exit: print(err) # will print something", "def main(): try: opts, args = getopt.getopt(sys.argv[1:], \"ho:v:c:s\", [\"help\", \"output=\", \"city=\", \"silent-mode\"]) except", "silent_mode = True else: assert False, \"unhandled option\" if silent_mode == True: f", "in opts: if o == \"-v\": verbose = True elif o in (\"-h\",", "to open scroll_pause_time = 4 # set pause time between scrolls screen_height =", "time from selenium import webdriver from selenium.webdriver.chrome.options import Options #old_address = lambda n,city:", "scroll height can change after we scrolled the page #scroll_height = browser.execute_script(\"return document.body.scrollHeight;\")", "4 # set pause time between scrolls screen_height = browser.execute_script(\"return window.screen.height;\") # get", "the page, this made their website much more usable. # The infinite scroll", "total scroll height #if (screen_height) * i > scroll_height: # Warning: stopping when", "t = r.text.replace(\"\\'\", \"\") resto_set.add(t) print('Removing duplicates and sorting the results...') sorted_set =", "o in (\"-h\", \"--help\"): usage() sys.exit() elif o in (\"-o\", \"--output\"): output =", "f if city == None : print('city is a mandatory parameter') exit(1) if", ": print('city is a mandatory parameter') exit(1) if output == None : output", "tree = html.fromstring(page.content) total_resto_number = tree.xpath('//*[@id=\"spanNbResult\"]/text()') if total_resto_number == None or len(total_resto_number) ==", "browser.execute_script(\"return document.body.scrollHeight;\") restaurants = browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]') print(f'resto found till now: {len(restaurants)}') # Break the", "i = 1 while True: # scroll one screen height each time browser.execute_script(\"window.scrollTo(0,", "import time from selenium import webdriver from selenium.webdriver.chrome.options import Options #old_address = lambda", "[] # With the latest version of the site, the list of restaurants", "as the scroll height can change after we scrolled the page #scroll_height =", "= getTotalNumberOfRestaurants(browser, city) if total_resto == 0: print(f'no restaurant found') return # collect", "#scroll_height = browser.execute_script(\"return document.body.scrollHeight;\") restaurants = browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]') print(f'resto found till now: {len(restaurants)}') #", "when we found all the restaturants if len(restaurants) >= total_resto: break if len(restaurants)", "option\" if silent_mode == True: f = open(os.devnull, 'w') sys.stdout = f if", "stop when the scrolled more than remain scrollHeight # for some reason in", "version of the site, the list of restaurants is loaded dinamically # when", "address = lambda city: f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration' # Write the list of sorted items in", "page = requests.get(address(city)) browser.get(address(city)) if page.status_code != 200: print(f'cannot connect to ancv website')", "the restaurants name restaurants = [] # With the latest version of the", "0: return 0 else: print(f'Total number of restaurants: {total_resto_number[0]}') return int(total_resto_number[0]) def restoLookup(city):", "return int(total_resto_number[0]) def restoLookup(city): print('Start...') total_resto = 0 resto_set = set() # Set", "o == \"-v\": verbose = True elif o in (\"-h\", \"--help\"): usage() sys.exit()", "open the browser options = Options() options.add_argument('--headless') options.add_argument(\"--no-sandbox\") options.add_argument(\"--disable-dev-shm-usage\") browser = webdriver.Chrome(options=options) #", "print(f'restaurants {len(restaurants)} found') # Add restaurants to the set for r in restaurants:", "With the latest version of the site, the list of restaurants is loaded", "<city> -o <output-file>') def main(): try: opts, args = getopt.getopt(sys.argv[1:], \"ho:v:c:s\", [\"help\", \"output=\",", "else: assert False, \"unhandled option\" if silent_mode == True: f = open(os.devnull, 'w')", "screen height of the web i = 1 while True: # scroll one", "restaurants page = requests.get(address(city)) browser.get(address(city)) if page.status_code != 200: print(f'cannot connect to ancv", "set for r in restaurants: print(f'Restaurant name: {r.text}') t = r.text.replace(\"\\'\", \"\") resto_set.add(t)", "latest version of the site, the list of restaurants is loaded dinamically #", "of the site, the list of restaurants is loaded dinamically # when the", "* i > scroll_height: # Warning: stopping when we found all the restaturants", "output == None : output = 'restaurants_cv.txt' restaurants = restoLookup(city) store(restaurants, output) if", "can be normally stop when the scrolled more than remain scrollHeight # for", "one screen height each time browser.execute_script(\"window.scrollTo(0, {screen_height}*{i}*10);\".format(screen_height=screen_height, i=i)) i += 1 time.sleep(scroll_pause_time) #", "len(total_resto_number) == 0: return 0 else: print(f'Total number of restaurants: {total_resto_number[0]}') return int(total_resto_number[0])", "else: print(f'restaurants {len(restaurants)} found') # Add restaurants to the set for r in", "\"--output\"): output = a elif o in (\"-c\", \"--city\"): city = a elif", "= 1 while True: # scroll one screen height each time browser.execute_script(\"window.scrollTo(0, {screen_height}*{i}*10);\".format(screen_height=screen_height,", "# Allow 2 seconds for the web page to open scroll_pause_time = 4", "output): if output == None: print('output name is mandatory') exit(1) else: with open(output,\"w\")", "total_resto: break if len(restaurants) == 0: print(f'no restaurant found') return else: print(f'restaurants {len(restaurants)}", "[\"help\", \"output=\", \"city=\", \"silent-mode\"]) except getopt.GetoptError as err: # print help information and", "from os import makedirs, path from lxml import html import requests import urllib", "sys.exit(2) output = None city = None verbose = False silent_mode = False", "than the total scroll height #if (screen_height) * i > scroll_height: # Warning:", "= a elif o in (\"-s\", \"--silent-mode\"): silent_mode = True else: assert False,", "def restoLookup(city): print('Start...') total_resto = 0 resto_set = set() # Set option to", "else: with open(output,\"w\") as file: for t in set_items: str = ''.join(t) file.writelines(str", "website') sys.exit(1) tree = html.fromstring(page.content) total_resto_number = tree.xpath('//*[@id=\"spanNbResult\"]/text()') if total_resto_number == None or", "> scroll_height: # Warning: stopping when we found all the restaturants if len(restaurants)", "if len(restaurants) == 0: print(f'no restaurant found') return else: print(f'restaurants {len(restaurants)} found') #", "larger than the total scroll height #if (screen_height) * i > scroll_height: #", "the total number of restaurants page = requests.get(address(city)) browser.get(address(city)) if page.status_code != 200:", "name is mandatory') exit(1) else: with open(output,\"w\") as file: for t in set_items:", "as file: for t in set_items: str = ''.join(t) file.writelines(str + '\\n') def", "restaurants = [] # With the latest version of the site, the list", "print('Usage: ./ancv_html_scraper.py -c <city> -o <output-file>') def main(): try: opts, args = getopt.getopt(sys.argv[1:],", "the loop we found all the restaurants. # I will add a safety", "# The workaround was to stop the loop we found all the restaurants.", "try: opts, args = getopt.getopt(sys.argv[1:], \"ho:v:c:s\", [\"help\", \"output=\", \"city=\", \"silent-mode\"]) except getopt.GetoptError as", "like \"option -a not recognized\" usage() sys.exit(2) output = None city = None", "set pause time between scrolls screen_height = browser.execute_script(\"return window.screen.height;\") # get the screen", "web i = 1 while True: # scroll one screen height each time", "option to do not open the browser options = Options() options.add_argument('--headless') options.add_argument(\"--no-sandbox\") options.add_argument(\"--disable-dev-shm-usage\")", "attribute is not updated after each scroll. # The workaround was to stop", "== True: f = open(os.devnull, 'w') sys.stdout = f if city == None", "opts: if o == \"-v\": verbose = True elif o in (\"-h\", \"--help\"):", "= 4 # set pause time between scrolls screen_height = browser.execute_script(\"return window.screen.height;\") #", "== 0: print(f'no restaurant found') return else: print(f'restaurants {len(restaurants)} found') # Add restaurants", "web page to open scroll_pause_time = 4 # set pause time between scrolls", "assert False, \"unhandled option\" if silent_mode == True: f = open(os.devnull, 'w') sys.stdout", "t in set_items: str = ''.join(t) file.writelines(str + '\\n') def getTotalNumberOfRestaurants(browser, city): #", "in set_items: str = ''.join(t) file.writelines(str + '\\n') def getTotalNumberOfRestaurants(browser, city): # Get", "print('Removing duplicates and sorting the results...') sorted_set = sorted(resto_set) print('Done') print(f'Restaurants found: {len(sorted_set)}')", "restoLookup(city): print('Start...') total_resto = 0 resto_set = set() # Set option to do", "print('output name is mandatory') exit(1) else: with open(output,\"w\") as file: for t in", "output = 'restaurants_cv.txt' restaurants = restoLookup(city) store(restaurants, output) if __name__ == \"__main__\": main()", "{r.text}') t = r.text.replace(\"\\'\", \"\") resto_set.add(t) print('Removing duplicates and sorting the results...') sorted_set", "f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}' address = lambda city: f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration' # Write the list of sorted items", "with open(output,\"w\") as file: for t in set_items: str = ''.join(t) file.writelines(str +", "args = getopt.getopt(sys.argv[1:], \"ho:v:c:s\", [\"help\", \"output=\", \"city=\", \"silent-mode\"]) except getopt.GetoptError as err: #", "from selenium import webdriver from selenium.webdriver.chrome.options import Options #old_address = lambda n,city: f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}'", "True: f = open(os.devnull, 'w') sys.stdout = f if city == None :", "o, a in opts: if o == \"-v\": verbose = True elif o", "screen height each time browser.execute_script(\"window.scrollTo(0, {screen_height}*{i}*10);\".format(screen_height=screen_height, i=i)) i += 1 time.sleep(scroll_pause_time) # update", "# Set option to do not open the browser options = Options() options.add_argument('--headless')", "None verbose = False silent_mode = False for o, a in opts: if", "o in (\"-s\", \"--silent-mode\"): silent_mode = True else: assert False, \"unhandled option\" if", "total_resto == 0: print(f'no restaurant found') return # collect all the restaurants name", "after scrolled, as the scroll height can change after we scrolled the page", "set() # Set option to do not open the browser options = Options()", "print(f'Total number of restaurants: {total_resto_number[0]}') return int(total_resto_number[0]) def restoLookup(city): print('Start...') total_resto = 0", "verbose = False silent_mode = False for o, a in opts: if o", "height of the web i = 1 while True: # scroll one screen", "restaurants. # I will add a safety timer to avoid infinite loop. time.sleep(2)", "between scrolls screen_height = browser.execute_script(\"return window.screen.height;\") # get the screen height of the", "sys, os import re import time from selenium import webdriver from selenium.webdriver.chrome.options import", "loop. time.sleep(2) # Allow 2 seconds for the web page to open scroll_pause_time", "loop when the height we need to scroll to is larger than the", "city): # Get the total number of restaurants page = requests.get(address(city)) browser.get(address(city)) if", "import webdriver from selenium.webdriver.chrome.options import Options #old_address = lambda n,city: f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}' address =", "len(restaurants) == 0: print(f'no restaurant found') return else: print(f'restaurants {len(restaurants)} found') # Add", "workaround was to stop the loop we found all the restaurants. # I", "loaded dinamically # when the user scrolls the page, this made their website", "print(f'Restaurant name: {r.text}') t = r.text.replace(\"\\'\", \"\") resto_set.add(t) print('Removing duplicates and sorting the", "lambda city: f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration' # Write the list of sorted items in file def", "int(total_resto_number[0]) def restoLookup(city): print('Start...') total_resto = 0 resto_set = set() # Set option", "height can change after we scrolled the page #scroll_height = browser.execute_script(\"return document.body.scrollHeight;\") restaurants", "scroll_pause_time = 4 # set pause time between scrolls screen_height = browser.execute_script(\"return window.screen.height;\")", "exit(1) if output == None : output = 'restaurants_cv.txt' restaurants = restoLookup(city) store(restaurants,", "if o == \"-v\": verbose = True elif o in (\"-h\", \"--help\"): usage()", "Set option to do not open the browser options = Options() options.add_argument('--headless') options.add_argument(\"--no-sandbox\")", "print help information and exit: print(err) # will print something like \"option -a", "options = Options() options.add_argument('--headless') options.add_argument(\"--no-sandbox\") options.add_argument(\"--disable-dev-shm-usage\") browser = webdriver.Chrome(options=options) # total restaurants total_resto", "return 0 else: print(f'Total number of restaurants: {total_resto_number[0]}') return int(total_resto_number[0]) def restoLookup(city): print('Start...')", "the total scroll height #if (screen_height) * i > scroll_height: # Warning: stopping", "options.add_argument(\"--disable-dev-shm-usage\") browser = webdriver.Chrome(options=options) # total restaurants total_resto = getTotalNumberOfRestaurants(browser, city) if total_resto", "# print help information and exit: print(err) # will print something like \"option", "in this website thescrollHeight attribute is not updated after each scroll. # The", "exit: print(err) # will print something like \"option -a not recognized\" usage() sys.exit(2)", "not recognized\" usage() sys.exit(2) output = None city = None verbose = False", "0 resto_set = set() # Set option to do not open the browser", "in restaurants: print(f'Restaurant name: {r.text}') t = r.text.replace(\"\\'\", \"\") resto_set.add(t) print('Removing duplicates and", "r in restaurants: print(f'Restaurant name: {r.text}') t = r.text.replace(\"\\'\", \"\") resto_set.add(t) print('Removing duplicates", "more usable. # The infinite scroll can be normally stop when the scrolled", "from lxml import html import requests import urllib import getopt, sys, os import", "print(f'Restaurants found: {len(sorted_set)}') return sorted_set def usage(): print('Usage: ./ancv_html_scraper.py -c <city> -o <output-file>')", "= lambda n,city: f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}' address = lambda city: f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration' # Write the list", "than remain scrollHeight # for some reason in this website thescrollHeight attribute is", "lxml import html import requests import urllib import getopt, sys, os import re", "{total_resto_number[0]}') return int(total_resto_number[0]) def restoLookup(city): print('Start...') total_resto = 0 resto_set = set() #", "sorted items in file def store(set_items, output): if output == None: print('output name", "break if len(restaurants) == 0: print(f'no restaurant found') return else: print(f'restaurants {len(restaurants)} found')", "change after we scrolled the page #scroll_height = browser.execute_script(\"return document.body.scrollHeight;\") restaurants = browser.find_elements_by_xpath('//*[@id=\"ptl-list-content\"]/div/div/div[2]/p[2]')", "import Options #old_address = lambda n,city: f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}' address = lambda city: f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration' #", "the restaurants. # I will add a safety timer to avoid infinite loop.", "total_resto_number = tree.xpath('//*[@id=\"spanNbResult\"]/text()') if total_resto_number == None or len(total_resto_number) == 0: return 0", "\"--help\"): usage() sys.exit() elif o in (\"-o\", \"--output\"): output = a elif o", "if total_resto == 0: print(f'no restaurant found') return # collect all the restaurants", "when the scrolled more than remain scrollHeight # for some reason in this", "(screen_height) * i > scroll_height: # Warning: stopping when we found all the", "\"option -a not recognized\" usage() sys.exit(2) output = None city = None verbose", "to the set for r in restaurants: print(f'Restaurant name: {r.text}') t = r.text.replace(\"\\'\",", "selenium.webdriver.chrome.options import Options #old_address = lambda n,city: f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}' address = lambda city: f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration'", "lambda n,city: f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}' address = lambda city: f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration' # Write the list of", "i=i)) i += 1 time.sleep(scroll_pause_time) # update scroll height each time after scrolled,", "to ancv website') sys.exit(1) tree = html.fromstring(page.content) total_resto_number = tree.xpath('//*[@id=\"spanNbResult\"]/text()') if total_resto_number ==", "True else: assert False, \"unhandled option\" if silent_mode == True: f = open(os.devnull,", "(\"-o\", \"--output\"): output = a elif o in (\"-c\", \"--city\"): city = a", "scrolls the page, this made their website much more usable. # The infinite", "now: {len(restaurants)}') # Break the loop when the height we need to scroll", "\"city=\", \"silent-mode\"]) except getopt.GetoptError as err: # print help information and exit: print(err)", "= 0 resto_set = set() # Set option to do not open the", "the list of restaurants is loaded dinamically # when the user scrolls the", "n,city: f'https://guide.ancv.com/recherche/liste/cv?page={n}&rows=30&f%5B0%5D=im_field_ptl_activite_reference%3A6339&f%5B1%5D=im_field_ptl_activite_reference%3A6344&localisation={city}' address = lambda city: f'https://leguide.ancv.com/ptl/recherche/list?location={city}&filters%5Bdomaine_activite_principale%5D%5BRestauration%5D=Restauration' # Write the list of sorted", "total_resto_number == None or len(total_resto_number) == 0: return 0 else: print(f'Total number of", "scrolled, as the scroll height can change after we scrolled the page #scroll_height", "restaurants total_resto = getTotalNumberOfRestaurants(browser, city) if total_resto == 0: print(f'no restaurant found') return", "each time browser.execute_script(\"window.scrollTo(0, {screen_height}*{i}*10);\".format(screen_height=screen_height, i=i)) i += 1 time.sleep(scroll_pause_time) # update scroll height", "# Get the total number of restaurants page = requests.get(address(city)) browser.get(address(city)) if page.status_code", "import makedirs, path from lxml import html import requests import urllib import getopt,", "list of restaurants is loaded dinamically # when the user scrolls the page,", "height we need to scroll to is larger than the total scroll height", "name: {r.text}') t = r.text.replace(\"\\'\", \"\") resto_set.add(t) print('Removing duplicates and sorting the results...')", "elif o in (\"-o\", \"--output\"): output = a elif o in (\"-c\", \"--city\"):", "a mandatory parameter') exit(1) if output == None : output = 'restaurants_cv.txt' restaurants", "is a mandatory parameter') exit(1) if output == None : output = 'restaurants_cv.txt'" ]
[ "\"******You are now Backing up CISCO and ARISTA router******\" user = raw_input (\"Enter", "Backing up CISCO and ARISTA router******\" user = raw_input (\"Enter your username of", "up CISCO and ARISTA router******\" user = raw_input (\"Enter your username of CISCO", "print \"******You are now Backing up CISCO and ARISTA router******\" user = raw_input", "(\"Enter your username of CISCO and ARISTA:\") password = getpass.getpass() HOST =(\"192.168.13.144\",\"192.168.13.145\",\"192.168.13.146\") for", "of CISCO and ARISTA:\") password = getpass.getpass() HOST =(\"192.168.13.144\",\"192.168.13.145\",\"192.168.13.146\") for i in HOST:", "are now Backing up CISCO and ARISTA router******\" user = raw_input (\"Enter your", "router******\" user = raw_input (\"Enter your username of CISCO and ARISTA:\") password =", "raw_input (\"Enter your username of CISCO and ARISTA:\") password = getpass.getpass() HOST =(\"192.168.13.144\",\"192.168.13.145\",\"192.168.13.146\")", "= raw_input (\"Enter your username of CISCO and ARISTA:\") password = getpass.getpass() HOST", "<reponame>paringandhi10/AND_lab import getpass import telnetlib print \"******You are now Backing up CISCO and", "import telnetlib print \"******You are now Backing up CISCO and ARISTA router******\" user", "import getpass import telnetlib print \"******You are now Backing up CISCO and ARISTA", "CISCO and ARISTA router******\" user = raw_input (\"Enter your username of CISCO and", "user = raw_input (\"Enter your username of CISCO and ARISTA:\") password = getpass.getpass()", "ARISTA router******\" user = raw_input (\"Enter your username of CISCO and ARISTA:\") password", "telnetlib print \"******You are now Backing up CISCO and ARISTA router******\" user =", "now Backing up CISCO and ARISTA router******\" user = raw_input (\"Enter your username", "your username of CISCO and ARISTA:\") password = getpass.getpass() HOST =(\"192.168.13.144\",\"192.168.13.145\",\"192.168.13.146\") for i", "getpass import telnetlib print \"******You are now Backing up CISCO and ARISTA router******\"", "username of CISCO and ARISTA:\") password = getpass.getpass() HOST =(\"192.168.13.144\",\"192.168.13.145\",\"192.168.13.146\") for i in", "and ARISTA router******\" user = raw_input (\"Enter your username of CISCO and ARISTA:\")" ]
[ "import server from apps import state, county cases = pd.read_csv('data/cases.csv') cases['report_date']=pd.to_datetime(cases.report_date) top_layout =", "2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}) ],style = {'marginTop':'-15px'}), ], className='one-third column', id =", "COVID', style={'marginBottom': '10','marginTop':'-15px'}), html.H3('Virginia COVID-19 Dashboard', style={'marginTop':'-15px'}) ], style={'textAlign':'center'}) ], className='one-third column', id='title'),", "import pandas as pd import numpy as np from app import app from", "html.H3('Virginia COVID-19 Dashboard', style={'marginTop':'-15px'}) ], style={'textAlign':'center'}) ], className='one-third column', id='title'), # last update", "app import app from app import server from apps import state, county cases", "app import server from apps import state, county cases = pd.read_csv('data/cases.csv') cases['report_date']=pd.to_datetime(cases.report_date) top_layout", "dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output import", "import state, county cases = pd.read_csv('data/cases.csv') cases['report_date']=pd.to_datetime(cases.report_date) top_layout = html.Div([ #links to other", "x COVID', style={'marginBottom': '10','marginTop':'-15px'}), html.H3('Virginia COVID-19 Dashboard', style={'marginTop':'-15px'}) ], style={'textAlign':'center'}) ], className='one-third column',", "cases['report_date']=pd.to_datetime(cases.report_date) top_layout = html.Div([ #links to other pages html.Div([ html.Nav(className = \"nav nav-pills\",", "'10','marginTop':'-15px'}), html.H3('Virginia COVID-19 Dashboard', style={'marginTop':'-15px'}) ], style={'textAlign':'center'}) ], className='one-third column', id='title'), # last", "def display_page(pathname): if pathname == '/apps/state': return state.layout if pathname == '/apps/county': return", "'links', style={'textAlign':'center'}), #title html.Div([ html.Div([ html.H2('VA x COVID', style={'marginBottom': '10','marginTop':'-15px'}), html.H3('Virginia COVID-19 Dashboard',", "from app import app from app import server from apps import state, county", "'title1', style={'textAlign':'center'}) ], id='header',className='row flex-display', style={'margin-bottom': '10px','marginTop':'-15px'}) app.layout = html.Div([ dcc.Location(id='url',refresh=False), top_layout, html.Div(id='page-content',children=[])", "html.H5(\"\"), html.A('County', className=\"nav-item nav-link active btn\", href='/apps/county', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px", "= 'links', style={'textAlign':'center'}), #title html.Div([ html.Div([ html.H2('VA x COVID', style={'marginBottom': '10','marginTop':'-15px'}), html.H3('Virginia COVID-19", "#links to other pages html.Div([ html.Nav(className = \"nav nav-pills\", children=[ html.A('State', className=\"nav-item nav-link", "id = 'links', style={'textAlign':'center'}), #title html.Div([ html.Div([ html.H2('VA x COVID', style={'marginBottom': '10','marginTop':'-15px'}), html.H3('Virginia", "@app.callback(Output('page-content', 'children'), [Input('url','pathname')]) def display_page(pathname): if pathname == '/apps/state': return state.layout if pathname", "id='header',className='row flex-display', style={'margin-bottom': '10px','marginTop':'-15px'}) app.layout = html.Div([ dcc.Location(id='url',refresh=False), top_layout, html.Div(id='page-content',children=[]) ], id='mainContainer', style={'display':", "'flex','flex-direction':'column'}) @app.callback(Output('page-content', 'children'), [Input('url','pathname')]) def display_page(pathname): if pathname == '/apps/state': return state.layout if", "html.A('County', className=\"nav-item nav-link active btn\", href='/apps/county', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\",", "COVID-19 Dashboard', style={'marginTop':'-15px'}) ], style={'textAlign':'center'}) ], className='one-third column', id='title'), # last update date", "%d, %Y')) + ' 13:00 (EST)') ], className='one-third column', id = 'title1', style={'textAlign':'center'})", "display_page(pathname): if pathname == '/apps/state': return state.layout if pathname == '/apps/county': return county.layout", "column', id = 'links', style={'textAlign':'center'}), #title html.Div([ html.Div([ html.H2('VA x COVID', style={'marginBottom': '10','marginTop':'-15px'}),", "dash import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input,", "pages html.Div([ html.Nav(className = \"nav nav-pills\", children=[ html.A('State', className=\"nav-item nav-link btn\", href='/apps/state', style={\"font-size\":", "column', id='title'), # last update date html.Div([ html.H6('Last Updated: ', style={'marginTop':'-15px'}), html.H6(str(cases['report_date'].iloc[-1].strftime('%B %d,", "#e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}) ],style = {'marginTop':'-15px'}), ], className='one-third column', id = 'links',", "%Y')) + ' 13:00 (EST)') ], className='one-third column', id = 'title1', style={'textAlign':'center'}) ],", "(EST)') ], className='one-third column', id = 'title1', style={'textAlign':'center'}) ], id='header',className='row flex-display', style={'margin-bottom': '10px','marginTop':'-15px'})", "], id='header',className='row flex-display', style={'margin-bottom': '10px','marginTop':'-15px'}) app.layout = html.Div([ dcc.Location(id='url',refresh=False), top_layout, html.Div(id='page-content',children=[]) ], id='mainContainer',", "pathname == '/apps/state': return state.layout if pathname == '/apps/county': return county.layout else: return", "as html import dash_core_components as dcc from dash.dependencies import Input, Output import plotly.graph_objs", "import plotly.graph_objs as go import plotly.express as px import pandas as pd import", "app.layout = html.Div([ dcc.Location(id='url',refresh=False), top_layout, html.Div(id='page-content',children=[]) ], id='mainContainer', style={'display': 'flex','flex-direction':'column'}) @app.callback(Output('page-content', 'children'), [Input('url','pathname')])", "' 13:00 (EST)') ], className='one-third column', id = 'title1', style={'textAlign':'center'}) ], id='header',className='row flex-display',", "'10px','marginTop':'-15px'}) app.layout = html.Div([ dcc.Location(id='url',refresh=False), top_layout, html.Div(id='page-content',children=[]) ], id='mainContainer', style={'display': 'flex','flex-direction':'column'}) @app.callback(Output('page-content', 'children'),", "'marginTop':'-15px'}), html.H5(\"\"), html.A('County', className=\"nav-item nav-link active btn\", href='/apps/county', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px", "import dash_core_components as dcc from dash.dependencies import Input, Output import plotly.graph_objs as go", "flex-display', style={'margin-bottom': '10px','marginTop':'-15px'}) app.layout = html.Div([ dcc.Location(id='url',refresh=False), top_layout, html.Div(id='page-content',children=[]) ], id='mainContainer', style={'display': 'flex','flex-direction':'column'})", "className=\"nav-item nav-link active btn\", href='/apps/county', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\":", "style={'marginTop':'-15px'}) ], style={'textAlign':'center'}) ], className='one-third column', id='title'), # last update date html.Div([ html.H6('Last", "\"5px\", 'marginTop':'-15px'}), html.H5(\"\"), html.A('County', className=\"nav-item nav-link active btn\", href='/apps/county', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px", "to other pages html.Div([ html.Nav(className = \"nav nav-pills\", children=[ html.A('State', className=\"nav-item nav-link btn\",", "style={'textAlign':'center'}) ], className='one-third column', id='title'), # last update date html.Div([ html.H6('Last Updated: ',", "'marginTop':'-15px'}) ],style = {'marginTop':'-15px'}), ], className='one-third column', id = 'links', style={'textAlign':'center'}), #title html.Div([", "id='title'), # last update date html.Div([ html.H6('Last Updated: ', style={'marginTop':'-15px'}), html.H6(str(cases['report_date'].iloc[-1].strftime('%B %d, %Y'))", "html.Div([ html.Div([ html.H2('VA x COVID', style={'marginBottom': '10','marginTop':'-15px'}), html.H3('Virginia COVID-19 Dashboard', style={'marginTop':'-15px'}) ], style={'textAlign':'center'})", "\"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}) ],style = {'marginTop':'-15px'}), ], className='one-third", "\"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}), html.H5(\"\"), html.A('County', className=\"nav-item nav-link active", "style={'textAlign':'center'}), #title html.Div([ html.Div([ html.H2('VA x COVID', style={'marginBottom': '10','marginTop':'-15px'}), html.H3('Virginia COVID-19 Dashboard', style={'marginTop':'-15px'})", "# last update date html.Div([ html.H6('Last Updated: ', style={'marginTop':'-15px'}), html.H6(str(cases['report_date'].iloc[-1].strftime('%B %d, %Y')) +", "cases = pd.read_csv('data/cases.csv') cases['report_date']=pd.to_datetime(cases.report_date) top_layout = html.Div([ #links to other pages html.Div([ html.Nav(className", "html.H6(str(cases['report_date'].iloc[-1].strftime('%B %d, %Y')) + ' 13:00 (EST)') ], className='one-third column', id = 'title1',", "column', id = 'title1', style={'textAlign':'center'}) ], id='header',className='row flex-display', style={'margin-bottom': '10px','marginTop':'-15px'}) app.layout = html.Div([", "as np from app import app from app import server from apps import", "className='one-third column', id='title'), # last update date html.Div([ html.H6('Last Updated: ', style={'marginTop':'-15px'}), html.H6(str(cases['report_date'].iloc[-1].strftime('%B", "style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}), html.H5(\"\"), html.A('County', className=\"nav-item", "pd.read_csv('data/cases.csv') cases['report_date']=pd.to_datetime(cases.report_date) top_layout = html.Div([ #links to other pages html.Div([ html.Nav(className = \"nav", "as go import plotly.express as px import pandas as pd import numpy as", "2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}), html.H5(\"\"), html.A('County', className=\"nav-item nav-link active btn\", href='/apps/county', style={\"font-size\":", "], className='one-third column', id='title'), # last update date html.Div([ html.H6('Last Updated: ', style={'marginTop':'-15px'}),", "className='one-third column', id = 'title1', style={'textAlign':'center'}) ], id='header',className='row flex-display', style={'margin-bottom': '10px','marginTop':'-15px'}) app.layout =", "href='/apps/county', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}) ],style =", "import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output", "active btn\", href='/apps/county', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'})", "\"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}), html.H5(\"\"), html.A('County', className=\"nav-item nav-link active btn\",", "{'marginTop':'-15px'}), ], className='one-third column', id = 'links', style={'textAlign':'center'}), #title html.Div([ html.Div([ html.H2('VA x", "'/apps/state': return state.layout if pathname == '/apps/county': return county.layout else: return state.layout if", "top_layout, html.Div(id='page-content',children=[]) ], id='mainContainer', style={'display': 'flex','flex-direction':'column'}) @app.callback(Output('page-content', 'children'), [Input('url','pathname')]) def display_page(pathname): if pathname", "import Input, Output import plotly.graph_objs as go import plotly.express as px import pandas", "update date html.Div([ html.H6('Last Updated: ', style={'marginTop':'-15px'}), html.H6(str(cases['report_date'].iloc[-1].strftime('%B %d, %Y')) + ' 13:00", "\"5px\", 'marginTop':'-15px'}) ],style = {'marginTop':'-15px'}), ], className='one-third column', id = 'links', style={'textAlign':'center'}), #title", "dcc.Location(id='url',refresh=False), top_layout, html.Div(id='page-content',children=[]) ], id='mainContainer', style={'display': 'flex','flex-direction':'column'}) @app.callback(Output('page-content', 'children'), [Input('url','pathname')]) def display_page(pathname): if", "children=[ html.A('State', className=\"nav-item nav-link btn\", href='/apps/state', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\",", "nav-link btn\", href='/apps/state', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}),", "Output import plotly.graph_objs as go import plotly.express as px import pandas as pd", "\"nav nav-pills\", children=[ html.A('State', className=\"nav-item nav-link btn\", href='/apps/state', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px", "== '/apps/state': return state.layout if pathname == '/apps/county': return county.layout else: return state.layout", "\"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}), html.H5(\"\"), html.A('County', className=\"nav-item nav-link", "= {'marginTop':'-15px'}), ], className='one-third column', id = 'links', style={'textAlign':'center'}), #title html.Div([ html.Div([ html.H2('VA", "= pd.read_csv('data/cases.csv') cases['report_date']=pd.to_datetime(cases.report_date) top_layout = html.Div([ #links to other pages html.Div([ html.Nav(className =", "app from app import server from apps import state, county cases = pd.read_csv('data/cases.csv')", "style={'marginTop':'-15px'}), html.H6(str(cases['report_date'].iloc[-1].strftime('%B %d, %Y')) + ' 13:00 (EST)') ], className='one-third column', id =", "13:00 (EST)') ], className='one-third column', id = 'title1', style={'textAlign':'center'}) ], id='header',className='row flex-display', style={'margin-bottom':", "style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}) ],style = {'marginTop':'-15px'}),", "if pathname == '/apps/state': return state.layout if pathname == '/apps/county': return county.layout else:", "as px import pandas as pd import numpy as np from app import", "#title html.Div([ html.Div([ html.H2('VA x COVID', style={'marginBottom': '10','marginTop':'-15px'}), html.H3('Virginia COVID-19 Dashboard', style={'marginTop':'-15px'}) ],", "dash_core_components as dcc from dash.dependencies import Input, Output import plotly.graph_objs as go import", "\"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}) ],style = {'marginTop':'-15px'}), ], className='one-third column',", "html.Div([ html.H2('VA x COVID', style={'marginBottom': '10','marginTop':'-15px'}), html.H3('Virginia COVID-19 Dashboard', style={'marginTop':'-15px'}) ], style={'textAlign':'center'}) ],", "Updated: ', style={'marginTop':'-15px'}), html.H6(str(cases['report_date'].iloc[-1].strftime('%B %d, %Y')) + ' 13:00 (EST)') ], className='one-third column',", "html import dash_core_components as dcc from dash.dependencies import Input, Output import plotly.graph_objs as", "pandas as pd import numpy as np from app import app from app", "], className='one-third column', id = 'links', style={'textAlign':'center'}), #title html.Div([ html.Div([ html.H2('VA x COVID',", "Dashboard', style={'marginTop':'-15px'}) ], style={'textAlign':'center'}) ], className='one-third column', id='title'), # last update date html.Div([", "'children'), [Input('url','pathname')]) def display_page(pathname): if pathname == '/apps/state': return state.layout if pathname ==", "[Input('url','pathname')]) def display_page(pathname): if pathname == '/apps/state': return state.layout if pathname == '/apps/county':", "state, county cases = pd.read_csv('data/cases.csv') cases['report_date']=pd.to_datetime(cases.report_date) top_layout = html.Div([ #links to other pages", "= html.Div([ #links to other pages html.Div([ html.Nav(className = \"nav nav-pills\", children=[ html.A('State',", "html.H2('VA x COVID', style={'marginBottom': '10','marginTop':'-15px'}), html.H3('Virginia COVID-19 Dashboard', style={'marginTop':'-15px'}) ], style={'textAlign':'center'}) ], className='one-third", "style={'marginBottom': '10','marginTop':'-15px'}), html.H3('Virginia COVID-19 Dashboard', style={'marginTop':'-15px'}) ], style={'textAlign':'center'}) ], className='one-third column', id='title'), #", "html.Div([ html.H6('Last Updated: ', style={'marginTop':'-15px'}), html.H6(str(cases['report_date'].iloc[-1].strftime('%B %d, %Y')) + ' 13:00 (EST)') ],", "last update date html.Div([ html.H6('Last Updated: ', style={'marginTop':'-15px'}), html.H6(str(cases['report_date'].iloc[-1].strftime('%B %d, %Y')) + '", "go import plotly.express as px import pandas as pd import numpy as np", "state.layout if pathname == '/apps/county': return county.layout else: return state.layout if __name__ ==", "html.Div([ html.Nav(className = \"nav nav-pills\", children=[ html.A('State', className=\"nav-item nav-link btn\", href='/apps/state', style={\"font-size\": \"2rem\",", "np from app import app from app import server from apps import state,", "date html.Div([ html.H6('Last Updated: ', style={'marginTop':'-15px'}), html.H6(str(cases['report_date'].iloc[-1].strftime('%B %d, %Y')) + ' 13:00 (EST)')", "top_layout = html.Div([ #links to other pages html.Div([ html.Nav(className = \"nav nav-pills\", children=[", "import dash import dash_html_components as html import dash_core_components as dcc from dash.dependencies import", "from dash.dependencies import Input, Output import plotly.graph_objs as go import plotly.express as px", "import numpy as np from app import app from app import server from", "\"padding\": \"5px\", 'marginTop':'-15px'}) ],style = {'marginTop':'-15px'}), ], className='one-third column', id = 'links', style={'textAlign':'center'}),", "style={'margin-bottom': '10px','marginTop':'-15px'}) app.layout = html.Div([ dcc.Location(id='url',refresh=False), top_layout, html.Div(id='page-content',children=[]) ], id='mainContainer', style={'display': 'flex','flex-direction':'column'}) @app.callback(Output('page-content',", "pathname == '/apps/county': return county.layout else: return state.layout if __name__ == '__main__': app.run_server(debug=True)", "btn\", href='/apps/state', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}), html.H5(\"\"),", "plotly.graph_objs as go import plotly.express as px import pandas as pd import numpy", "from app import server from apps import state, county cases = pd.read_csv('data/cases.csv') cases['report_date']=pd.to_datetime(cases.report_date)", "], id='mainContainer', style={'display': 'flex','flex-direction':'column'}) @app.callback(Output('page-content', 'children'), [Input('url','pathname')]) def display_page(pathname): if pathname == '/apps/state':", "#e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}), html.H5(\"\"), html.A('County', className=\"nav-item nav-link active btn\", href='/apps/county', style={\"font-size\": \"2rem\",", "html.Div([ dcc.Location(id='url',refresh=False), top_layout, html.Div(id='page-content',children=[]) ], id='mainContainer', style={'display': 'flex','flex-direction':'column'}) @app.callback(Output('page-content', 'children'), [Input('url','pathname')]) def display_page(pathname):", "nav-pills\", children=[ html.A('State', className=\"nav-item nav-link btn\", href='/apps/state', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px", "dcc from dash.dependencies import Input, Output import plotly.graph_objs as go import plotly.express as", "href='/apps/state', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}), html.H5(\"\"), html.A('County',", "import plotly.express as px import pandas as pd import numpy as np from", "], style={'textAlign':'center'}) ], className='one-third column', id='title'), # last update date html.Div([ html.H6('Last Updated:", "id = 'title1', style={'textAlign':'center'}) ], id='header',className='row flex-display', style={'margin-bottom': '10px','marginTop':'-15px'}) app.layout = html.Div([ dcc.Location(id='url',refresh=False),", "id='mainContainer', style={'display': 'flex','flex-direction':'column'}) @app.callback(Output('page-content', 'children'), [Input('url','pathname')]) def display_page(pathname): if pathname == '/apps/state': return", "dash.dependencies import Input, Output import plotly.graph_objs as go import plotly.express as px import", "', style={'marginTop':'-15px'}), html.H6(str(cases['report_date'].iloc[-1].strftime('%B %d, %Y')) + ' 13:00 (EST)') ], className='one-third column', id", "apps import state, county cases = pd.read_csv('data/cases.csv') cases['report_date']=pd.to_datetime(cases.report_date) top_layout = html.Div([ #links to", "= html.Div([ dcc.Location(id='url',refresh=False), top_layout, html.Div(id='page-content',children=[]) ], id='mainContainer', style={'display': 'flex','flex-direction':'column'}) @app.callback(Output('page-content', 'children'), [Input('url','pathname')]) def", "\"padding\": \"5px\", 'marginTop':'-15px'}), html.H5(\"\"), html.A('County', className=\"nav-item nav-link active btn\", href='/apps/county', style={\"font-size\": \"2rem\", \"box-shadow\":", "html.Div(id='page-content',children=[]) ], id='mainContainer', style={'display': 'flex','flex-direction':'column'}) @app.callback(Output('page-content', 'children'), [Input('url','pathname')]) def display_page(pathname): if pathname ==", "as pd import numpy as np from app import app from app import", "className='one-third column', id = 'links', style={'textAlign':'center'}), #title html.Div([ html.Div([ html.H2('VA x COVID', style={'marginBottom':", "= \"nav nav-pills\", children=[ html.A('State', className=\"nav-item nav-link btn\", href='/apps/state', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px", "className=\"nav-item nav-link btn\", href='/apps/state', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\",", "Input, Output import plotly.graph_objs as go import plotly.express as px import pandas as", "from apps import state, county cases = pd.read_csv('data/cases.csv') cases['report_date']=pd.to_datetime(cases.report_date) top_layout = html.Div([ #links", "if pathname == '/apps/county': return county.layout else: return state.layout if __name__ == '__main__':", "county cases = pd.read_csv('data/cases.csv') cases['report_date']=pd.to_datetime(cases.report_date) top_layout = html.Div([ #links to other pages html.Div([", "pd import numpy as np from app import app from app import server", "html.Div([ #links to other pages html.Div([ html.Nav(className = \"nav nav-pills\", children=[ html.A('State', className=\"nav-item", "other pages html.Div([ html.Nav(className = \"nav nav-pills\", children=[ html.A('State', className=\"nav-item nav-link btn\", href='/apps/state',", "html.H6('Last Updated: ', style={'marginTop':'-15px'}), html.H6(str(cases['report_date'].iloc[-1].strftime('%B %d, %Y')) + ' 13:00 (EST)') ], className='one-third", "= 'title1', style={'textAlign':'center'}) ], id='header',className='row flex-display', style={'margin-bottom': '10px','marginTop':'-15px'}) app.layout = html.Div([ dcc.Location(id='url',refresh=False), top_layout,", "html.A('State', className=\"nav-item nav-link btn\", href='/apps/state', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\":", "px import pandas as pd import numpy as np from app import app", "nav-link active btn\", href='/apps/county', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\",", "as dcc from dash.dependencies import Input, Output import plotly.graph_objs as go import plotly.express", "numpy as np from app import app from app import server from apps", "html.Nav(className = \"nav nav-pills\", children=[ html.A('State', className=\"nav-item nav-link btn\", href='/apps/state', style={\"font-size\": \"2rem\", \"box-shadow\":", "btn\", href='/apps/county', style={\"font-size\": \"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}) ],style", "],style = {'marginTop':'-15px'}), ], className='one-third column', id = 'links', style={'textAlign':'center'}), #title html.Div([ html.Div([", "+ ' 13:00 (EST)') ], className='one-third column', id = 'title1', style={'textAlign':'center'}) ], id='header',className='row", "], className='one-third column', id = 'title1', style={'textAlign':'center'}) ], id='header',className='row flex-display', style={'margin-bottom': '10px','marginTop':'-15px'}) app.layout", "\"2rem\", \"box-shadow\": \"4px 4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}) ],style = {'marginTop':'-15px'}), ],", "style={'textAlign':'center'}) ], id='header',className='row flex-display', style={'margin-bottom': '10px','marginTop':'-15px'}) app.layout = html.Div([ dcc.Location(id='url',refresh=False), top_layout, html.Div(id='page-content',children=[]) ],", "4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}) ],style = {'marginTop':'-15px'}), ], className='one-third column', id", "4px 2px #e3e3e3\", \"padding\": \"5px\", 'marginTop':'-15px'}), html.H5(\"\"), html.A('County', className=\"nav-item nav-link active btn\", href='/apps/county',", "return state.layout if pathname == '/apps/county': return county.layout else: return state.layout if __name__", "server from apps import state, county cases = pd.read_csv('data/cases.csv') cases['report_date']=pd.to_datetime(cases.report_date) top_layout = html.Div([", "import app from app import server from apps import state, county cases =", "style={'display': 'flex','flex-direction':'column'}) @app.callback(Output('page-content', 'children'), [Input('url','pathname')]) def display_page(pathname): if pathname == '/apps/state': return state.layout", "plotly.express as px import pandas as pd import numpy as np from app" ]
[ ": [0.5, 0.5, 0.5], \"shading\" : \"Lambert\", \"specularCoef\" : 50, \"transparency\" : 1.0,", "%(faces)s } \"\"\" def tessToJson( vert, face, nvert, nface): '''Specify compatible lists of", "\"uvs\": [[]], \"faces\": %(faces)s } \"\"\" def tessToJson( vert, face, nvert, nface): '''Specify", ": 3, \"generatedBy\" : \"ParametricParts\", \"vertices\" : %(nVertices)d, \"faces\" : %(nFaces)d, \"normals\" :", "\"morphTargets\": [], \"normals\": [], \"colors\": [], \"uvs\": [[]], \"faces\": %(faces)s } \"\"\" def", "\"colorAmbient\" : [0.0, 0.0, 0.0], \"colorDiffuse\" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746], \"colorSpecular\" : [0.5,", "1.0, \"materials\": [ { \"DbgColor\" : 15658734, \"DbgIndex\" : 0, \"DbgName\" : \"Material\",", "object notation # https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3 # JSON_TEMPLATE= \"\"\"\\ { \"metadata\" : { \"formatVersion\" :", "\"Material\", \"colorAmbient\" : [0.0, 0.0, 0.0], \"colorDiffuse\" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746], \"colorSpecular\" :", "0.126246120426746], \"colorSpecular\" : [0.5, 0.5, 0.5], \"shading\" : \"Lambert\", \"specularCoef\" : 50, \"transparency\"", "three.js JSON object notation # https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3 # JSON_TEMPLATE= \"\"\"\\ { \"metadata\" : {", "tessToJson( vert, face, nvert, nface): '''Specify compatible lists of vertices and faces, and", "\"vertexColors\" : false }], \"vertices\": %(vertices)s, \"morphTargets\": [], \"normals\": [], \"colors\": [], \"uvs\":", "0 }, \"scale\" : 1.0, \"materials\": [ { \"DbgColor\" : 15658734, \"DbgIndex\" :", "\"materials\": [ { \"DbgColor\" : 15658734, \"DbgIndex\" : 0, \"DbgName\" : \"Material\", \"colorAmbient\"", "3, \"generatedBy\" : \"ParametricParts\", \"vertices\" : %(nVertices)d, \"faces\" : %(nFaces)d, \"normals\" : 0,", "\"vertices\" : %(nVertices)d, \"faces\" : %(nFaces)d, \"normals\" : 0, \"colors\" : 0, \"uvs\"", "of vertices and faces, and get a three.js JSON object back. Note: list", "face indices must be compatible, i.e. lead with 0 for each row of", "[0.0, 0.0, 0.0], \"colorDiffuse\" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746], \"colorSpecular\" : [0.5, 0.5, 0.5],", ": %(nVertices)d, \"faces\" : %(nFaces)d, \"normals\" : 0, \"colors\" : 0, \"uvs\" :", "nface): '''Specify compatible lists of vertices and faces, and get a three.js JSON", "{ 'vertices' : str(vert), 'faces' : str(face), 'nVertices': nvert, 'nFaces' : nface };", "https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3 # JSON_TEMPLATE= \"\"\"\\ { \"metadata\" : { \"formatVersion\" : 3, \"generatedBy\" :", "to create a triangle. Spec: https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3''' return JSON_TEMPLATE % { 'vertices' : str(vert),", "# JSON_TEMPLATE= \"\"\"\\ { \"metadata\" : { \"formatVersion\" : 3, \"generatedBy\" : \"ParametricParts\",", "JSON_TEMPLATE= \"\"\"\\ { \"metadata\" : { \"formatVersion\" : 3, \"generatedBy\" : \"ParametricParts\", \"vertices\"", "3 indices to create a triangle. Spec: https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3''' return JSON_TEMPLATE % { 'vertices'", "\"\"\" def tessToJson( vert, face, nvert, nface): '''Specify compatible lists of vertices and", ": 0, \"uvs\" : 0, \"materials\" : 1, \"morphTargets\" : 0 }, \"scale\"", "each row of 3 indices to create a triangle. Spec: https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3''' return JSON_TEMPLATE", "0 for each row of 3 indices to create a triangle. Spec: https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3'''", "lists of vertices and faces, and get a three.js JSON object back. Note:", "and get a three.js JSON object back. Note: list of face indices must", "be compatible, i.e. lead with 0 for each row of 3 indices to", "1, \"morphTargets\" : 0 }, \"scale\" : 1.0, \"materials\": [ { \"DbgColor\" :", ": \"ParametricParts\", \"vertices\" : %(nVertices)d, \"faces\" : %(nFaces)d, \"normals\" : 0, \"colors\" :", "} \"\"\" def tessToJson( vert, face, nvert, nface): '''Specify compatible lists of vertices", "\"colors\": [], \"uvs\": [[]], \"faces\": %(faces)s } \"\"\" def tessToJson( vert, face, nvert,", "nvert, nface): '''Specify compatible lists of vertices and faces, and get a three.js", "\"DbgColor\" : 15658734, \"DbgIndex\" : 0, \"DbgName\" : \"Material\", \"colorAmbient\" : [0.0, 0.0,", "lead with 0 for each row of 3 indices to create a triangle.", ": [0.6400000190734865, 0.10179081114814892, 0.126246120426746], \"colorSpecular\" : [0.5, 0.5, 0.5], \"shading\" : \"Lambert\", \"specularCoef\"", ": 0, \"colors\" : 0, \"uvs\" : 0, \"materials\" : 1, \"morphTargets\" :", "compatible lists of vertices and faces, and get a three.js JSON object back.", "faces, and get a three.js JSON object back. Note: list of face indices", "\"faces\": %(faces)s } \"\"\" def tessToJson( vert, face, nvert, nface): '''Specify compatible lists", "of 3 indices to create a triangle. Spec: https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3''' return JSON_TEMPLATE % {", "15658734, \"DbgIndex\" : 0, \"DbgName\" : \"Material\", \"colorAmbient\" : [0.0, 0.0, 0.0], \"colorDiffuse\"", "Objects that represent # three.js JSON object notation # https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3 # JSON_TEMPLATE= \"\"\"\\", ": 0 }, \"scale\" : 1.0, \"materials\": [ { \"DbgColor\" : 15658734, \"DbgIndex\"", "and faces, and get a three.js JSON object back. Note: list of face", "JSON_TEMPLATE % { 'vertices' : str(vert), 'faces' : str(face), 'nVertices': nvert, 'nFaces' :", "false }], \"vertices\": %(vertices)s, \"morphTargets\": [], \"normals\": [], \"colors\": [], \"uvs\": [[]], \"faces\":", "\"specularCoef\" : 50, \"transparency\" : 1.0, \"vertexColors\" : false }], \"vertices\": %(vertices)s, \"morphTargets\":", "[0.6400000190734865, 0.10179081114814892, 0.126246120426746], \"colorSpecular\" : [0.5, 0.5, 0.5], \"shading\" : \"Lambert\", \"specularCoef\" :", "for each row of 3 indices to create a triangle. Spec: https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3''' return", "face, nvert, nface): '''Specify compatible lists of vertices and faces, and get a", "{ \"DbgColor\" : 15658734, \"DbgIndex\" : 0, \"DbgName\" : \"Material\", \"colorAmbient\" : [0.0,", "a three.js JSON object back. Note: list of face indices must be compatible,", "\"normals\": [], \"colors\": [], \"uvs\": [[]], \"faces\": %(faces)s } \"\"\" def tessToJson( vert,", "\"colors\" : 0, \"uvs\" : 0, \"materials\" : 1, \"morphTargets\" : 0 },", "\"scale\" : 1.0, \"materials\": [ { \"DbgColor\" : 15658734, \"DbgIndex\" : 0, \"DbgName\"", "get a three.js JSON object back. Note: list of face indices must be", "a triangle. Spec: https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3''' return JSON_TEMPLATE % { 'vertices' : str(vert), 'faces' :", "0.5], \"shading\" : \"Lambert\", \"specularCoef\" : 50, \"transparency\" : 1.0, \"vertexColors\" : false", "return JSON_TEMPLATE % { 'vertices' : str(vert), 'faces' : str(face), 'nVertices': nvert, 'nFaces'", "0.10179081114814892, 0.126246120426746], \"colorSpecular\" : [0.5, 0.5, 0.5], \"shading\" : \"Lambert\", \"specularCoef\" : 50,", "three.js JSON object back. Note: list of face indices must be compatible, i.e.", "JSON object notation # https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3 # JSON_TEMPLATE= \"\"\"\\ { \"metadata\" : { \"formatVersion\"", "of face indices must be compatible, i.e. lead with 0 for each row", "\"normals\" : 0, \"colors\" : 0, \"uvs\" : 0, \"materials\" : 1, \"morphTargets\"", "0.0, 0.0], \"colorDiffuse\" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746], \"colorSpecular\" : [0.5, 0.5, 0.5], \"shading\"", ": 50, \"transparency\" : 1.0, \"vertexColors\" : false }], \"vertices\": %(vertices)s, \"morphTargets\": [],", "compatible, i.e. lead with 0 for each row of 3 indices to create", "vert, face, nvert, nface): '''Specify compatible lists of vertices and faces, and get", "row of 3 indices to create a triangle. Spec: https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3''' return JSON_TEMPLATE %", "Spec: https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3''' return JSON_TEMPLATE % { 'vertices' : str(vert), 'faces' : str(face), 'nVertices':", "triangle. Spec: https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3''' return JSON_TEMPLATE % { 'vertices' : str(vert), 'faces' : str(face),", "https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3''' return JSON_TEMPLATE % { 'vertices' : str(vert), 'faces' : str(face), 'nVertices': nvert,", "list of face indices must be compatible, i.e. lead with 0 for each", "%(vertices)s, \"morphTargets\": [], \"normals\": [], \"colors\": [], \"uvs\": [[]], \"faces\": %(faces)s } \"\"\"", "# three.js JSON object notation # https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3 # JSON_TEMPLATE= \"\"\"\\ { \"metadata\" :", "Note: list of face indices must be compatible, i.e. lead with 0 for", ": 15658734, \"DbgIndex\" : 0, \"DbgName\" : \"Material\", \"colorAmbient\" : [0.0, 0.0, 0.0],", "back. Note: list of face indices must be compatible, i.e. lead with 0", "[], \"colors\": [], \"uvs\": [[]], \"faces\": %(faces)s } \"\"\" def tessToJson( vert, face,", "# https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3 # JSON_TEMPLATE= \"\"\"\\ { \"metadata\" : { \"formatVersion\" : 3, \"generatedBy\"", "0.0], \"colorDiffuse\" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746], \"colorSpecular\" : [0.5, 0.5, 0.5], \"shading\" :", "}], \"vertices\": %(vertices)s, \"morphTargets\": [], \"normals\": [], \"colors\": [], \"uvs\": [[]], \"faces\": %(faces)s", "{ \"metadata\" : { \"formatVersion\" : 3, \"generatedBy\" : \"ParametricParts\", \"vertices\" : %(nVertices)d,", "\"colorSpecular\" : [0.5, 0.5, 0.5], \"shading\" : \"Lambert\", \"specularCoef\" : 50, \"transparency\" :", ": 0, \"materials\" : 1, \"morphTargets\" : 0 }, \"scale\" : 1.0, \"materials\":", ": { \"formatVersion\" : 3, \"generatedBy\" : \"ParametricParts\", \"vertices\" : %(nVertices)d, \"faces\" :", "\"shading\" : \"Lambert\", \"specularCoef\" : 50, \"transparency\" : 1.0, \"vertexColors\" : false }],", "\"uvs\" : 0, \"materials\" : 1, \"morphTargets\" : 0 }, \"scale\" : 1.0,", ": 1.0, \"materials\": [ { \"DbgColor\" : 15658734, \"DbgIndex\" : 0, \"DbgName\" :", "0, \"DbgName\" : \"Material\", \"colorAmbient\" : [0.0, 0.0, 0.0], \"colorDiffuse\" : [0.6400000190734865, 0.10179081114814892,", ": \"Material\", \"colorAmbient\" : [0.0, 0.0, 0.0], \"colorDiffuse\" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746], \"colorSpecular\"", "\"transparency\" : 1.0, \"vertexColors\" : false }], \"vertices\": %(vertices)s, \"morphTargets\": [], \"normals\": [],", "\"DbgName\" : \"Material\", \"colorAmbient\" : [0.0, 0.0, 0.0], \"colorDiffuse\" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746],", ": [0.0, 0.0, 0.0], \"colorDiffuse\" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746], \"colorSpecular\" : [0.5, 0.5,", "}, \"scale\" : 1.0, \"materials\": [ { \"DbgColor\" : 15658734, \"DbgIndex\" : 0,", "1.0, \"vertexColors\" : false }], \"vertices\": %(vertices)s, \"morphTargets\": [], \"normals\": [], \"colors\": [],", "with 0 for each row of 3 indices to create a triangle. Spec:", ": 1.0, \"vertexColors\" : false }], \"vertices\": %(vertices)s, \"morphTargets\": [], \"normals\": [], \"colors\":", "Adapted from https://github.com/dcowden/cadquery/blob/master/cadquery/freecad_impl/exporters.py # Objects that represent # three.js JSON object notation #", "that represent # three.js JSON object notation # https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3 # JSON_TEMPLATE= \"\"\"\\ {", "[ { \"DbgColor\" : 15658734, \"DbgIndex\" : 0, \"DbgName\" : \"Material\", \"colorAmbient\" :", "i.e. lead with 0 for each row of 3 indices to create a", "\"generatedBy\" : \"ParametricParts\", \"vertices\" : %(nVertices)d, \"faces\" : %(nFaces)d, \"normals\" : 0, \"colors\"", "50, \"transparency\" : 1.0, \"vertexColors\" : false }], \"vertices\": %(vertices)s, \"morphTargets\": [], \"normals\":", "0, \"materials\" : 1, \"morphTargets\" : 0 }, \"scale\" : 1.0, \"materials\": [", "vertices and faces, and get a three.js JSON object back. Note: list of", "0.5, 0.5], \"shading\" : \"Lambert\", \"specularCoef\" : 50, \"transparency\" : 1.0, \"vertexColors\" :", "\"ParametricParts\", \"vertices\" : %(nVertices)d, \"faces\" : %(nFaces)d, \"normals\" : 0, \"colors\" : 0,", "# Adapted from https://github.com/dcowden/cadquery/blob/master/cadquery/freecad_impl/exporters.py # Objects that represent # three.js JSON object notation", "\"\"\"\\ { \"metadata\" : { \"formatVersion\" : 3, \"generatedBy\" : \"ParametricParts\", \"vertices\" :", "0, \"uvs\" : 0, \"materials\" : 1, \"morphTargets\" : 0 }, \"scale\" :", ": %(nFaces)d, \"normals\" : 0, \"colors\" : 0, \"uvs\" : 0, \"materials\" :", "must be compatible, i.e. lead with 0 for each row of 3 indices", "notation # https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3 # JSON_TEMPLATE= \"\"\"\\ { \"metadata\" : { \"formatVersion\" : 3,", "%(nFaces)d, \"normals\" : 0, \"colors\" : 0, \"uvs\" : 0, \"materials\" : 1,", "[], \"normals\": [], \"colors\": [], \"uvs\": [[]], \"faces\": %(faces)s } \"\"\" def tessToJson(", ": false }], \"vertices\": %(vertices)s, \"morphTargets\": [], \"normals\": [], \"colors\": [], \"uvs\": [[]],", "represent # three.js JSON object notation # https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3 # JSON_TEMPLATE= \"\"\"\\ { \"metadata\"", "object back. Note: list of face indices must be compatible, i.e. lead with", "\"materials\" : 1, \"morphTargets\" : 0 }, \"scale\" : 1.0, \"materials\": [ {", "0, \"colors\" : 0, \"uvs\" : 0, \"materials\" : 1, \"morphTargets\" : 0", "indices to create a triangle. Spec: https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3''' return JSON_TEMPLATE % { 'vertices' :", "\"metadata\" : { \"formatVersion\" : 3, \"generatedBy\" : \"ParametricParts\", \"vertices\" : %(nVertices)d, \"faces\"", "indices must be compatible, i.e. lead with 0 for each row of 3", ": \"Lambert\", \"specularCoef\" : 50, \"transparency\" : 1.0, \"vertexColors\" : false }], \"vertices\":", "def tessToJson( vert, face, nvert, nface): '''Specify compatible lists of vertices and faces,", "from https://github.com/dcowden/cadquery/blob/master/cadquery/freecad_impl/exporters.py # Objects that represent # three.js JSON object notation # https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3", ": 1, \"morphTargets\" : 0 }, \"scale\" : 1.0, \"materials\": [ { \"DbgColor\"", "\"vertices\": %(vertices)s, \"morphTargets\": [], \"normals\": [], \"colors\": [], \"uvs\": [[]], \"faces\": %(faces)s }", "create a triangle. Spec: https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3''' return JSON_TEMPLATE % { 'vertices' : str(vert), 'faces'", "\"formatVersion\" : 3, \"generatedBy\" : \"ParametricParts\", \"vertices\" : %(nVertices)d, \"faces\" : %(nFaces)d, \"normals\"", "# Objects that represent # three.js JSON object notation # https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3 # JSON_TEMPLATE=", "[], \"uvs\": [[]], \"faces\": %(faces)s } \"\"\" def tessToJson( vert, face, nvert, nface):", "'''Specify compatible lists of vertices and faces, and get a three.js JSON object", "https://github.com/dcowden/cadquery/blob/master/cadquery/freecad_impl/exporters.py # Objects that represent # three.js JSON object notation # https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3 #", "# # Adapted from https://github.com/dcowden/cadquery/blob/master/cadquery/freecad_impl/exporters.py # Objects that represent # three.js JSON object", "\"colorDiffuse\" : [0.6400000190734865, 0.10179081114814892, 0.126246120426746], \"colorSpecular\" : [0.5, 0.5, 0.5], \"shading\" : \"Lambert\",", "\"Lambert\", \"specularCoef\" : 50, \"transparency\" : 1.0, \"vertexColors\" : false }], \"vertices\": %(vertices)s,", "% { 'vertices' : str(vert), 'faces' : str(face), 'nVertices': nvert, 'nFaces' : nface", "[[]], \"faces\": %(faces)s } \"\"\" def tessToJson( vert, face, nvert, nface): '''Specify compatible", "{ \"formatVersion\" : 3, \"generatedBy\" : \"ParametricParts\", \"vertices\" : %(nVertices)d, \"faces\" : %(nFaces)d,", "\"faces\" : %(nFaces)d, \"normals\" : 0, \"colors\" : 0, \"uvs\" : 0, \"materials\"", "JSON object back. Note: list of face indices must be compatible, i.e. lead", "%(nVertices)d, \"faces\" : %(nFaces)d, \"normals\" : 0, \"colors\" : 0, \"uvs\" : 0,", "\"DbgIndex\" : 0, \"DbgName\" : \"Material\", \"colorAmbient\" : [0.0, 0.0, 0.0], \"colorDiffuse\" :", ": 0, \"DbgName\" : \"Material\", \"colorAmbient\" : [0.0, 0.0, 0.0], \"colorDiffuse\" : [0.6400000190734865,", "\"morphTargets\" : 0 }, \"scale\" : 1.0, \"materials\": [ { \"DbgColor\" : 15658734,", "[0.5, 0.5, 0.5], \"shading\" : \"Lambert\", \"specularCoef\" : 50, \"transparency\" : 1.0, \"vertexColors\"" ]
[ "can be useful for distribution or for easy writing of code and bundle", "needed to build multiple files into a single script. It can be useful", "multiple files into a single script. It can be useful for distribution or", "of code and bundle it (for example for www.codingame.com) \"\"\" import re from", "for easy writing of code and bundle it (for example for www.codingame.com) \"\"\"", "= re.split('\\n{2}', __doc__) setup( name='pyndler', version='1.0.0', description=description, long_description=long_description, author='<NAME>', author_email='<EMAIL>', url='http://github.com/dimastark/pyndler', tests_require=['pytest'], scripts=[\"scripts/pyndler\"],", "a single script. It can be useful for distribution or for easy writing", "script A utility needed to build multiple files into a single script. It", "code and bundle it (for example for www.codingame.com) \"\"\" import re from distutils.core", "__doc__) setup( name='pyndler', version='1.0.0', description=description, long_description=long_description, author='<NAME>', author_email='<EMAIL>', url='http://github.com/dimastark/pyndler', tests_require=['pytest'], scripts=[\"scripts/pyndler\"], packages=['pyndler'], )", "python \"\"\" Bundle Python packages into a single script A utility needed to", "bundle it (for example for www.codingame.com) \"\"\" import re from distutils.core import setup", "It can be useful for distribution or for easy writing of code and", "useful for distribution or for easy writing of code and bundle it (for", "long_description = re.split('\\n{2}', __doc__) setup( name='pyndler', version='1.0.0', description=description, long_description=long_description, author='<NAME>', author_email='<EMAIL>', url='http://github.com/dimastark/pyndler', tests_require=['pytest'],", "for distribution or for easy writing of code and bundle it (for example", "distribution or for easy writing of code and bundle it (for example for", "(for example for www.codingame.com) \"\"\" import re from distutils.core import setup description, long_description", "and bundle it (for example for www.codingame.com) \"\"\" import re from distutils.core import", "Python packages into a single script A utility needed to build multiple files", "Bundle Python packages into a single script A utility needed to build multiple", "single script A utility needed to build multiple files into a single script.", "single script. It can be useful for distribution or for easy writing of", "setup description, long_description = re.split('\\n{2}', __doc__) setup( name='pyndler', version='1.0.0', description=description, long_description=long_description, author='<NAME>', author_email='<EMAIL>',", "\"\"\" Bundle Python packages into a single script A utility needed to build", "example for www.codingame.com) \"\"\" import re from distutils.core import setup description, long_description =", "www.codingame.com) \"\"\" import re from distutils.core import setup description, long_description = re.split('\\n{2}', __doc__)", "A utility needed to build multiple files into a single script. It can", "description, long_description = re.split('\\n{2}', __doc__) setup( name='pyndler', version='1.0.0', description=description, long_description=long_description, author='<NAME>', author_email='<EMAIL>', url='http://github.com/dimastark/pyndler',", "build multiple files into a single script. It can be useful for distribution", "script. It can be useful for distribution or for easy writing of code", "distutils.core import setup description, long_description = re.split('\\n{2}', __doc__) setup( name='pyndler', version='1.0.0', description=description, long_description=long_description,", "re.split('\\n{2}', __doc__) setup( name='pyndler', version='1.0.0', description=description, long_description=long_description, author='<NAME>', author_email='<EMAIL>', url='http://github.com/dimastark/pyndler', tests_require=['pytest'], scripts=[\"scripts/pyndler\"], packages=['pyndler'],", "utility needed to build multiple files into a single script. It can be", "from distutils.core import setup description, long_description = re.split('\\n{2}', __doc__) setup( name='pyndler', version='1.0.0', description=description,", "into a single script A utility needed to build multiple files into a", "writing of code and bundle it (for example for www.codingame.com) \"\"\" import re", "it (for example for www.codingame.com) \"\"\" import re from distutils.core import setup description,", "#!/usr/bin/env python \"\"\" Bundle Python packages into a single script A utility needed", "easy writing of code and bundle it (for example for www.codingame.com) \"\"\" import", "to build multiple files into a single script. It can be useful for", "be useful for distribution or for easy writing of code and bundle it", "or for easy writing of code and bundle it (for example for www.codingame.com)", "\"\"\" import re from distutils.core import setup description, long_description = re.split('\\n{2}', __doc__) setup(", "packages into a single script A utility needed to build multiple files into", "into a single script. It can be useful for distribution or for easy", "import re from distutils.core import setup description, long_description = re.split('\\n{2}', __doc__) setup( name='pyndler',", "re from distutils.core import setup description, long_description = re.split('\\n{2}', __doc__) setup( name='pyndler', version='1.0.0',", "a single script A utility needed to build multiple files into a single", "import setup description, long_description = re.split('\\n{2}', __doc__) setup( name='pyndler', version='1.0.0', description=description, long_description=long_description, author='<NAME>',", "files into a single script. It can be useful for distribution or for", "for www.codingame.com) \"\"\" import re from distutils.core import setup description, long_description = re.split('\\n{2}'," ]
[ "return response def country_choice_view(self, request, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta", "None context = { **self.admin_site.each_context(request), \"current_url\": current_url, \"title\": \"%s (%s)\" % (_.countries, obj)", "\"title\": \"%s (%s)\" % (_.countries, obj) if obj else _.countries, \"object_name\": str(opts.verbose_name), \"object\":", "or \"admin/company_country_search.html\", } from company.views import SearchByCountry return SearchByCountry.as_view(**defaults)(request=request) @never_cache def country_add_view(self, request,", "\"object\": obj, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } request.current_app = self.admin_site.name defaults", "django.conf import settings from django.views.decorators.cache import never_cache from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.utils", "AddressAdminInline from company import models, fields, translates as _ from company.apps import CompanyConfig", "_.search, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } defaults = { \"extra_context\": context,", "opts, \"app_label\": opts.app_label, \"media\": self.media } defaults = { \"extra_context\": context, \"country\": country,", "translates as _ from company.apps import CompanyConfig as conf class CompanyAdmin(BaseAdmin): fieldsets =", "('named_id',)) def render_change_form(self, request, context, add=False, change=False, form_url=\"\", obj=None): response = super().render_change_form(request, context,", "hasattr(self.model, \"changelog_model\"): response.template_name = self.change_form_logs_template return response def country_choice_view(self, request, object_id=None, extra_context=None): current_url", "from django.views.decorators.cache import never_cache from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.utils import unquote from", "{ **self.admin_site.each_context(request), \"parent_object\": parent_object, \"app_path\": request.get_full_path(), \"username\": request.user.get_username(), \"current_url\": current_url, \"country\": country, \"title\":", "CompanyFRAdminInline(admin.StackedInline): fields = fields.country + fields.fr extra = 0 max_num = 0 class", "def country_choice_view(self, request, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field =", "\"company_fr__siret\") change_list_template = \"admin/company_change_list.html\" change_form_template = \"admin/company_change_form.html\" change_form_logs_template = \"admin/company_change_form_logs.html\" readonly_fields = ('siege_fr',)", "def country_add_view(self, request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field", "import AddressAdminInline from company import models, fields, translates as _ from company.apps import", "purpose', {\"classes\": (\"wide\",), \"fields\": ('purpose', 'instance_comex', 'matrix_skills')}), ('market', {\"classes\": (\"wide\",), \"fields\": ( 'capital_socnomtotal',", "\"extra_context\": context, \"country\": country, \"parent_object\": parent_object if parent_object else None, \"success_url\": current_url, \"template_name\":", "path(\"add/\", self.country_add_view, name=\"%s_%s_country_add\" % info), ])) ])), path(\"<path:object_id>/choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice_extend\" %", "'share_kind')}), ('comex & purpose', {\"classes\": (\"wide\",), \"fields\": ('purpose', 'instance_comex', 'matrix_skills')}), ('market', {\"classes\": (\"wide\",),", "\"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } defaults = { \"extra_context\": context, \"admin\":", "= ( (None, {\"classes\": (\"wide\",), \"fields\": ('denomination', 'is_type', 'since', 'site', 'effective', 'secretary', 'resume',", "my_urls + urls ##################### # FR ##################### class CompanyFRAdminInline(admin.StackedInline): fields = fields.country +", "else _.countries, \"object_name\": str(opts.verbose_name), \"object\": obj, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media }", "\"admin/company_change_form_logs.html\" readonly_fields = ('siege_fr',) search_template = None def __init__(self, model, admin_site): super().__init__(model, admin_site)", "search_template = None def __init__(self, model, admin_site): super().__init__(model, admin_site) if conf.named_id: self.readonly_fields +=", "mighty.admin.models import BaseAdmin from mighty.applications.address import fields as address_fields from mighty.applications.address.admin import AddressAdminInline", "name=\"%s_%s_country_add_extend\" % info), ])) ])) ] return my_urls + urls ##################### # FR", "0 class CompanyAddressFRAdminInline(AddressAdminInline): fields = address_fields + ('is_siege', 'is_active') class BaloAdmin(BaseAdmin): fieldsets =", "= { **self.admin_site.each_context(request), \"current_url\": current_url, \"title\": \"%s (%s)\" % (_.countries, obj) if obj", "( (None, {\"classes\": (\"wide\",), \"fields\": ('denomination', 'is_type', 'since', 'site', 'effective', 'secretary', 'resume', 'share_kind')}),", "\"country\": country, \"parent_object\": parent_object if parent_object else None, \"success_url\": current_url, \"template_name\": self.search_template or", "self.model._meta.app_label, self.model._meta.model_name my_urls = [ path(\"choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice\" % info), path(\"<str:country>/search/\",", "(\"wide\",), \"fields\": ( 'siege_fr', )})) list_display = ('denomination', 'since', 'siege_fr') search_fields = (\"denomination\",", "self.readonly_fields += ('named_id',) self.add_field('Informations', ('named_id',)) def render_change_form(self, request, context, add=False, change=False, form_url=\"\", obj=None):", "'dowjones', 'nasdaq', 'gaia' )}), ('rules', {\"classes\": (\"wide\",), \"fields\": ( 'duration_mandate', 'settle_internal', 'age_limit_pdg', 'age_limit_dg',", "'since', 'site', 'effective', 'secretary', 'resume', 'share_kind')}), ('comex & purpose', {\"classes\": (\"wide\",), \"fields\": ('purpose',", "extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) parent_object =", "{ \"extra_context\": context, \"template_name\": self.search_template or \"admin/company_country_choice.html\", } from company.views import ChoiceCountry return", "= { \"extra_context\": context, \"template_name\": self.search_template or \"admin/company_country_choice.html\", } from company.views import ChoiceCountry", "info), ])) ])) ] return my_urls + urls ##################### # FR ##################### class", "request, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))", "= self.get_object(request, unquote(object_id), to_field) if object_id else None context = { **self.admin_site.each_context(request), \"current_url\":", "obj else _.countries, \"object_name\": str(opts.verbose_name), \"object\": obj, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media", "include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search_extend\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add_extend\" % info), ])) ]))", "from django.urls import path, include urls = super().get_urls() info = self.model._meta.app_label, self.model._meta.model_name my_urls", "'capital_socnomtotal', 'capital_division', 'current', 'share_capital', 'turnover', 'floating', 'icb', 'market', 'dowjones', 'nasdaq', 'gaia' )}), ('rules',", "self.media } defaults = { \"extra_context\": context, \"country\": country, \"parent_object\": parent_object if parent_object", "\"admin/company_country_add.html\", } from company.views import AddByCountry return AddByCountry.as_view(**defaults)(request) def get_urls(self): from django.urls import", "context, \"country\": country, \"parent_object\": parent_object if parent_object else None, \"success_url\": current_url, \"template_name\": self.search_template", "country_search_view(self, request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field =", "info), ])) ])), path(\"<path:object_id>/choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice_extend\" % info), path(\"<str:country>/search/\", include([ path(\"\",", "\"app_label\": opts.app_label, \"media\": self.media } request.current_app = self.admin_site.name defaults = { \"extra_context\": context,", "\"media\": self.media } defaults = { \"extra_context\": context, \"country\": country, \"parent_object\": parent_object if", "\"media\": self.media } request.current_app = self.admin_site.name defaults = { \"extra_context\": context, \"template_name\": self.search_template", "{ \"extra_context\": context, \"admin\": True, \"country\": country, \"parent_object\": parent_object if parent_object else None,", "])) ])) ] return my_urls + urls ##################### # FR ##################### class CompanyFRAdminInline(admin.StackedInline):", "model, admin_site): super().__init__(model, admin_site) if conf.named_id: self.readonly_fields += ('named_id',) self.add_field('Informations', ('named_id',)) def render_change_form(self,", "never_cache from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.utils import unquote from django.urls import reverse,", "defaults = { \"extra_context\": context, \"template_name\": self.search_template or \"admin/company_country_choice.html\", } from company.views import", "'siege_fr', )})) list_display = ('denomination', 'since', 'siege_fr') search_fields = (\"denomination\", \"company_fr__siret\") change_list_template =", "path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add\" % info), ]))", "as address_fields from mighty.applications.address.admin import AddressAdminInline from company import models, fields, translates as", "django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.utils import unquote from django.urls import reverse, resolve from", "object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) obj", "import never_cache from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.utils import unquote from django.urls import", "self.media } request.current_app = self.admin_site.name defaults = { \"extra_context\": context, \"template_name\": self.search_template or", "to_field) if object_id else None context = { **self.admin_site.each_context(request), \"parent_object\": parent_object, \"app_path\": request.get_full_path(),", "\"fields\": ( 'siege_fr', )})) list_display = ('denomination', 'since', 'siege_fr') search_fields = (\"denomination\", \"company_fr__siret\")", "TemplateResponse from mighty.admin.models import BaseAdmin from mighty.applications.address import fields as address_fields from mighty.applications.address.admin", "} request.current_app = self.admin_site.name defaults = { \"extra_context\": context, \"template_name\": self.search_template or \"admin/company_country_choice.html\",", "= (\"denomination\", \"company_fr__siret\") change_list_template = \"admin/company_change_list.html\" change_form_template = \"admin/company_change_form.html\" change_form_logs_template = \"admin/company_change_form_logs.html\" readonly_fields", "extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) obj =", "opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) obj = self.get_object(request, unquote(object_id), to_field) if", "or \"admin/company_country_choice.html\", } from company.views import ChoiceCountry return ChoiceCountry.as_view(**defaults)(request) @never_cache def country_search_view(self, request,", "self.change_form_logs_template return response def country_choice_view(self, request, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts =", "name=\"%s_%s_country_search\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add\" % info), ])) ])), path(\"<path:object_id>/choices/\", include([ path(\"\",", "import ChoiceCountry return ChoiceCountry.as_view(**defaults)(request) @never_cache def country_search_view(self, request, country, object_id=None, extra_context=None): current_url =", "if object_id else None context = { **self.admin_site.each_context(request), \"current_url\": current_url, \"title\": \"%s (%s)\"", "<reponame>dev-easyshares/company from django.contrib import admin from django.conf import settings from django.views.decorators.cache import never_cache", "if hasattr(self.model, \"changelog_model\"): response.template_name = self.change_form_logs_template return response def country_choice_view(self, request, object_id=None, extra_context=None):", "= { \"extra_context\": context, \"admin\": True, \"country\": country, \"parent_object\": parent_object if parent_object else", "import CompanyConfig as conf class CompanyAdmin(BaseAdmin): fieldsets = ( (None, {\"classes\": (\"wide\",), \"fields\":", "change_form_template = \"admin/company_change_form.html\" change_form_logs_template = \"admin/company_change_form_logs.html\" readonly_fields = ('siege_fr',) search_template = None def", "CompanyConfig as conf class CompanyAdmin(BaseAdmin): fieldsets = ( (None, {\"classes\": (\"wide\",), \"fields\": ('denomination',", "from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.utils import unquote from django.urls import reverse, resolve", "**self.admin_site.each_context(request), \"current_url\": current_url, \"title\": \"%s (%s)\" % (_.countries, obj) if obj else _.countries,", "= super().render_change_form(request, context, add, change, form_url, obj) if hasattr(self.model, \"changelog_model\"): response.template_name = self.change_form_logs_template", "self.search_template or \"admin/company_country_add.html\", } from company.views import AddByCountry return AddByCountry.as_view(**defaults)(request) def get_urls(self): from", "get_urls(self): from django.urls import path, include urls = super().get_urls() info = self.model._meta.app_label, self.model._meta.model_name", "= [ path(\"choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view,", "])) ])), path(\"<path:object_id>/choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice_extend\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view,", "opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) parent_object = self.get_object(request, unquote(object_id), to_field) if", "\"admin/company_change_form.html\" change_form_logs_template = \"admin/company_change_form_logs.html\" readonly_fields = ('siege_fr',) search_template = None def __init__(self, model,", "else None context = { **self.admin_site.each_context(request), \"parent_object\": parent_object, \"app_path\": request.get_full_path(), \"username\": request.user.get_username(), \"current_url\":", "CompanyAdmin(BaseAdmin): fieldsets = ( (None, {\"classes\": (\"wide\",), \"fields\": ('denomination', 'is_type', 'since', 'site', 'effective',", "+ ('is_siege', 'is_active') class BaloAdmin(BaseAdmin): fieldsets = ((None, {\"classes\": (\"wide\",), \"fields\": fields.balo}),) #####################", "'stock_min_rule', 'stock_min_status' )}), ('sieges', {\"classes\": (\"wide\",), \"fields\": ( 'siege_fr', )})) list_display = ('denomination',", "include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search\" % info),", "import reverse, resolve from django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from", "return AddByCountry.as_view(**defaults)(request) def get_urls(self): from django.urls import path, include urls = super().get_urls() info", "[ path(\"choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search\"", "self.country_add_view, name=\"%s_%s_country_add\" % info), ])) ])), path(\"<path:object_id>/choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice_extend\" % info),", "or \"admin/company_country_add.html\", } from company.views import AddByCountry return AddByCountry.as_view(**defaults)(request) def get_urls(self): from django.urls", "context, \"template_name\": self.search_template or \"admin/company_country_choice.html\", } from company.views import ChoiceCountry return ChoiceCountry.as_view(**defaults)(request) @never_cache", "AddByCountry return AddByCountry.as_view(**defaults)(request) def get_urls(self): from django.urls import path, include urls = super().get_urls()", "'is_type', 'since', 'site', 'effective', 'secretary', 'resume', 'share_kind')}), ('comex & purpose', {\"classes\": (\"wide\",), \"fields\":", "company import models, fields, translates as _ from company.apps import CompanyConfig as conf", "if obj else _.countries, \"object_name\": str(opts.verbose_name), \"object\": obj, \"opts\": opts, \"app_label\": opts.app_label, \"media\":", "'capital_division', 'current', 'share_capital', 'turnover', 'floating', 'icb', 'market', 'dowjones', 'nasdaq', 'gaia' )}), ('rules', {\"classes\":", "include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice_extend\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search_extend\" % info),", "address_fields + ('is_siege', 'is_active') class BaloAdmin(BaseAdmin): fieldsets = ((None, {\"classes\": (\"wide\",), \"fields\": fields.balo}),)", "super().render_change_form(request, context, add, change, form_url, obj) if hasattr(self.model, \"changelog_model\"): response.template_name = self.change_form_logs_template return", "( 'capital_socnomtotal', 'capital_division', 'current', 'share_capital', 'turnover', 'floating', 'icb', 'market', 'dowjones', 'nasdaq', 'gaia' )}),", "+= ('named_id',) self.add_field('Informations', ('named_id',)) def render_change_form(self, request, context, add=False, change=False, form_url=\"\", obj=None): response", "add, change, form_url, obj) if hasattr(self.model, \"changelog_model\"): response.template_name = self.change_form_logs_template return response def", "obj=None): response = super().render_change_form(request, context, add, change, form_url, obj) if hasattr(self.model, \"changelog_model\"): response.template_name", "request.user.get_username(), \"current_url\": current_url, \"country\": country, \"title\": _.search, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media", "\"admin\": True, \"country\": country, \"parent_object\": parent_object if parent_object else None, \"template_name\": self.search_template or", "= ('denomination', 'since', 'siege_fr') search_fields = (\"denomination\", \"company_fr__siret\") change_list_template = \"admin/company_change_list.html\" change_form_template =", "if object_id else None context = { **self.admin_site.each_context(request), \"parent_object\": parent_object, \"app_path\": request.get_full_path(), \"username\":", "import fields as address_fields from mighty.applications.address.admin import AddressAdminInline from company import models, fields,", "class CompanyAdmin(BaseAdmin): fieldsets = ( (None, {\"classes\": (\"wide\",), \"fields\": ('denomination', 'is_type', 'since', 'site',", "& purpose', {\"classes\": (\"wide\",), \"fields\": ('purpose', 'instance_comex', 'matrix_skills')}), ('market', {\"classes\": (\"wide\",), \"fields\": (", "defaults = { \"extra_context\": context, \"admin\": True, \"country\": country, \"parent_object\": parent_object if parent_object", "= self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) obj = self.get_object(request, unquote(object_id), to_field) if object_id", "path(\"\", self.country_search_view, name=\"%s_%s_country_search_extend\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add_extend\" % info), ])) ])) ]", "from mighty.admin.models import BaseAdmin from mighty.applications.address import fields as address_fields from mighty.applications.address.admin import", "fields.country + fields.fr extra = 0 max_num = 0 class CompanyAddressFRAdminInline(AddressAdminInline): fields =", "\"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } request.current_app = self.admin_site.name defaults = {", "from company.views import AddByCountry return AddByCountry.as_view(**defaults)(request) def get_urls(self): from django.urls import path, include", "self.get_object(request, unquote(object_id), to_field) if object_id else None context = { **self.admin_site.each_context(request), \"parent_object\": parent_object,", "_.countries, \"object_name\": str(opts.verbose_name), \"object\": obj, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } request.current_app", "\"fields\": ( 'duration_mandate', 'settle_internal', 'age_limit_pdg', 'age_limit_dg', 'stock_min_rule', 'stock_min_status' )}), ('sieges', {\"classes\": (\"wide\",), \"fields\":", "from django.conf import settings from django.views.decorators.cache import never_cache from django.contrib.admin.options import TO_FIELD_VAR from", "} defaults = { \"extra_context\": context, \"country\": country, \"parent_object\": parent_object if parent_object else", "% info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search_extend\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add_extend\" %", "self.search_template or \"admin/company_country_search.html\", } from company.views import SearchByCountry return SearchByCountry.as_view(**defaults)(request=request) @never_cache def country_add_view(self,", "= self.model._meta.app_label, self.model._meta.model_name my_urls = [ path(\"choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice\" % info),", "if parent_object else None, \"template_name\": self.search_template or \"admin/company_country_add.html\", } from company.views import AddByCountry", "path(\"<path:object_id>/choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice_extend\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search_extend\" %", "'resume', 'share_kind')}), ('comex & purpose', {\"classes\": (\"wide\",), \"fields\": ('purpose', 'instance_comex', 'matrix_skills')}), ('market', {\"classes\":", "request, context, add=False, change=False, form_url=\"\", obj=None): response = super().render_change_form(request, context, add, change, form_url,", "name=\"%s_%s_country_choice\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add\"", "country_choice_view(self, request, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR,", "\"template_name\": self.search_template or \"admin/company_country_choice.html\", } from company.views import ChoiceCountry return ChoiceCountry.as_view(**defaults)(request) @never_cache def", "my_urls = [ path(\"choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice\" % info), path(\"<str:country>/search/\", include([ path(\"\",", "= request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) obj = self.get_object(request, unquote(object_id), to_field) if object_id else None context", "readonly_fields = ('siege_fr',) search_template = None def __init__(self, model, admin_site): super().__init__(model, admin_site) if", "(\"wide\",), \"fields\": ('purpose', 'instance_comex', 'matrix_skills')}), ('market', {\"classes\": (\"wide\",), \"fields\": ( 'capital_socnomtotal', 'capital_division', 'current',", "return SearchByCountry.as_view(**defaults)(request=request) @never_cache def country_add_view(self, request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts", "##################### class CompanyFRAdminInline(admin.StackedInline): fields = fields.country + fields.fr extra = 0 max_num =", "self.add_field('Informations', ('named_id',)) def render_change_form(self, request, context, add=False, change=False, form_url=\"\", obj=None): response = super().render_change_form(request,", "obj = self.get_object(request, unquote(object_id), to_field) if object_id else None context = { **self.admin_site.each_context(request),", "= resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) parent_object = self.get_object(request, unquote(object_id),", "urls ##################### # FR ##################### class CompanyFRAdminInline(admin.StackedInline): fields = fields.country + fields.fr extra", "= 0 class CompanyAddressFRAdminInline(AddressAdminInline): fields = address_fields + ('is_siege', 'is_active') class BaloAdmin(BaseAdmin): fieldsets", "= self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) parent_object = self.get_object(request, unquote(object_id), to_field) if object_id", "class CompanyFRAdminInline(admin.StackedInline): fields = fields.country + fields.fr extra = 0 max_num = 0", "company.views import SearchByCountry return SearchByCountry.as_view(**defaults)(request=request) @never_cache def country_add_view(self, request, country, object_id=None, extra_context=None): current_url", "( 'siege_fr', )})) list_display = ('denomination', 'since', 'siege_fr') search_fields = (\"denomination\", \"company_fr__siret\") change_list_template", "\"country\": country, \"parent_object\": parent_object if parent_object else None, \"template_name\": self.search_template or \"admin/company_country_add.html\", }", "admin_site): super().__init__(model, admin_site) if conf.named_id: self.readonly_fields += ('named_id',) self.add_field('Informations', ('named_id',)) def render_change_form(self, request,", "= address_fields + ('is_siege', 'is_active') class BaloAdmin(BaseAdmin): fieldsets = ((None, {\"classes\": (\"wide\",), \"fields\":", "mighty.applications.address import fields as address_fields from mighty.applications.address.admin import AddressAdminInline from company import models,", "= { \"extra_context\": context, \"country\": country, \"parent_object\": parent_object if parent_object else None, \"success_url\":", "import settings from django.views.decorators.cache import never_cache from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.utils import", "models, fields, translates as _ from company.apps import CompanyConfig as conf class CompanyAdmin(BaseAdmin):", "ChoiceCountry.as_view(**defaults)(request) @never_cache def country_search_view(self, request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts =", "import models, fields, translates as _ from company.apps import CompanyConfig as conf class", "request.current_app = self.admin_site.name defaults = { \"extra_context\": context, \"template_name\": self.search_template or \"admin/company_country_choice.html\", }", "(\"wide\",), \"fields\": ( 'duration_mandate', 'settle_internal', 'age_limit_pdg', 'age_limit_dg', 'stock_min_rule', 'stock_min_status' )}), ('sieges', {\"classes\": (\"wide\",),", "self.country_choice_view, name=\"%s_%s_country_choice_extend\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search_extend\" % info), path(\"add/\", self.country_add_view,", "fields = fields.country + fields.fr extra = 0 max_num = 0 class CompanyAddressFRAdminInline(AddressAdminInline):", "'site', 'effective', 'secretary', 'resume', 'share_kind')}), ('comex & purpose', {\"classes\": (\"wide\",), \"fields\": ('purpose', 'instance_comex',", "##################### # FR ##################### class CompanyFRAdminInline(admin.StackedInline): fields = fields.country + fields.fr extra =", "0 max_num = 0 class CompanyAddressFRAdminInline(AddressAdminInline): fields = address_fields + ('is_siege', 'is_active') class", "def render_change_form(self, request, context, add=False, change=False, form_url=\"\", obj=None): response = super().render_change_form(request, context, add,", "'effective', 'secretary', 'resume', 'share_kind')}), ('comex & purpose', {\"classes\": (\"wide\",), \"fields\": ('purpose', 'instance_comex', 'matrix_skills')}),", "\"%s (%s)\" % (_.countries, obj) if obj else _.countries, \"object_name\": str(opts.verbose_name), \"object\": obj,", "])), path(\"<path:object_id>/choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice_extend\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search_extend\"", "Http404, HttpResponseRedirect from django.template.response import TemplateResponse from mighty.admin.models import BaseAdmin from mighty.applications.address import", "current_url = resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) parent_object = self.get_object(request,", "company.views import AddByCountry return AddByCountry.as_view(**defaults)(request) def get_urls(self): from django.urls import path, include urls", "AddByCountry.as_view(**defaults)(request) def get_urls(self): from django.urls import path, include urls = super().get_urls() info =", "= resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) obj = self.get_object(request, unquote(object_id),", "'floating', 'icb', 'market', 'dowjones', 'nasdaq', 'gaia' )}), ('rules', {\"classes\": (\"wide\",), \"fields\": ( 'duration_mandate',", "\"app_label\": opts.app_label, \"media\": self.media } defaults = { \"extra_context\": context, \"admin\": True, \"country\":", "info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add_extend\" % info), ])) ])) ] return my_urls + urls", "country, \"parent_object\": parent_object if parent_object else None, \"template_name\": self.search_template or \"admin/company_country_add.html\", } from", "\"admin/company_country_search.html\", } from company.views import SearchByCountry return SearchByCountry.as_view(**defaults)(request=request) @never_cache def country_add_view(self, request, country,", "\"template_name\": self.search_template or \"admin/company_country_add.html\", } from company.views import AddByCountry return AddByCountry.as_view(**defaults)(request) def get_urls(self):", "fields.fr extra = 0 max_num = 0 class CompanyAddressFRAdminInline(AddressAdminInline): fields = address_fields +", "= ('siege_fr',) search_template = None def __init__(self, model, admin_site): super().__init__(model, admin_site) if conf.named_id:", "class BaloAdmin(BaseAdmin): fieldsets = ((None, {\"classes\": (\"wide\",), \"fields\": fields.balo}),) ##################### # US #####################", "{\"classes\": (\"wide\",), \"fields\": ('denomination', 'is_type', 'since', 'site', 'effective', 'secretary', 'resume', 'share_kind')}), ('comex &", "name=\"%s_%s_country_search_extend\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add_extend\" % info), ])) ])) ] return my_urls", "= super().get_urls() info = self.model._meta.app_label, self.model._meta.model_name my_urls = [ path(\"choices/\", include([ path(\"\", self.country_choice_view,", "return ChoiceCountry.as_view(**defaults)(request) @never_cache def country_search_view(self, request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts", "'age_limit_dg', 'stock_min_rule', 'stock_min_status' )}), ('sieges', {\"classes\": (\"wide\",), \"fields\": ( 'siege_fr', )})) list_display =", "opts.app_label, \"media\": self.media } defaults = { \"extra_context\": context, \"admin\": True, \"country\": country,", "\"object_name\": str(opts.verbose_name), \"object\": obj, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } request.current_app =", "defaults = { \"extra_context\": context, \"country\": country, \"parent_object\": parent_object if parent_object else None,", "\"extra_context\": context, \"admin\": True, \"country\": country, \"parent_object\": parent_object if parent_object else None, \"template_name\":", "if conf.named_id: self.readonly_fields += ('named_id',) self.add_field('Informations', ('named_id',)) def render_change_form(self, request, context, add=False, change=False,", "info = self.model._meta.app_label, self.model._meta.model_name my_urls = [ path(\"choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice\" %", "'nasdaq', 'gaia' )}), ('rules', {\"classes\": (\"wide\",), \"fields\": ( 'duration_mandate', 'settle_internal', 'age_limit_pdg', 'age_limit_dg', 'stock_min_rule',", "return my_urls + urls ##################### # FR ##################### class CompanyFRAdminInline(admin.StackedInline): fields = fields.country", "'duration_mandate', 'settle_internal', 'age_limit_pdg', 'age_limit_dg', 'stock_min_rule', 'stock_min_status' )}), ('sieges', {\"classes\": (\"wide\",), \"fields\": ( 'siege_fr',", "render_change_form(self, request, context, add=False, change=False, form_url=\"\", obj=None): response = super().render_change_form(request, context, add, change,", "} from company.views import SearchByCountry return SearchByCountry.as_view(**defaults)(request=request) @never_cache def country_add_view(self, request, country, object_id=None,", "{\"classes\": (\"wide\",), \"fields\": ('purpose', 'instance_comex', 'matrix_skills')}), ('market', {\"classes\": (\"wide\",), \"fields\": ( 'capital_socnomtotal', 'capital_division',", "address_fields from mighty.applications.address.admin import AddressAdminInline from company import models, fields, translates as _", "context, \"admin\": True, \"country\": country, \"parent_object\": parent_object if parent_object else None, \"template_name\": self.search_template", "path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search_extend\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add_extend\" % info), ]))", "from mighty.applications.address import fields as address_fields from mighty.applications.address.admin import AddressAdminInline from company import", "{\"classes\": (\"wide\",), \"fields\": ( 'siege_fr', )})) list_display = ('denomination', 'since', 'siege_fr') search_fields =", "request.GET.get(TO_FIELD_VAR)) parent_object = self.get_object(request, unquote(object_id), to_field) if object_id else None context = {", "conf class CompanyAdmin(BaseAdmin): fieldsets = ( (None, {\"classes\": (\"wide\",), \"fields\": ('denomination', 'is_type', 'since',", "context, add, change, form_url, obj) if hasattr(self.model, \"changelog_model\"): response.template_name = self.change_form_logs_template return response", "+ fields.fr extra = 0 max_num = 0 class CompanyAddressFRAdminInline(AddressAdminInline): fields = address_fields", "info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add\" % info),", "__init__(self, model, admin_site): super().__init__(model, admin_site) if conf.named_id: self.readonly_fields += ('named_id',) self.add_field('Informations', ('named_id',)) def", "to_field) if object_id else None context = { **self.admin_site.each_context(request), \"current_url\": current_url, \"title\": \"%s", ")}), ('rules', {\"classes\": (\"wide\",), \"fields\": ( 'duration_mandate', 'settle_internal', 'age_limit_pdg', 'age_limit_dg', 'stock_min_rule', 'stock_min_status' )}),", "request.GET.get(TO_FIELD_VAR)) obj = self.get_object(request, unquote(object_id), to_field) if object_id else None context = {", "str(opts.verbose_name), \"object\": obj, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } request.current_app = self.admin_site.name", "from company.views import ChoiceCountry return ChoiceCountry.as_view(**defaults)(request) @never_cache def country_search_view(self, request, country, object_id=None, extra_context=None):", "search_fields = (\"denomination\", \"company_fr__siret\") change_list_template = \"admin/company_change_list.html\" change_form_template = \"admin/company_change_form.html\" change_form_logs_template = \"admin/company_change_form_logs.html\"", "request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR,", "\"changelog_model\"): response.template_name = self.change_form_logs_template return response def country_choice_view(self, request, object_id=None, extra_context=None): current_url =", "request.get_full_path(), \"username\": request.user.get_username(), \"current_url\": current_url, \"country\": country, \"title\": _.search, \"opts\": opts, \"app_label\": opts.app_label,", "django.template.response import TemplateResponse from mighty.admin.models import BaseAdmin from mighty.applications.address import fields as address_fields", "parent_object else None, \"success_url\": current_url, \"template_name\": self.search_template or \"admin/company_country_search.html\", } from company.views import", "% info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add\" %", "= request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) parent_object = self.get_object(request, unquote(object_id), to_field) if object_id else None context", "True, \"country\": country, \"parent_object\": parent_object if parent_object else None, \"template_name\": self.search_template or \"admin/company_country_add.html\",", "'age_limit_pdg', 'age_limit_dg', 'stock_min_rule', 'stock_min_status' )}), ('sieges', {\"classes\": (\"wide\",), \"fields\": ( 'siege_fr', )})) list_display", "None, \"success_url\": current_url, \"template_name\": self.search_template or \"admin/company_country_search.html\", } from company.views import SearchByCountry return", "path(\"choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search\" %", "from django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from mighty.admin.models import BaseAdmin", "= 0 max_num = 0 class CompanyAddressFRAdminInline(AddressAdminInline): fields = address_fields + ('is_siege', 'is_active')", "'instance_comex', 'matrix_skills')}), ('market', {\"classes\": (\"wide\",), \"fields\": ( 'capital_socnomtotal', 'capital_division', 'current', 'share_capital', 'turnover', 'floating',", "object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) parent_object", "resolve from django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from mighty.admin.models import", "(\"wide\",), \"fields\": ('denomination', 'is_type', 'since', 'site', 'effective', 'secretary', 'resume', 'share_kind')}), ('comex & purpose',", "super().get_urls() info = self.model._meta.app_label, self.model._meta.model_name my_urls = [ path(\"choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice\"", "self.country_search_view, name=\"%s_%s_country_search\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add\" % info), ])) ])), path(\"<path:object_id>/choices/\", include([", "\"extra_context\": context, \"template_name\": self.search_template or \"admin/company_country_choice.html\", } from company.views import ChoiceCountry return ChoiceCountry.as_view(**defaults)(request)", "\"parent_object\": parent_object if parent_object else None, \"template_name\": self.search_template or \"admin/company_country_add.html\", } from company.views", "} from company.views import AddByCountry return AddByCountry.as_view(**defaults)(request) def get_urls(self): from django.urls import path,", "{ **self.admin_site.each_context(request), \"current_url\": current_url, \"title\": \"%s (%s)\" % (_.countries, obj) if obj else", "'secretary', 'resume', 'share_kind')}), ('comex & purpose', {\"classes\": (\"wide\",), \"fields\": ('purpose', 'instance_comex', 'matrix_skills')}), ('market',", "django.contrib import admin from django.conf import settings from django.views.decorators.cache import never_cache from django.contrib.admin.options", "urls = super().get_urls() info = self.model._meta.app_label, self.model._meta.model_name my_urls = [ path(\"choices/\", include([ path(\"\",", "**self.admin_site.each_context(request), \"parent_object\": parent_object, \"app_path\": request.get_full_path(), \"username\": request.user.get_username(), \"current_url\": current_url, \"country\": country, \"title\": _.search,", "info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add\" % info), ])) ])), path(\"<path:object_id>/choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice_extend\"", "(None, {\"classes\": (\"wide\",), \"fields\": ('denomination', 'is_type', 'since', 'site', 'effective', 'secretary', 'resume', 'share_kind')}), ('comex", "\"fields\": ('denomination', 'is_type', 'since', 'site', 'effective', 'secretary', 'resume', 'share_kind')}), ('comex & purpose', {\"classes\":", "country_add_view(self, request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field =", "parent_object = self.get_object(request, unquote(object_id), to_field) if object_id else None context = { **self.admin_site.each_context(request),", "django.urls import reverse, resolve from django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse", "parent_object, \"app_path\": request.get_full_path(), \"username\": request.user.get_username(), \"current_url\": current_url, \"country\": country, \"title\": _.search, \"opts\": opts,", "import admin from django.conf import settings from django.views.decorators.cache import never_cache from django.contrib.admin.options import", "self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) parent_object = self.get_object(request, unquote(object_id), to_field) if object_id else", "country, \"title\": _.search, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } defaults = {", "import path, include urls = super().get_urls() info = self.model._meta.app_label, self.model._meta.model_name my_urls = [", "'turnover', 'floating', 'icb', 'market', 'dowjones', 'nasdaq', 'gaia' )}), ('rules', {\"classes\": (\"wide\",), \"fields\": (", "name=\"%s_%s_country_choice_extend\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search_extend\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add_extend\"", "(\"denomination\", \"company_fr__siret\") change_list_template = \"admin/company_change_list.html\" change_form_template = \"admin/company_change_form.html\" change_form_logs_template = \"admin/company_change_form_logs.html\" readonly_fields =", "response.template_name = self.change_form_logs_template return response def country_choice_view(self, request, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name", "= None def __init__(self, model, admin_site): super().__init__(model, admin_site) if conf.named_id: self.readonly_fields += ('named_id',)", "= self.get_object(request, unquote(object_id), to_field) if object_id else None context = { **self.admin_site.each_context(request), \"parent_object\":", "('is_siege', 'is_active') class BaloAdmin(BaseAdmin): fieldsets = ((None, {\"classes\": (\"wide\",), \"fields\": fields.balo}),) ##################### #", "company.views import ChoiceCountry return ChoiceCountry.as_view(**defaults)(request) @never_cache def country_search_view(self, request, country, object_id=None, extra_context=None): current_url", "'siege_fr') search_fields = (\"denomination\", \"company_fr__siret\") change_list_template = \"admin/company_change_list.html\" change_form_template = \"admin/company_change_form.html\" change_form_logs_template =", "opts.app_label, \"media\": self.media } defaults = { \"extra_context\": context, \"country\": country, \"parent_object\": parent_object", "parent_object if parent_object else None, \"success_url\": current_url, \"template_name\": self.search_template or \"admin/company_country_search.html\", } from", "current_url, \"template_name\": self.search_template or \"admin/company_country_search.html\", } from company.views import SearchByCountry return SearchByCountry.as_view(**defaults)(request=request) @never_cache", "import unquote from django.urls import reverse, resolve from django.http import Http404, HttpResponseRedirect from", "response = super().render_change_form(request, context, add, change, form_url, obj) if hasattr(self.model, \"changelog_model\"): response.template_name =", "TO_FIELD_VAR from django.contrib.admin.utils import unquote from django.urls import reverse, resolve from django.http import", "name=\"%s_%s_country_add\" % info), ])) ])), path(\"<path:object_id>/choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice_extend\" % info), path(\"<str:country>/search/\",", "FR ##################### class CompanyFRAdminInline(admin.StackedInline): fields = fields.country + fields.fr extra = 0 max_num", "self.country_search_view, name=\"%s_%s_country_search_extend\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add_extend\" % info), ])) ])) ] return", "include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add\" % info), ])) ])),", "(%s)\" % (_.countries, obj) if obj else _.countries, \"object_name\": str(opts.verbose_name), \"object\": obj, \"opts\":", "from company import models, fields, translates as _ from company.apps import CompanyConfig as", "{\"classes\": (\"wide\",), \"fields\": ( 'duration_mandate', 'settle_internal', 'age_limit_pdg', 'age_limit_dg', 'stock_min_rule', 'stock_min_status' )}), ('sieges', {\"classes\":", "} from company.views import ChoiceCountry return ChoiceCountry.as_view(**defaults)(request) @never_cache def country_search_view(self, request, country, object_id=None,", "\"title\": _.search, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } defaults = { \"extra_context\":", "import BaseAdmin from mighty.applications.address import fields as address_fields from mighty.applications.address.admin import AddressAdminInline from", "change, form_url, obj) if hasattr(self.model, \"changelog_model\"): response.template_name = self.change_form_logs_template return response def country_choice_view(self,", "self.admin_site.name defaults = { \"extra_context\": context, \"template_name\": self.search_template or \"admin/company_country_choice.html\", } from company.views", "change_list_template = \"admin/company_change_list.html\" change_form_template = \"admin/company_change_form.html\" change_form_logs_template = \"admin/company_change_form_logs.html\" readonly_fields = ('siege_fr',) search_template", "from django.template.response import TemplateResponse from mighty.admin.models import BaseAdmin from mighty.applications.address import fields as", "\"fields\": ('purpose', 'instance_comex', 'matrix_skills')}), ('market', {\"classes\": (\"wide\",), \"fields\": ( 'capital_socnomtotal', 'capital_division', 'current', 'share_capital',", "])) ] return my_urls + urls ##################### # FR ##################### class CompanyFRAdminInline(admin.StackedInline): fields", "\"country\": country, \"title\": _.search, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } defaults =", "obj) if obj else _.countries, \"object_name\": str(opts.verbose_name), \"object\": obj, \"opts\": opts, \"app_label\": opts.app_label,", "path, include urls = super().get_urls() info = self.model._meta.app_label, self.model._meta.model_name my_urls = [ path(\"choices/\",", "SearchByCountry.as_view(**defaults)(request=request) @never_cache def country_add_view(self, request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts =", "{\"classes\": (\"wide\",), \"fields\": ( 'capital_socnomtotal', 'capital_division', 'current', 'share_capital', 'turnover', 'floating', 'icb', 'market', 'dowjones',", "django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from mighty.admin.models import BaseAdmin from", "SearchByCountry return SearchByCountry.as_view(**defaults)(request=request) @never_cache def country_add_view(self, request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name", "object_id else None context = { **self.admin_site.each_context(request), \"current_url\": current_url, \"title\": \"%s (%s)\" %", "to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) obj = self.get_object(request, unquote(object_id), to_field) if object_id else None", "def __init__(self, model, admin_site): super().__init__(model, admin_site) if conf.named_id: self.readonly_fields += ('named_id',) self.add_field('Informations', ('named_id',))", "self.media } defaults = { \"extra_context\": context, \"admin\": True, \"country\": country, \"parent_object\": parent_object", "= { **self.admin_site.each_context(request), \"parent_object\": parent_object, \"app_path\": request.get_full_path(), \"username\": request.user.get_username(), \"current_url\": current_url, \"country\": country,", "else None, \"template_name\": self.search_template or \"admin/company_country_add.html\", } from company.views import AddByCountry return AddByCountry.as_view(**defaults)(request)", "None def __init__(self, model, admin_site): super().__init__(model, admin_site) if conf.named_id: self.readonly_fields += ('named_id',) self.add_field('Informations',", "fields = address_fields + ('is_siege', 'is_active') class BaloAdmin(BaseAdmin): fieldsets = ((None, {\"classes\": (\"wide\",),", "% info), ])) ])), path(\"<path:object_id>/choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice_extend\" % info), path(\"<str:country>/search/\", include([", "'share_capital', 'turnover', 'floating', 'icb', 'market', 'dowjones', 'nasdaq', 'gaia' )}), ('rules', {\"classes\": (\"wide\",), \"fields\":", "mighty.applications.address.admin import AddressAdminInline from company import models, fields, translates as _ from company.apps", "BaseAdmin from mighty.applications.address import fields as address_fields from mighty.applications.address.admin import AddressAdminInline from company", "extra = 0 max_num = 0 class CompanyAddressFRAdminInline(AddressAdminInline): fields = address_fields + ('is_siege',", "'matrix_skills')}), ('market', {\"classes\": (\"wide\",), \"fields\": ( 'capital_socnomtotal', 'capital_division', 'current', 'share_capital', 'turnover', 'floating', 'icb',", "else None context = { **self.admin_site.each_context(request), \"current_url\": current_url, \"title\": \"%s (%s)\" % (_.countries,", "change_form_logs_template = \"admin/company_change_form_logs.html\" readonly_fields = ('siege_fr',) search_template = None def __init__(self, model, admin_site):", "def get_urls(self): from django.urls import path, include urls = super().get_urls() info = self.model._meta.app_label,", "\"app_label\": opts.app_label, \"media\": self.media } defaults = { \"extra_context\": context, \"country\": country, \"parent_object\":", "django.urls import path, include urls = super().get_urls() info = self.model._meta.app_label, self.model._meta.model_name my_urls =", "self.search_template or \"admin/company_country_choice.html\", } from company.views import ChoiceCountry return ChoiceCountry.as_view(**defaults)(request) @never_cache def country_search_view(self,", "'market', 'dowjones', 'nasdaq', 'gaia' )}), ('rules', {\"classes\": (\"wide\",), \"fields\": ( 'duration_mandate', 'settle_internal', 'age_limit_pdg',", "('named_id',) self.add_field('Informations', ('named_id',)) def render_change_form(self, request, context, add=False, change=False, form_url=\"\", obj=None): response =", "from django.urls import reverse, resolve from django.http import Http404, HttpResponseRedirect from django.template.response import", "current_url = resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) obj = self.get_object(request,", "'settle_internal', 'age_limit_pdg', 'age_limit_dg', 'stock_min_rule', 'stock_min_status' )}), ('sieges', {\"classes\": (\"wide\",), \"fields\": ( 'siege_fr', )}))", "= \"admin/company_change_list.html\" change_form_template = \"admin/company_change_form.html\" change_form_logs_template = \"admin/company_change_form_logs.html\" readonly_fields = ('siege_fr',) search_template =", "obj) if hasattr(self.model, \"changelog_model\"): response.template_name = self.change_form_logs_template return response def country_choice_view(self, request, object_id=None,", "change=False, form_url=\"\", obj=None): response = super().render_change_form(request, context, add, change, form_url, obj) if hasattr(self.model,", "from django.contrib import admin from django.conf import settings from django.views.decorators.cache import never_cache from", "context = { **self.admin_site.each_context(request), \"parent_object\": parent_object, \"app_path\": request.get_full_path(), \"username\": request.user.get_username(), \"current_url\": current_url, \"country\":", "self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) obj = self.get_object(request, unquote(object_id), to_field) if object_id else", "# FR ##################### class CompanyFRAdminInline(admin.StackedInline): fields = fields.country + fields.fr extra = 0", "django.views.decorators.cache import never_cache from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.utils import unquote from django.urls", "to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) parent_object = self.get_object(request, unquote(object_id), to_field) if object_id else None", "info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search_extend\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add_extend\" % info),", "= \"admin/company_change_form.html\" change_form_logs_template = \"admin/company_change_form_logs.html\" readonly_fields = ('siege_fr',) search_template = None def __init__(self,", "\"admin/company_country_choice.html\", } from company.views import ChoiceCountry return ChoiceCountry.as_view(**defaults)(request) @never_cache def country_search_view(self, request, country,", "% info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add_extend\" % info), ])) ])) ] return my_urls +", "\"current_url\": current_url, \"country\": country, \"title\": _.search, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media }", "unquote from django.urls import reverse, resolve from django.http import Http404, HttpResponseRedirect from django.template.response", "fields as address_fields from mighty.applications.address.admin import AddressAdminInline from company import models, fields, translates", "('denomination', 'is_type', 'since', 'site', 'effective', 'secretary', 'resume', 'share_kind')}), ('comex & purpose', {\"classes\": (\"wide\",),", "\"template_name\": self.search_template or \"admin/company_country_search.html\", } from company.views import SearchByCountry return SearchByCountry.as_view(**defaults)(request=request) @never_cache def", "\"admin/company_change_list.html\" change_form_template = \"admin/company_change_form.html\" change_form_logs_template = \"admin/company_change_form_logs.html\" readonly_fields = ('siege_fr',) search_template = None", "\"app_path\": request.get_full_path(), \"username\": request.user.get_username(), \"current_url\": current_url, \"country\": country, \"title\": _.search, \"opts\": opts, \"app_label\":", "\"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } defaults = { \"extra_context\": context, \"country\":", "_ from company.apps import CompanyConfig as conf class CompanyAdmin(BaseAdmin): fieldsets = ( (None,", "parent_object else None, \"template_name\": self.search_template or \"admin/company_country_add.html\", } from company.views import AddByCountry return", "self.get_object(request, unquote(object_id), to_field) if object_id else None context = { **self.admin_site.each_context(request), \"current_url\": current_url,", "('comex & purpose', {\"classes\": (\"wide\",), \"fields\": ('purpose', 'instance_comex', 'matrix_skills')}), ('market', {\"classes\": (\"wide\",), \"fields\":", "super().__init__(model, admin_site) if conf.named_id: self.readonly_fields += ('named_id',) self.add_field('Informations', ('named_id',)) def render_change_form(self, request, context,", "def country_search_view(self, request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field", "conf.named_id: self.readonly_fields += ('named_id',) self.add_field('Informations', ('named_id',)) def render_change_form(self, request, context, add=False, change=False, form_url=\"\",", "\"parent_object\": parent_object, \"app_path\": request.get_full_path(), \"username\": request.user.get_username(), \"current_url\": current_url, \"country\": country, \"title\": _.search, \"opts\":", "\"success_url\": current_url, \"template_name\": self.search_template or \"admin/company_country_search.html\", } from company.views import SearchByCountry return SearchByCountry.as_view(**defaults)(request=request)", "parent_object if parent_object else None, \"template_name\": self.search_template or \"admin/company_country_add.html\", } from company.views import", "(_.countries, obj) if obj else _.countries, \"object_name\": str(opts.verbose_name), \"object\": obj, \"opts\": opts, \"app_label\":", "from mighty.applications.address.admin import AddressAdminInline from company import models, fields, translates as _ from", "from company.views import SearchByCountry return SearchByCountry.as_view(**defaults)(request=request) @never_cache def country_add_view(self, request, country, object_id=None, extra_context=None):", "include urls = super().get_urls() info = self.model._meta.app_label, self.model._meta.model_name my_urls = [ path(\"choices/\", include([", "add=False, change=False, form_url=\"\", obj=None): response = super().render_change_form(request, context, add, change, form_url, obj) if", "@never_cache def country_search_view(self, request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta", "resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) obj = self.get_object(request, unquote(object_id), to_field)", "country, \"parent_object\": parent_object if parent_object else None, \"success_url\": current_url, \"template_name\": self.search_template or \"admin/company_country_search.html\",", "] return my_urls + urls ##################### # FR ##################### class CompanyFRAdminInline(admin.StackedInline): fields =", "None context = { **self.admin_site.each_context(request), \"parent_object\": parent_object, \"app_path\": request.get_full_path(), \"username\": request.user.get_username(), \"current_url\": current_url,", "self.country_choice_view, name=\"%s_%s_country_choice\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search\" % info), path(\"add/\", self.country_add_view,", "from django.contrib.admin.utils import unquote from django.urls import reverse, resolve from django.http import Http404,", "unquote(object_id), to_field) if object_id else None context = { **self.admin_site.each_context(request), \"current_url\": current_url, \"title\":", "import AddByCountry return AddByCountry.as_view(**defaults)(request) def get_urls(self): from django.urls import path, include urls =", "reverse, resolve from django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from mighty.admin.models", "fieldsets = ( (None, {\"classes\": (\"wide\",), \"fields\": ('denomination', 'is_type', 'since', 'site', 'effective', 'secretary',", "('purpose', 'instance_comex', 'matrix_skills')}), ('market', {\"classes\": (\"wide\",), \"fields\": ( 'capital_socnomtotal', 'capital_division', 'current', 'share_capital', 'turnover',", "admin_site) if conf.named_id: self.readonly_fields += ('named_id',) self.add_field('Informations', ('named_id',)) def render_change_form(self, request, context, add=False,", "% (_.countries, obj) if obj else _.countries, \"object_name\": str(opts.verbose_name), \"object\": obj, \"opts\": opts,", "object_id else None context = { **self.admin_site.each_context(request), \"parent_object\": parent_object, \"app_path\": request.get_full_path(), \"username\": request.user.get_username(),", "'current', 'share_capital', 'turnover', 'floating', 'icb', 'market', 'dowjones', 'nasdaq', 'gaia' )}), ('rules', {\"classes\": (\"wide\",),", "% info), ])) ])) ] return my_urls + urls ##################### # FR #####################", "@never_cache def country_add_view(self, request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta", "if parent_object else None, \"success_url\": current_url, \"template_name\": self.search_template or \"admin/company_country_search.html\", } from company.views", "'since', 'siege_fr') search_fields = (\"denomination\", \"company_fr__siret\") change_list_template = \"admin/company_change_list.html\" change_form_template = \"admin/company_change_form.html\" change_form_logs_template", "form_url, obj) if hasattr(self.model, \"changelog_model\"): response.template_name = self.change_form_logs_template return response def country_choice_view(self, request,", "import TemplateResponse from mighty.admin.models import BaseAdmin from mighty.applications.address import fields as address_fields from", "('market', {\"classes\": (\"wide\",), \"fields\": ( 'capital_socnomtotal', 'capital_division', 'current', 'share_capital', 'turnover', 'floating', 'icb', 'market',", "('sieges', {\"classes\": (\"wide\",), \"fields\": ( 'siege_fr', )})) list_display = ('denomination', 'since', 'siege_fr') search_fields", "resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) parent_object = self.get_object(request, unquote(object_id), to_field)", "} defaults = { \"extra_context\": context, \"admin\": True, \"country\": country, \"parent_object\": parent_object if", "settings from django.views.decorators.cache import never_cache from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.utils import unquote", "\"parent_object\": parent_object if parent_object else None, \"success_url\": current_url, \"template_name\": self.search_template or \"admin/company_country_search.html\", }", "from company.apps import CompanyConfig as conf class CompanyAdmin(BaseAdmin): fieldsets = ( (None, {\"classes\":", "= fields.country + fields.fr extra = 0 max_num = 0 class CompanyAddressFRAdminInline(AddressAdminInline): fields", "response def country_choice_view(self, request, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field", "{ \"extra_context\": context, \"country\": country, \"parent_object\": parent_object if parent_object else None, \"success_url\": current_url,", "import TO_FIELD_VAR from django.contrib.admin.utils import unquote from django.urls import reverse, resolve from django.http", "request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) obj = self.get_object(request, unquote(object_id), to_field) if object_id else None context =", "opts, \"app_label\": opts.app_label, \"media\": self.media } request.current_app = self.admin_site.name defaults = { \"extra_context\":", "request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) parent_object = self.get_object(request, unquote(object_id), to_field) if object_id else None context =", "class CompanyAddressFRAdminInline(AddressAdminInline): fields = address_fields + ('is_siege', 'is_active') class BaloAdmin(BaseAdmin): fieldsets = ((None,", "None, \"template_name\": self.search_template or \"admin/company_country_add.html\", } from company.views import AddByCountry return AddByCountry.as_view(**defaults)(request) def", "(\"wide\",), \"fields\": ( 'capital_socnomtotal', 'capital_division', 'current', 'share_capital', 'turnover', 'floating', 'icb', 'market', 'dowjones', 'nasdaq',", "django.contrib.admin.utils import unquote from django.urls import reverse, resolve from django.http import Http404, HttpResponseRedirect", "'stock_min_status' )}), ('sieges', {\"classes\": (\"wide\",), \"fields\": ( 'siege_fr', )})) list_display = ('denomination', 'since',", "\"current_url\": current_url, \"title\": \"%s (%s)\" % (_.countries, obj) if obj else _.countries, \"object_name\":", "admin from django.conf import settings from django.views.decorators.cache import never_cache from django.contrib.admin.options import TO_FIELD_VAR", "opts, \"app_label\": opts.app_label, \"media\": self.media } defaults = { \"extra_context\": context, \"admin\": True,", "= \"admin/company_change_form_logs.html\" readonly_fields = ('siege_fr',) search_template = None def __init__(self, model, admin_site): super().__init__(model,", "import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from mighty.admin.models import BaseAdmin from mighty.applications.address", "context = { **self.admin_site.each_context(request), \"current_url\": current_url, \"title\": \"%s (%s)\" % (_.countries, obj) if", "fields, translates as _ from company.apps import CompanyConfig as conf class CompanyAdmin(BaseAdmin): fieldsets", "CompanyAddressFRAdminInline(AddressAdminInline): fields = address_fields + ('is_siege', 'is_active') class BaloAdmin(BaseAdmin): fieldsets = ((None, {\"classes\":", "\"username\": request.user.get_username(), \"current_url\": current_url, \"country\": country, \"title\": _.search, \"opts\": opts, \"app_label\": opts.app_label, \"media\":", "context, add=False, change=False, form_url=\"\", obj=None): response = super().render_change_form(request, context, add, change, form_url, obj)", "+ urls ##################### # FR ##################### class CompanyFRAdminInline(admin.StackedInline): fields = fields.country + fields.fr", "ChoiceCountry return ChoiceCountry.as_view(**defaults)(request) @never_cache def country_search_view(self, request, country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name", "'icb', 'market', 'dowjones', 'nasdaq', 'gaia' )}), ('rules', {\"classes\": (\"wide\",), \"fields\": ( 'duration_mandate', 'settle_internal',", "obj, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } request.current_app = self.admin_site.name defaults =", "('rules', {\"classes\": (\"wide\",), \"fields\": ( 'duration_mandate', 'settle_internal', 'age_limit_pdg', 'age_limit_dg', 'stock_min_rule', 'stock_min_status' )}), ('sieges',", "country, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts = self.model._meta to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))", "self.country_add_view, name=\"%s_%s_country_add_extend\" % info), ])) ])) ] return my_urls + urls ##################### #", "\"fields\": ( 'capital_socnomtotal', 'capital_division', 'current', 'share_capital', 'turnover', 'floating', 'icb', 'market', 'dowjones', 'nasdaq', 'gaia'", "( 'duration_mandate', 'settle_internal', 'age_limit_pdg', 'age_limit_dg', 'stock_min_rule', 'stock_min_status' )}), ('sieges', {\"classes\": (\"wide\",), \"fields\": (", "\"media\": self.media } defaults = { \"extra_context\": context, \"admin\": True, \"country\": country, \"parent_object\":", "'gaia' )}), ('rules', {\"classes\": (\"wide\",), \"fields\": ( 'duration_mandate', 'settle_internal', 'age_limit_pdg', 'age_limit_dg', 'stock_min_rule', 'stock_min_status'", ")}), ('sieges', {\"classes\": (\"wide\",), \"fields\": ( 'siege_fr', )})) list_display = ('denomination', 'since', 'siege_fr')", "form_url=\"\", obj=None): response = super().render_change_form(request, context, add, change, form_url, obj) if hasattr(self.model, \"changelog_model\"):", "as _ from company.apps import CompanyConfig as conf class CompanyAdmin(BaseAdmin): fieldsets = (", "opts.app_label, \"media\": self.media } request.current_app = self.admin_site.name defaults = { \"extra_context\": context, \"template_name\":", "% info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add\" % info), ])) ])), path(\"<path:object_id>/choices/\", include([ path(\"\", self.country_choice_view,", "path(\"\", self.country_search_view, name=\"%s_%s_country_search\" % info), path(\"add/\", self.country_add_view, name=\"%s_%s_country_add\" % info), ])) ])), path(\"<path:object_id>/choices/\",", "path(\"\", self.country_choice_view, name=\"%s_%s_country_choice\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search\" % info), path(\"add/\",", "path(\"add/\", self.country_add_view, name=\"%s_%s_country_add_extend\" % info), ])) ])) ] return my_urls + urls #####################", "'is_active') class BaloAdmin(BaseAdmin): fieldsets = ((None, {\"classes\": (\"wide\",), \"fields\": fields.balo}),) ##################### # US", "else None, \"success_url\": current_url, \"template_name\": self.search_template or \"admin/company_country_search.html\", } from company.views import SearchByCountry", "current_url, \"title\": \"%s (%s)\" % (_.countries, obj) if obj else _.countries, \"object_name\": str(opts.verbose_name),", "HttpResponseRedirect from django.template.response import TemplateResponse from mighty.admin.models import BaseAdmin from mighty.applications.address import fields", "path(\"\", self.country_choice_view, name=\"%s_%s_country_choice_extend\" % info), path(\"<str:country>/search/\", include([ path(\"\", self.country_search_view, name=\"%s_%s_country_search_extend\" % info), path(\"add/\",", "current_url, \"country\": country, \"title\": _.search, \"opts\": opts, \"app_label\": opts.app_label, \"media\": self.media } defaults", "company.apps import CompanyConfig as conf class CompanyAdmin(BaseAdmin): fieldsets = ( (None, {\"classes\": (\"wide\",),", "= self.admin_site.name defaults = { \"extra_context\": context, \"template_name\": self.search_template or \"admin/company_country_choice.html\", } from", "('denomination', 'since', 'siege_fr') search_fields = (\"denomination\", \"company_fr__siret\") change_list_template = \"admin/company_change_list.html\" change_form_template = \"admin/company_change_form.html\"", "('siege_fr',) search_template = None def __init__(self, model, admin_site): super().__init__(model, admin_site) if conf.named_id: self.readonly_fields", "unquote(object_id), to_field) if object_id else None context = { **self.admin_site.each_context(request), \"parent_object\": parent_object, \"app_path\":", "import SearchByCountry return SearchByCountry.as_view(**defaults)(request=request) @never_cache def country_add_view(self, request, country, object_id=None, extra_context=None): current_url =", "self.model._meta.model_name my_urls = [ path(\"choices/\", include([ path(\"\", self.country_choice_view, name=\"%s_%s_country_choice\" % info), path(\"<str:country>/search/\", include([", "= self.change_form_logs_template return response def country_choice_view(self, request, object_id=None, extra_context=None): current_url = resolve(request.path_info).url_name opts", "as conf class CompanyAdmin(BaseAdmin): fieldsets = ( (None, {\"classes\": (\"wide\",), \"fields\": ('denomination', 'is_type',", "max_num = 0 class CompanyAddressFRAdminInline(AddressAdminInline): fields = address_fields + ('is_siege', 'is_active') class BaloAdmin(BaseAdmin):", ")})) list_display = ('denomination', 'since', 'siege_fr') search_fields = (\"denomination\", \"company_fr__siret\") change_list_template = \"admin/company_change_list.html\"", "list_display = ('denomination', 'since', 'siege_fr') search_fields = (\"denomination\", \"company_fr__siret\") change_list_template = \"admin/company_change_list.html\" change_form_template" ]
[ "and validation output_prefix = os.path.join(target_path, \"{}.filtered\".format(corpus_name)) dictionary_file = output_prefix + \".dictionary\" dictionary.save(dictionary_file) #", ":param corpus_name: name of UCI corpus :param target_path: output directory for dictionary file", "num_documents = len(corpus) num_documents_training = int(training_pct * num_documents) num_documents_validation = num_documents - num_documents_training", "corpus.num_terms)) print(\"dropping top/bottom words in dictionary\") corpus, dictionary = filter_corpus(corpus) # output mm", "\"\"\" Download corpus from UCI website :param corpus_name: :param target_path: :return: \"\"\" url_root", "training: {:,.0f}\".format(num_documents_training)) print(\" num validation: {:,.0f}\".format(num_documents_validation)) print(\" vocab size: {:,.0f}\".format(num_vocab)) # output same", "os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name)) print(\"downloading {} vocab file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file)", "= os.path.join(target_path, \"docword.{}.txt.gz\".format(corpus_name)) print(\"downloading {} bag of words to: {}\".format(corpus_name, docword_file)) urllib.request.urlretrieve(url_root +", "filter_corpus(corpus: UciCorpus) -> (CorpusABC, Dictionary): \"\"\" Filter extreme (frequent and infrequent) words from", "\"docword.{}.txt.gz\".format(corpus_name)) print(\"downloading {} bag of words to: {}\".format(corpus_name, docword_file)) urllib.request.urlretrieve(url_root + \"docword.{}.txt.gz\".format(corpus_name), filename=docword_file)", "num documents: {:,.0f}\".format(num_documents)) print(\" num training: {:,.0f}\".format(num_documents_training)) print(\" num validation: {:,.0f}\".format(num_documents_validation)) print(\" vocab", "import urllib import os from itertools import islice import copy from gensim.models import", "from UCI website :param corpus_name: :param target_path: :return: \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path", "not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file = os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name)) print(\"downloading {}", "validation: {:,.0f}\".format(num_documents_validation)) print(\" vocab size: {:,.0f}\".format(num_vocab)) # output same dictionary for training and", "filtered_dict.filter_extremes(no_below=20, no_above=.1) # now transform the corpus old2new = {original_dict.token2id[token]: new_id for new_id,", "\".dictionary\" dictionary.save(dictionary_file) # training data output_file = output_prefix + \".training.mm\" training_corpus = islice(corpus,", "target_path: str) -> UciCorpus: \"\"\" Download corpus from UCI website :param corpus_name: :param", "MmCorpus.serialize(output_file, training_corpus, dictionary) # validation output_file = output_prefix + \".validation.mm\" validation_corpus = islice(corpus,", "print(\" num validation: {:,.0f}\".format(num_documents_validation)) print(\" vocab size: {:,.0f}\".format(num_vocab)) # output same dictionary for", "Dictionary from gensim.corpora import MmCorpus, UciCorpus from gensim.interfaces import CorpusABC def generate_mmcorpus_files(corpus_name: str,", "corpus.num_docs, corpus.num_terms)) print(\"dropping top/bottom words in dictionary\") corpus, dictionary = filter_corpus(corpus) # output", "target_path = os.path.join(target_path, \"uci\", \"raw\") if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path)", "{}\".format(corpus_name, docword_file)) urllib.request.urlretrieve(url_root + \"docword.{}.txt.gz\".format(corpus_name), filename=docword_file) corpus = UciCorpus(docword_file, vocab_file) return corpus def", "dictionary :param corpus: :return: (filtered corpus, filtered dictionary) \"\"\" # filter dictionary first", "UciCorpus) -> (CorpusABC, Dictionary): \"\"\" Filter extreme (frequent and infrequent) words from dictionary", "line in f: dictionary.add_documents([[line.strip()]]) dictionary.compactify() return dictionary def filter_corpus(corpus: UciCorpus) -> (CorpusABC, Dictionary):", "int(training_pct * num_documents) num_documents_validation = num_documents - num_documents_training num_vocab = len(dictionary) print(\"outputting\") print(\"", "= islice(corpus, num_documents_training, num_documents) MmCorpus.serialize(output_file, validation_corpus, dictionary) def download_corpus(corpus_name: str, target_path: str) ->", ":param target_path: :return: \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"raw\", \"uci\") if", ":return: (filtered corpus, filtered dictionary) \"\"\" # filter dictionary first original_dict = corpus.create_dictionary()", "# output mm files num_documents = len(corpus) num_documents_training = int(training_pct * num_documents) num_documents_validation", "corpus.create_dictionary() filtered_dict = copy.deepcopy(original_dict) filtered_dict.filter_extremes(no_below=20, no_above=.1) # now transform the corpus old2new =", "os.makedirs(target_path) vocab_file = os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name)) print(\"downloading {} vocab file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root", "documents: {:,.0f}\".format(num_documents)) print(\" num training: {:,.0f}\".format(num_documents_training)) print(\" num validation: {:,.0f}\".format(num_documents_validation)) print(\" vocab size:", "old2new = {original_dict.token2id[token]: new_id for new_id, token in filtered_dict.iteritems()} vt = VocabTransform(old2new) return", "data output_file = output_prefix + \".training.mm\" training_corpus = islice(corpus, num_documents_training) MmCorpus.serialize(output_file, training_corpus, dictionary)", "dictionary.save(dictionary_file) # training data output_file = output_prefix + \".training.mm\" training_corpus = islice(corpus, num_documents_training)", "= UciCorpus(docword_file, vocab_file) return corpus def download_dictionary(corpus_name: str, target_path: str) -> Dictionary: \"\"\"", "target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file = os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name)) print(\"downloading {} vocab file to:", "website :param corpus_name: name of UCI corpus :param target_path: output directory for dictionary", "words in dictionary\") corpus, dictionary = filter_corpus(corpus) # output mm files num_documents =", "filename=docword_file) corpus = UciCorpus(docword_file, vocab_file) return corpus def download_dictionary(corpus_name: str, target_path: str) ->", "filename=vocab_file) dictionary = Dictionary() with open(vocab_file) as f: for line in f: dictionary.add_documents([[line.strip()]])", "and validation MM corpus files :param corpus_name: :param target_path: :param training_pct: :return: \"\"\"", "import os from itertools import islice import copy from gensim.models import VocabTransform from", "float = .8): \"\"\" Output training and validation MM corpus files :param corpus_name:", "training data output_file = output_prefix + \".training.mm\" training_corpus = islice(corpus, num_documents_training) MmCorpus.serialize(output_file, training_corpus,", ":return: \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"raw\", \"uci\") if not os.path.exists(target_path):", "{} vocab file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) dictionary = Dictionary()", "corpus_name: :param target_path: :param training_pct: :return: \"\"\" corpus = download_corpus(corpus_name, target_path) print(\"downloaded {}", "now transform the corpus old2new = {original_dict.token2id[token]: new_id for new_id, token in filtered_dict.iteritems()}", "to: {}\".format(corpus_name, docword_file)) urllib.request.urlretrieve(url_root + \"docword.{}.txt.gz\".format(corpus_name), filename=docword_file) corpus = UciCorpus(docword_file, vocab_file) return corpus", "len(dictionary) print(\"outputting\") print(\" num documents: {:,.0f}\".format(num_documents)) print(\" num training: {:,.0f}\".format(num_documents_training)) print(\" num validation:", "corpus from UCI website :param corpus_name: :param target_path: :return: \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\"", "to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) dictionary = Dictionary() with open(vocab_file) as", "in dictionary\") corpus, dictionary = filter_corpus(corpus) # output mm files num_documents = len(corpus)", "= len(dictionary) print(\"outputting\") print(\" num documents: {:,.0f}\".format(num_documents)) print(\" num training: {:,.0f}\".format(num_documents_training)) print(\" num", "\"\"\" Output training and validation MM corpus files :param corpus_name: :param target_path: :param", "directory for dictionary file :return: gensim Dictionary \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path =", "print(\" num documents: {:,.0f}\".format(num_documents)) print(\" num training: {:,.0f}\".format(num_documents_training)) print(\" num validation: {:,.0f}\".format(num_documents_validation)) print(\"", "files num_documents = len(corpus) num_documents_training = int(training_pct * num_documents) num_documents_validation = num_documents -", "validation_corpus = islice(corpus, num_documents_training, num_documents) MmCorpus.serialize(output_file, validation_corpus, dictionary) def download_corpus(corpus_name: str, target_path: str)", "output_prefix = os.path.join(target_path, \"{}.filtered\".format(corpus_name)) dictionary_file = output_prefix + \".dictionary\" dictionary.save(dictionary_file) # training data", "= os.path.join(target_path, \"{}.filtered\".format(corpus_name)) dictionary_file = output_prefix + \".dictionary\" dictionary.save(dictionary_file) # training data output_file", "from gensim.models import VocabTransform from gensim.corpora.dictionary import Dictionary from gensim.corpora import MmCorpus, UciCorpus", "target_path: :return: \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"raw\", \"uci\") if not", "training_pct: float = .8): \"\"\" Output training and validation MM corpus files :param", "print(\"outputting\") print(\" num documents: {:,.0f}\".format(num_documents)) print(\" num training: {:,.0f}\".format(num_documents_training)) print(\" num validation: {:,.0f}\".format(num_documents_validation))", "\"uci\", \"raw\") if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file = os.path.join(target_path,", "return corpus def download_dictionary(corpus_name: str, target_path: str) -> Dictionary: \"\"\" Download dictionary only", "\"vocab.{}.txt\".format(corpus_name), filename=vocab_file) docword_file = os.path.join(target_path, \"docword.{}.txt.gz\".format(corpus_name)) print(\"downloading {} bag of words to: {}\".format(corpus_name,", "# training data output_file = output_prefix + \".training.mm\" training_corpus = islice(corpus, num_documents_training) MmCorpus.serialize(output_file,", "num_documents_training = int(training_pct * num_documents) num_documents_validation = num_documents - num_documents_training num_vocab = len(dictionary)", "Dictionary): \"\"\" Filter extreme (frequent and infrequent) words from dictionary :param corpus: :return:", "os.path.join(target_path, \"docword.{}.txt.gz\".format(corpus_name)) print(\"downloading {} bag of words to: {}\".format(corpus_name, docword_file)) urllib.request.urlretrieve(url_root + \"docword.{}.txt.gz\".format(corpus_name),", "corpus_name: :param target_path: :return: \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"raw\", \"uci\")", "= download_corpus(corpus_name, target_path) print(\"downloaded {} corpus [num_docs={}, num_terms={}]\".format(corpus_name, corpus.num_docs, corpus.num_terms)) print(\"dropping top/bottom words", "training_corpus, dictionary) # validation output_file = output_prefix + \".validation.mm\" validation_corpus = islice(corpus, num_documents_training,", "size: {:,.0f}\".format(num_vocab)) # output same dictionary for training and validation output_prefix = os.path.join(target_path,", "dictionary for training and validation output_prefix = os.path.join(target_path, \"{}.filtered\".format(corpus_name)) dictionary_file = output_prefix +", "os.path.join(target_path, \"raw\", \"uci\") if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file =", "-> UciCorpus: \"\"\" Download corpus from UCI website :param corpus_name: :param target_path: :return:", "training and validation MM corpus files :param corpus_name: :param target_path: :param training_pct: :return:", "vocab_file) return corpus def download_dictionary(corpus_name: str, target_path: str) -> Dictionary: \"\"\" Download dictionary", "corpus from UCI website :param corpus_name: name of UCI corpus :param target_path: output", "gensim Dictionary \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"uci\", \"raw\") if not", "in f: dictionary.add_documents([[line.strip()]]) dictionary.compactify() return dictionary def filter_corpus(corpus: UciCorpus) -> (CorpusABC, Dictionary): \"\"\"", "of words to: {}\".format(corpus_name, docword_file)) urllib.request.urlretrieve(url_root + \"docword.{}.txt.gz\".format(corpus_name), filename=docword_file) corpus = UciCorpus(docword_file, vocab_file)", "gensim.corpora.dictionary import Dictionary from gensim.corpora import MmCorpus, UciCorpus from gensim.interfaces import CorpusABC def", "urllib import os from itertools import islice import copy from gensim.models import VocabTransform", "\"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"uci\", \"raw\") if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path))", "file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) docword_file = os.path.join(target_path, \"docword.{}.txt.gz\".format(corpus_name)) print(\"downloading", "training_pct: :return: \"\"\" corpus = download_corpus(corpus_name, target_path) print(\"downloaded {} corpus [num_docs={}, num_terms={}]\".format(corpus_name, corpus.num_docs,", "\"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"raw\", \"uci\") if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path))", "\"{}.filtered\".format(corpus_name)) dictionary_file = output_prefix + \".dictionary\" dictionary.save(dictionary_file) # training data output_file = output_prefix", "islice(corpus, num_documents_training) MmCorpus.serialize(output_file, training_corpus, dictionary) # validation output_file = output_prefix + \".validation.mm\" validation_corpus", "validation_corpus, dictionary) def download_corpus(corpus_name: str, target_path: str) -> UciCorpus: \"\"\" Download corpus from", "corpus = UciCorpus(docword_file, vocab_file) return corpus def download_dictionary(corpus_name: str, target_path: str) -> Dictionary:", "{} vocab file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) docword_file = os.path.join(target_path,", "corpus [num_docs={}, num_terms={}]\".format(corpus_name, corpus.num_docs, corpus.num_terms)) print(\"dropping top/bottom words in dictionary\") corpus, dictionary =", "os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file = os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name)) print(\"downloading {} vocab", "mm files num_documents = len(corpus) num_documents_training = int(training_pct * num_documents) num_documents_validation = num_documents", "validation MM corpus files :param corpus_name: :param target_path: :param training_pct: :return: \"\"\" corpus", "dictionary first original_dict = corpus.create_dictionary() filtered_dict = copy.deepcopy(original_dict) filtered_dict.filter_extremes(no_below=20, no_above=.1) # now transform", "VocabTransform from gensim.corpora.dictionary import Dictionary from gensim.corpora import MmCorpus, UciCorpus from gensim.interfaces import", "urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) dictionary = Dictionary() with open(vocab_file) as f: for line", ":param corpus_name: :param target_path: :return: \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"raw\",", "= output_prefix + \".validation.mm\" validation_corpus = islice(corpus, num_documents_training, num_documents) MmCorpus.serialize(output_file, validation_corpus, dictionary) def", "num_documents_validation = num_documents - num_documents_training num_vocab = len(dictionary) print(\"outputting\") print(\" num documents: {:,.0f}\".format(num_documents))", "corpus = download_corpus(corpus_name, target_path) print(\"downloaded {} corpus [num_docs={}, num_terms={}]\".format(corpus_name, corpus.num_docs, corpus.num_terms)) print(\"dropping top/bottom", "same dictionary for training and validation output_prefix = os.path.join(target_path, \"{}.filtered\".format(corpus_name)) dictionary_file = output_prefix", "a corpus from UCI website :param corpus_name: name of UCI corpus :param target_path:", "dictionary) \"\"\" # filter dictionary first original_dict = corpus.create_dictionary() filtered_dict = copy.deepcopy(original_dict) filtered_dict.filter_extremes(no_below=20,", "{} corpus [num_docs={}, num_terms={}]\".format(corpus_name, corpus.num_docs, corpus.num_terms)) print(\"dropping top/bottom words in dictionary\") corpus, dictionary", "dictionary = filter_corpus(corpus) # output mm files num_documents = len(corpus) num_documents_training = int(training_pct", "+ \".validation.mm\" validation_corpus = islice(corpus, num_documents_training, num_documents) MmCorpus.serialize(output_file, validation_corpus, dictionary) def download_corpus(corpus_name: str,", "print(\"downloaded {} corpus [num_docs={}, num_terms={}]\".format(corpus_name, corpus.num_docs, corpus.num_terms)) print(\"dropping top/bottom words in dictionary\") corpus,", "= islice(corpus, num_documents_training) MmCorpus.serialize(output_file, training_corpus, dictionary) # validation output_file = output_prefix + \".validation.mm\"", "urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) docword_file = os.path.join(target_path, \"docword.{}.txt.gz\".format(corpus_name)) print(\"downloading {} bag of words", "dictionary def filter_corpus(corpus: UciCorpus) -> (CorpusABC, Dictionary): \"\"\" Filter extreme (frequent and infrequent)", "only for a corpus from UCI website :param corpus_name: name of UCI corpus", "output mm files num_documents = len(corpus) num_documents_training = int(training_pct * num_documents) num_documents_validation =", "len(corpus) num_documents_training = int(training_pct * num_documents) num_documents_validation = num_documents - num_documents_training num_vocab =", "(filtered corpus, filtered dictionary) \"\"\" # filter dictionary first original_dict = corpus.create_dictionary() filtered_dict", "https://archive.ics.uci.edu/ml/datasets.html \"\"\" import urllib import os from itertools import islice import copy from", "\"\"\" # filter dictionary first original_dict = corpus.create_dictionary() filtered_dict = copy.deepcopy(original_dict) filtered_dict.filter_extremes(no_below=20, no_above=.1)", "target_path) print(\"downloaded {} corpus [num_docs={}, num_terms={}]\".format(corpus_name, corpus.num_docs, corpus.num_terms)) print(\"dropping top/bottom words in dictionary\")", "url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"raw\", \"uci\") if not os.path.exists(target_path): print(\"creating target", "num_vocab = len(dictionary) print(\"outputting\") print(\" num documents: {:,.0f}\".format(num_documents)) print(\" num training: {:,.0f}\".format(num_documents_training)) print(\"", "dictionary) def download_corpus(corpus_name: str, target_path: str) -> UciCorpus: \"\"\" Download corpus from UCI", "{:,.0f}\".format(num_documents)) print(\" num training: {:,.0f}\".format(num_documents_training)) print(\" num validation: {:,.0f}\".format(num_documents_validation)) print(\" vocab size: {:,.0f}\".format(num_vocab))", "{}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) docword_file = os.path.join(target_path, \"docword.{}.txt.gz\".format(corpus_name)) print(\"downloading {} bag", "file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) dictionary = Dictionary() with open(vocab_file)", "MmCorpus.serialize(output_file, validation_corpus, dictionary) def download_corpus(corpus_name: str, target_path: str) -> UciCorpus: \"\"\" Download corpus", ":param corpus: :return: (filtered corpus, filtered dictionary) \"\"\" # filter dictionary first original_dict", "print(\" num training: {:,.0f}\".format(num_documents_training)) print(\" num validation: {:,.0f}\".format(num_documents_validation)) print(\" vocab size: {:,.0f}\".format(num_vocab)) #", "- num_documents_training num_vocab = len(dictionary) print(\"outputting\") print(\" num documents: {:,.0f}\".format(num_documents)) print(\" num training:", "print(\"dropping top/bottom words in dictionary\") corpus, dictionary = filter_corpus(corpus) # output mm files", "website :param corpus_name: :param target_path: :return: \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path,", "num validation: {:,.0f}\".format(num_documents_validation)) print(\" vocab size: {:,.0f}\".format(num_vocab)) # output same dictionary for training", "training_corpus = islice(corpus, num_documents_training) MmCorpus.serialize(output_file, training_corpus, dictionary) # validation output_file = output_prefix +", "download_corpus(corpus_name: str, target_path: str) -> UciCorpus: \"\"\" Download corpus from UCI website :param", "\"vocab.{}.txt\".format(corpus_name), filename=vocab_file) dictionary = Dictionary() with open(vocab_file) as f: for line in f:", "from gensim.corpora.dictionary import Dictionary from gensim.corpora import MmCorpus, UciCorpus from gensim.interfaces import CorpusABC", "num_documents_training, num_documents) MmCorpus.serialize(output_file, validation_corpus, dictionary) def download_corpus(corpus_name: str, target_path: str) -> UciCorpus: \"\"\"", "= int(training_pct * num_documents) num_documents_validation = num_documents - num_documents_training num_vocab = len(dictionary) print(\"outputting\")", ":return: gensim Dictionary \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"uci\", \"raw\") if", "= output_prefix + \".dictionary\" dictionary.save(dictionary_file) # training data output_file = output_prefix + \".training.mm\"", "= corpus.create_dictionary() filtered_dict = copy.deepcopy(original_dict) filtered_dict.filter_extremes(no_below=20, no_above=.1) # now transform the corpus old2new", "# output same dictionary for training and validation output_prefix = os.path.join(target_path, \"{}.filtered\".format(corpus_name)) dictionary_file", "\"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"uci\", \"raw\") if not os.path.exists(target_path): print(\"creating", "for line in f: dictionary.add_documents([[line.strip()]]) dictionary.compactify() return dictionary def filter_corpus(corpus: UciCorpus) -> (CorpusABC,", "path: {}\".format(target_path)) os.makedirs(target_path) vocab_file = os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name)) print(\"downloading {} vocab file to: {}\".format(corpus_name,", "{} bag of words to: {}\".format(corpus_name, docword_file)) urllib.request.urlretrieve(url_root + \"docword.{}.txt.gz\".format(corpus_name), filename=docword_file) corpus =", "infrequent) words from dictionary :param corpus: :return: (filtered corpus, filtered dictionary) \"\"\" #", "{}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) dictionary = Dictionary() with open(vocab_file) as f:", "vocab file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) docword_file = os.path.join(target_path, \"docword.{}.txt.gz\".format(corpus_name))", "num_terms={}]\".format(corpus_name, corpus.num_docs, corpus.num_terms)) print(\"dropping top/bottom words in dictionary\") corpus, dictionary = filter_corpus(corpus) #", "corpus files :param corpus_name: :param target_path: :param training_pct: :return: \"\"\" corpus = download_corpus(corpus_name,", "transform the corpus old2new = {original_dict.token2id[token]: new_id for new_id, token in filtered_dict.iteritems()} vt", "corpus def download_dictionary(corpus_name: str, target_path: str) -> Dictionary: \"\"\" Download dictionary only for", "top/bottom words in dictionary\") corpus, dictionary = filter_corpus(corpus) # output mm files num_documents", "for a corpus from UCI website :param corpus_name: name of UCI corpus :param", "url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"uci\", \"raw\") if not os.path.exists(target_path): print(\"creating target", "\"\"\" corpus = download_corpus(corpus_name, target_path) print(\"downloaded {} corpus [num_docs={}, num_terms={}]\".format(corpus_name, corpus.num_docs, corpus.num_terms)) print(\"dropping", "islice(corpus, num_documents_training, num_documents) MmCorpus.serialize(output_file, validation_corpus, dictionary) def download_corpus(corpus_name: str, target_path: str) -> UciCorpus:", "docword_file)) urllib.request.urlretrieve(url_root + \"docword.{}.txt.gz\".format(corpus_name), filename=docword_file) corpus = UciCorpus(docword_file, vocab_file) return corpus def download_dictionary(corpus_name:", "UciCorpus: \"\"\" Download corpus from UCI website :param corpus_name: :param target_path: :return: \"\"\"", "from UCI website :param corpus_name: name of UCI corpus :param target_path: output directory", "{:,.0f}\".format(num_documents_training)) print(\" num validation: {:,.0f}\".format(num_documents_validation)) print(\" vocab size: {:,.0f}\".format(num_vocab)) # output same dictionary", "= \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"uci\", \"raw\") if not os.path.exists(target_path): print(\"creating target path:", "[num_docs={}, num_terms={}]\".format(corpus_name, corpus.num_docs, corpus.num_terms)) print(\"dropping top/bottom words in dictionary\") corpus, dictionary = filter_corpus(corpus)", "+ \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) docword_file = os.path.join(target_path, \"docword.{}.txt.gz\".format(corpus_name)) print(\"downloading {} bag of words to:", "num_documents - num_documents_training num_vocab = len(dictionary) print(\"outputting\") print(\" num documents: {:,.0f}\".format(num_documents)) print(\" num", "Dictionary() with open(vocab_file) as f: for line in f: dictionary.add_documents([[line.strip()]]) dictionary.compactify() return dictionary", "of UCI corpus :param target_path: output directory for dictionary file :return: gensim Dictionary", "UciCorpus(docword_file, vocab_file) return corpus def download_dictionary(corpus_name: str, target_path: str) -> Dictionary: \"\"\" Download", "\"\"\" Download dictionary only for a corpus from UCI website :param corpus_name: name", "print(\"downloading {} vocab file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) docword_file =", "islice import copy from gensim.models import VocabTransform from gensim.corpora.dictionary import Dictionary from gensim.corpora", "corpus :param target_path: output directory for dictionary file :return: gensim Dictionary \"\"\" url_root", "original_dict = corpus.create_dictionary() filtered_dict = copy.deepcopy(original_dict) filtered_dict.filter_extremes(no_below=20, no_above=.1) # now transform the corpus", "\"uci\") if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file = os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name))", "UCI https://archive.ics.uci.edu/ml/datasets.html \"\"\" import urllib import os from itertools import islice import copy", "print(\" vocab size: {:,.0f}\".format(num_vocab)) # output same dictionary for training and validation output_prefix", "os.path.join(target_path, \"{}.filtered\".format(corpus_name)) dictionary_file = output_prefix + \".dictionary\" dictionary.save(dictionary_file) # training data output_file =", "MM corpus files :param corpus_name: :param target_path: :param training_pct: :return: \"\"\" corpus =", "+ \".dictionary\" dictionary.save(dictionary_file) # training data output_file = output_prefix + \".training.mm\" training_corpus =", "first original_dict = corpus.create_dictionary() filtered_dict = copy.deepcopy(original_dict) filtered_dict.filter_extremes(no_below=20, no_above=.1) # now transform the", "file :return: gensim Dictionary \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"uci\", \"raw\")", "target_path: str, training_pct: float = .8): \"\"\" Output training and validation MM corpus", "files :param corpus_name: :param target_path: :param training_pct: :return: \"\"\" corpus = download_corpus(corpus_name, target_path)", "= output_prefix + \".training.mm\" training_corpus = islice(corpus, num_documents_training) MmCorpus.serialize(output_file, training_corpus, dictionary) # validation", "dictionary.compactify() return dictionary def filter_corpus(corpus: UciCorpus) -> (CorpusABC, Dictionary): \"\"\" Filter extreme (frequent", "= os.path.join(target_path, \"raw\", \"uci\") if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file", "def generate_mmcorpus_files(corpus_name: str, target_path: str, training_pct: float = .8): \"\"\" Output training and", "= filter_corpus(corpus) # output mm files num_documents = len(corpus) num_documents_training = int(training_pct *", "output same dictionary for training and validation output_prefix = os.path.join(target_path, \"{}.filtered\".format(corpus_name)) dictionary_file =", "Dictionary \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"uci\", \"raw\") if not os.path.exists(target_path):", "download_corpus(corpus_name, target_path) print(\"downloaded {} corpus [num_docs={}, num_terms={}]\".format(corpus_name, corpus.num_docs, corpus.num_terms)) print(\"dropping top/bottom words in", "\"docword.{}.txt.gz\".format(corpus_name), filename=docword_file) corpus = UciCorpus(docword_file, vocab_file) return corpus def download_dictionary(corpus_name: str, target_path: str)", "str, target_path: str) -> UciCorpus: \"\"\" Download corpus from UCI website :param corpus_name:", "words to: {}\".format(corpus_name, docword_file)) urllib.request.urlretrieve(url_root + \"docword.{}.txt.gz\".format(corpus_name), filename=docword_file) corpus = UciCorpus(docword_file, vocab_file) return", "Download dictionary only for a corpus from UCI website :param corpus_name: name of", "words from dictionary :param corpus: :return: (filtered corpus, filtered dictionary) \"\"\" # filter", "filtered_dict = copy.deepcopy(original_dict) filtered_dict.filter_extremes(no_below=20, no_above=.1) # now transform the corpus old2new = {original_dict.token2id[token]:", "\"\"\" Filter extreme (frequent and infrequent) words from dictionary :param corpus: :return: (filtered", "<filename>tmeval/corpora/generate/uci.py<gh_stars>0 \"\"\" Datasets from UCI https://archive.ics.uci.edu/ml/datasets.html \"\"\" import urllib import os from itertools", "UCI website :param corpus_name: :param target_path: :return: \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path =", "from UCI https://archive.ics.uci.edu/ml/datasets.html \"\"\" import urllib import os from itertools import islice import", "training and validation output_prefix = os.path.join(target_path, \"{}.filtered\".format(corpus_name)) dictionary_file = output_prefix + \".dictionary\" dictionary.save(dictionary_file)", "vocab file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) dictionary = Dictionary() with", "\"raw\") if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file = os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name))", "bag of words to: {}\".format(corpus_name, docword_file)) urllib.request.urlretrieve(url_root + \"docword.{}.txt.gz\".format(corpus_name), filename=docword_file) corpus = UciCorpus(docword_file,", "import CorpusABC def generate_mmcorpus_files(corpus_name: str, target_path: str, training_pct: float = .8): \"\"\" Output", "# now transform the corpus old2new = {original_dict.token2id[token]: new_id for new_id, token in", ":param corpus_name: :param target_path: :param training_pct: :return: \"\"\" corpus = download_corpus(corpus_name, target_path) print(\"downloaded", "itertools import islice import copy from gensim.models import VocabTransform from gensim.corpora.dictionary import Dictionary", "with open(vocab_file) as f: for line in f: dictionary.add_documents([[line.strip()]]) dictionary.compactify() return dictionary def", "= len(corpus) num_documents_training = int(training_pct * num_documents) num_documents_validation = num_documents - num_documents_training num_vocab", "-> (CorpusABC, Dictionary): \"\"\" Filter extreme (frequent and infrequent) words from dictionary :param", "import MmCorpus, UciCorpus from gensim.interfaces import CorpusABC def generate_mmcorpus_files(corpus_name: str, target_path: str, training_pct:", "corpus old2new = {original_dict.token2id[token]: new_id for new_id, token in filtered_dict.iteritems()} vt = VocabTransform(old2new)", "corpus, dictionary = filter_corpus(corpus) # output mm files num_documents = len(corpus) num_documents_training =", "* num_documents) num_documents_validation = num_documents - num_documents_training num_vocab = len(dictionary) print(\"outputting\") print(\" num", "MmCorpus, UciCorpus from gensim.interfaces import CorpusABC def generate_mmcorpus_files(corpus_name: str, target_path: str, training_pct: float", "\".training.mm\" training_corpus = islice(corpus, num_documents_training) MmCorpus.serialize(output_file, training_corpus, dictionary) # validation output_file = output_prefix", "copy from gensim.models import VocabTransform from gensim.corpora.dictionary import Dictionary from gensim.corpora import MmCorpus,", "str, training_pct: float = .8): \"\"\" Output training and validation MM corpus files", "name of UCI corpus :param target_path: output directory for dictionary file :return: gensim", "num_documents) num_documents_validation = num_documents - num_documents_training num_vocab = len(dictionary) print(\"outputting\") print(\" num documents:", "as f: for line in f: dictionary.add_documents([[line.strip()]]) dictionary.compactify() return dictionary def filter_corpus(corpus: UciCorpus)", "output_file = output_prefix + \".training.mm\" training_corpus = islice(corpus, num_documents_training) MmCorpus.serialize(output_file, training_corpus, dictionary) #", "os from itertools import islice import copy from gensim.models import VocabTransform from gensim.corpora.dictionary", "vocab_file = os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name)) print(\"downloading {} vocab file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root +", "num training: {:,.0f}\".format(num_documents_training)) print(\" num validation: {:,.0f}\".format(num_documents_validation)) print(\" vocab size: {:,.0f}\".format(num_vocab)) # output", "UCI corpus :param target_path: output directory for dictionary file :return: gensim Dictionary \"\"\"", "corpus, filtered dictionary) \"\"\" # filter dictionary first original_dict = corpus.create_dictionary() filtered_dict =", "= .8): \"\"\" Output training and validation MM corpus files :param corpus_name: :param", "from gensim.corpora import MmCorpus, UciCorpus from gensim.interfaces import CorpusABC def generate_mmcorpus_files(corpus_name: str, target_path:", "output_prefix + \".validation.mm\" validation_corpus = islice(corpus, num_documents_training, num_documents) MmCorpus.serialize(output_file, validation_corpus, dictionary) def download_corpus(corpus_name:", "+ \"docword.{}.txt.gz\".format(corpus_name), filename=docword_file) corpus = UciCorpus(docword_file, vocab_file) return corpus def download_dictionary(corpus_name: str, target_path:", "Filter extreme (frequent and infrequent) words from dictionary :param corpus: :return: (filtered corpus,", "generate_mmcorpus_files(corpus_name: str, target_path: str, training_pct: float = .8): \"\"\" Output training and validation", "f: dictionary.add_documents([[line.strip()]]) dictionary.compactify() return dictionary def filter_corpus(corpus: UciCorpus) -> (CorpusABC, Dictionary): \"\"\" Filter", "{:,.0f}\".format(num_documents_validation)) print(\" vocab size: {:,.0f}\".format(num_vocab)) # output same dictionary for training and validation", "= os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name)) print(\"downloading {} vocab file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name),", "vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) dictionary = Dictionary() with open(vocab_file) as f: for", "print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file = os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name)) print(\"downloading {} vocab file", "dictionary.add_documents([[line.strip()]]) dictionary.compactify() return dictionary def filter_corpus(corpus: UciCorpus) -> (CorpusABC, Dictionary): \"\"\" Filter extreme", "def download_corpus(corpus_name: str, target_path: str) -> UciCorpus: \"\"\" Download corpus from UCI website", ":param target_path: :param training_pct: :return: \"\"\" corpus = download_corpus(corpus_name, target_path) print(\"downloaded {} corpus", "def download_dictionary(corpus_name: str, target_path: str) -> Dictionary: \"\"\" Download dictionary only for a", "{original_dict.token2id[token]: new_id for new_id, token in filtered_dict.iteritems()} vt = VocabTransform(old2new) return vt[corpus], filtered_dict", "\"\"\" import urllib import os from itertools import islice import copy from gensim.models", "target_path: :param training_pct: :return: \"\"\" corpus = download_corpus(corpus_name, target_path) print(\"downloaded {} corpus [num_docs={},", "UCI website :param corpus_name: name of UCI corpus :param target_path: output directory for", "from itertools import islice import copy from gensim.models import VocabTransform from gensim.corpora.dictionary import", "output_file = output_prefix + \".validation.mm\" validation_corpus = islice(corpus, num_documents_training, num_documents) MmCorpus.serialize(output_file, validation_corpus, dictionary)", "print(\"downloading {} bag of words to: {}\".format(corpus_name, docword_file)) urllib.request.urlretrieve(url_root + \"docword.{}.txt.gz\".format(corpus_name), filename=docword_file) corpus", "(CorpusABC, Dictionary): \"\"\" Filter extreme (frequent and infrequent) words from dictionary :param corpus:", "-> Dictionary: \"\"\" Download dictionary only for a corpus from UCI website :param", ":return: \"\"\" corpus = download_corpus(corpus_name, target_path) print(\"downloaded {} corpus [num_docs={}, num_terms={}]\".format(corpus_name, corpus.num_docs, corpus.num_terms))", "no_above=.1) # now transform the corpus old2new = {original_dict.token2id[token]: new_id for new_id, token", "= \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"raw\", \"uci\") if not os.path.exists(target_path): print(\"creating target path:", "docword_file = os.path.join(target_path, \"docword.{}.txt.gz\".format(corpus_name)) print(\"downloading {} bag of words to: {}\".format(corpus_name, docword_file)) urllib.request.urlretrieve(url_root", "print(\"downloading {} vocab file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) dictionary =", "(frequent and infrequent) words from dictionary :param corpus: :return: (filtered corpus, filtered dictionary)", "gensim.models import VocabTransform from gensim.corpora.dictionary import Dictionary from gensim.corpora import MmCorpus, UciCorpus from", "output directory for dictionary file :return: gensim Dictionary \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path", "open(vocab_file) as f: for line in f: dictionary.add_documents([[line.strip()]]) dictionary.compactify() return dictionary def filter_corpus(corpus:", "extreme (frequent and infrequent) words from dictionary :param corpus: :return: (filtered corpus, filtered", "copy.deepcopy(original_dict) filtered_dict.filter_extremes(no_below=20, no_above=.1) # now transform the corpus old2new = {original_dict.token2id[token]: new_id for", "= {original_dict.token2id[token]: new_id for new_id, token in filtered_dict.iteritems()} vt = VocabTransform(old2new) return vt[corpus],", "\"vocab.{}.txt\".format(corpus_name)) print(\"downloading {} vocab file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) dictionary", "+ \".training.mm\" training_corpus = islice(corpus, num_documents_training) MmCorpus.serialize(output_file, training_corpus, dictionary) # validation output_file =", "\"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"raw\", \"uci\") if not os.path.exists(target_path): print(\"creating", "from gensim.interfaces import CorpusABC def generate_mmcorpus_files(corpus_name: str, target_path: str, training_pct: float = .8):", "target_path = os.path.join(target_path, \"raw\", \"uci\") if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path)", "+ \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) dictionary = Dictionary() with open(vocab_file) as f: for line in", "f: for line in f: dictionary.add_documents([[line.strip()]]) dictionary.compactify() return dictionary def filter_corpus(corpus: UciCorpus) ->", "# filter dictionary first original_dict = corpus.create_dictionary() filtered_dict = copy.deepcopy(original_dict) filtered_dict.filter_extremes(no_below=20, no_above=.1) #", "corpus: :return: (filtered corpus, filtered dictionary) \"\"\" # filter dictionary first original_dict =", "dictionary file :return: gensim Dictionary \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path, \"uci\",", "CorpusABC def generate_mmcorpus_files(corpus_name: str, target_path: str, training_pct: float = .8): \"\"\" Output training", "and infrequent) words from dictionary :param corpus: :return: (filtered corpus, filtered dictionary) \"\"\"", "os.path.join(target_path, \"uci\", \"raw\") if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file =", "if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file = os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name)) print(\"downloading", ".8): \"\"\" Output training and validation MM corpus files :param corpus_name: :param target_path:", "to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) docword_file = os.path.join(target_path, \"docword.{}.txt.gz\".format(corpus_name)) print(\"downloading {}", ":param training_pct: :return: \"\"\" corpus = download_corpus(corpus_name, target_path) print(\"downloaded {} corpus [num_docs={}, num_terms={}]\".format(corpus_name,", "# validation output_file = output_prefix + \".validation.mm\" validation_corpus = islice(corpus, num_documents_training, num_documents) MmCorpus.serialize(output_file,", "filter_corpus(corpus) # output mm files num_documents = len(corpus) num_documents_training = int(training_pct * num_documents)", "\"raw\", \"uci\") if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file = os.path.join(target_path,", "target_path: str) -> Dictionary: \"\"\" Download dictionary only for a corpus from UCI", "dictionary) # validation output_file = output_prefix + \".validation.mm\" validation_corpus = islice(corpus, num_documents_training, num_documents)", "dictionary\") corpus, dictionary = filter_corpus(corpus) # output mm files num_documents = len(corpus) num_documents_training", "filter dictionary first original_dict = corpus.create_dictionary() filtered_dict = copy.deepcopy(original_dict) filtered_dict.filter_extremes(no_below=20, no_above=.1) # now", "import VocabTransform from gensim.corpora.dictionary import Dictionary from gensim.corpora import MmCorpus, UciCorpus from gensim.interfaces", "dictionary only for a corpus from UCI website :param corpus_name: name of UCI", "urllib.request.urlretrieve(url_root + \"docword.{}.txt.gz\".format(corpus_name), filename=docword_file) corpus = UciCorpus(docword_file, vocab_file) return corpus def download_dictionary(corpus_name: str,", "str, target_path: str) -> Dictionary: \"\"\" Download dictionary only for a corpus from", "the corpus old2new = {original_dict.token2id[token]: new_id for new_id, token in filtered_dict.iteritems()} vt =", "{:,.0f}\".format(num_vocab)) # output same dictionary for training and validation output_prefix = os.path.join(target_path, \"{}.filtered\".format(corpus_name))", "\".validation.mm\" validation_corpus = islice(corpus, num_documents_training, num_documents) MmCorpus.serialize(output_file, validation_corpus, dictionary) def download_corpus(corpus_name: str, target_path:", "return dictionary def filter_corpus(corpus: UciCorpus) -> (CorpusABC, Dictionary): \"\"\" Filter extreme (frequent and", "vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) docword_file = os.path.join(target_path, \"docword.{}.txt.gz\".format(corpus_name)) print(\"downloading {} bag of", "Datasets from UCI https://archive.ics.uci.edu/ml/datasets.html \"\"\" import urllib import os from itertools import islice", "Output training and validation MM corpus files :param corpus_name: :param target_path: :param training_pct:", "str) -> Dictionary: \"\"\" Download dictionary only for a corpus from UCI website", "dictionary = Dictionary() with open(vocab_file) as f: for line in f: dictionary.add_documents([[line.strip()]]) dictionary.compactify()", "gensim.corpora import MmCorpus, UciCorpus from gensim.interfaces import CorpusABC def generate_mmcorpus_files(corpus_name: str, target_path: str,", "= copy.deepcopy(original_dict) filtered_dict.filter_extremes(no_below=20, no_above=.1) # now transform the corpus old2new = {original_dict.token2id[token]: new_id", "Download corpus from UCI website :param corpus_name: :param target_path: :return: \"\"\" url_root =", "\"vocab.{}.txt\".format(corpus_name)) print(\"downloading {} vocab file to: {}\".format(corpus_name, vocab_file)) urllib.request.urlretrieve(url_root + \"vocab.{}.txt\".format(corpus_name), filename=vocab_file) docword_file", "gensim.interfaces import CorpusABC def generate_mmcorpus_files(corpus_name: str, target_path: str, training_pct: float = .8): \"\"\"", "num_documents_training) MmCorpus.serialize(output_file, training_corpus, dictionary) # validation output_file = output_prefix + \".validation.mm\" validation_corpus =", "for training and validation output_prefix = os.path.join(target_path, \"{}.filtered\".format(corpus_name)) dictionary_file = output_prefix + \".dictionary\"", "str, target_path: str, training_pct: float = .8): \"\"\" Output training and validation MM", "filtered dictionary) \"\"\" # filter dictionary first original_dict = corpus.create_dictionary() filtered_dict = copy.deepcopy(original_dict)", "corpus_name: name of UCI corpus :param target_path: output directory for dictionary file :return:", "download_dictionary(corpus_name: str, target_path: str) -> Dictionary: \"\"\" Download dictionary only for a corpus", "target_path: output directory for dictionary file :return: gensim Dictionary \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\"", "filename=vocab_file) docword_file = os.path.join(target_path, \"docword.{}.txt.gz\".format(corpus_name)) print(\"downloading {} bag of words to: {}\".format(corpus_name, docword_file))", "= os.path.join(target_path, \"uci\", \"raw\") if not os.path.exists(target_path): print(\"creating target path: {}\".format(target_path)) os.makedirs(target_path) vocab_file", "num_documents_training num_vocab = len(dictionary) print(\"outputting\") print(\" num documents: {:,.0f}\".format(num_documents)) print(\" num training: {:,.0f}\".format(num_documents_training))", "for dictionary file :return: gensim Dictionary \"\"\" url_root = \"https://archive.ics.uci.edu/ml/machine-learning-databases/bag-of-words/\" target_path = os.path.join(target_path,", "output_prefix + \".dictionary\" dictionary.save(dictionary_file) # training data output_file = output_prefix + \".training.mm\" training_corpus", "UciCorpus from gensim.interfaces import CorpusABC def generate_mmcorpus_files(corpus_name: str, target_path: str, training_pct: float =", "{}\".format(target_path)) os.makedirs(target_path) vocab_file = os.path.join(target_path, \"vocab.{}.txt\".format(corpus_name)) print(\"downloading {} vocab file to: {}\".format(corpus_name, vocab_file))", "dictionary_file = output_prefix + \".dictionary\" dictionary.save(dictionary_file) # training data output_file = output_prefix +", "= Dictionary() with open(vocab_file) as f: for line in f: dictionary.add_documents([[line.strip()]]) dictionary.compactify() return", "str) -> UciCorpus: \"\"\" Download corpus from UCI website :param corpus_name: :param target_path:", "validation output_prefix = os.path.join(target_path, \"{}.filtered\".format(corpus_name)) dictionary_file = output_prefix + \".dictionary\" dictionary.save(dictionary_file) # training", "output_prefix + \".training.mm\" training_corpus = islice(corpus, num_documents_training) MmCorpus.serialize(output_file, training_corpus, dictionary) # validation output_file", "Dictionary: \"\"\" Download dictionary only for a corpus from UCI website :param corpus_name:", "import Dictionary from gensim.corpora import MmCorpus, UciCorpus from gensim.interfaces import CorpusABC def generate_mmcorpus_files(corpus_name:", "= num_documents - num_documents_training num_vocab = len(dictionary) print(\"outputting\") print(\" num documents: {:,.0f}\".format(num_documents)) print(\"", "from dictionary :param corpus: :return: (filtered corpus, filtered dictionary) \"\"\" # filter dictionary", "num_documents) MmCorpus.serialize(output_file, validation_corpus, dictionary) def download_corpus(corpus_name: str, target_path: str) -> UciCorpus: \"\"\" Download", "import islice import copy from gensim.models import VocabTransform from gensim.corpora.dictionary import Dictionary from", "import copy from gensim.models import VocabTransform from gensim.corpora.dictionary import Dictionary from gensim.corpora import", ":param target_path: output directory for dictionary file :return: gensim Dictionary \"\"\" url_root =", "vocab size: {:,.0f}\".format(num_vocab)) # output same dictionary for training and validation output_prefix =", "validation output_file = output_prefix + \".validation.mm\" validation_corpus = islice(corpus, num_documents_training, num_documents) MmCorpus.serialize(output_file, validation_corpus,", "def filter_corpus(corpus: UciCorpus) -> (CorpusABC, Dictionary): \"\"\" Filter extreme (frequent and infrequent) words", "\"\"\" Datasets from UCI https://archive.ics.uci.edu/ml/datasets.html \"\"\" import urllib import os from itertools import" ]
[ "= web3fsn.ticketsByAddress(pub_key) #print(Tckts) print('Total number of tickets: ',len(Tckts)) print('\\nor using totalNumberOfTicketsByAddress: ',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n') for", "Tckts = web3fsn.ticketsByAddress(pub_key) #print(Tckts) print('Total number of tickets: ',len(Tckts)) print('\\nor using totalNumberOfTicketsByAddress: ',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n')", "pub_key = \"0x3333333333333333333333333333333333333333\" Tckts = web3fsn.ticketsByAddress(pub_key) #print(Tckts) print('Total number of tickets: ',len(Tckts)) print('\\nor", "# One of 'testnet', or 'mainnet' 'provider' : 'WebSocket', # One of 'WebSocket',", "\"0x3333333333333333333333333333333333333333\" Tckts = web3fsn.ticketsByAddress(pub_key) #print(Tckts) print('Total number of tickets: ',len(Tckts)) print('\\nor using totalNumberOfTicketsByAddress:", "for a in Tckts: tck = Tckts[a] st = datetime.fromtimestamp(tck.StartTime).strftime('%c') ex = datetime.fromtimestamp(tck.ExpireTime).strftime('%c')", "print('\\nor using totalNumberOfTicketsByAddress: ',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n') for a in Tckts: tck = Tckts[a] st =", "print('Total number of tickets: ',len(Tckts)) print('\\nor using totalNumberOfTicketsByAddress: ',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n') for a in Tckts:", "datetime #web3fusion from web3fsnpy import Fsn linkToChain = { 'network' : 'mainnet', #", "Fsn linkToChain = { 'network' : 'mainnet', # One of 'testnet', or 'mainnet'", "= Tckts[a] st = datetime.fromtimestamp(tck.StartTime).strftime('%c') ex = datetime.fromtimestamp(tck.ExpireTime).strftime('%c') print('Block Height: ',tck.Height,' Start Time:", "from web3fsnpy import Fsn linkToChain = { 'network' : 'mainnet', # One of", "'mainnet', # One of 'testnet', or 'mainnet' 'provider' : 'WebSocket', # One of", "{ 'network' : 'mainnet', # One of 'testnet', or 'mainnet' 'provider' : 'WebSocket',", "'testnet', or 'mainnet' 'provider' : 'WebSocket', # One of 'WebSocket', 'HTTP', or 'IPC'", "'mainnet' 'provider' : 'WebSocket', # One of 'WebSocket', 'HTTP', or 'IPC' 'gateway' :", ": 'WebSocket', # One of 'WebSocket', 'HTTP', or 'IPC' 'gateway' : 'wss://mainnetpublicgateway1.fusionnetwork.io:10001', #'gateway'", "of 'WebSocket', 'HTTP', or 'IPC' 'gateway' : 'wss://mainnetpublicgateway1.fusionnetwork.io:10001', #'gateway' : 'wss://testnetpublicgateway1.fusionnetwork.io:10001', } web3fsn", "python3 from datetime import datetime #web3fusion from web3fsnpy import Fsn linkToChain = {", "import datetime #web3fusion from web3fsnpy import Fsn linkToChain = { 'network' : 'mainnet',", ": 'mainnet', # One of 'testnet', or 'mainnet' 'provider' : 'WebSocket', # One", "One of 'testnet', or 'mainnet' 'provider' : 'WebSocket', # One of 'WebSocket', 'HTTP',", "',len(Tckts)) print('\\nor using totalNumberOfTicketsByAddress: ',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n') for a in Tckts: tck = Tckts[a] st", "#web3fusion from web3fsnpy import Fsn linkToChain = { 'network' : 'mainnet', # One", "# One of 'WebSocket', 'HTTP', or 'IPC' 'gateway' : 'wss://mainnetpublicgateway1.fusionnetwork.io:10001', #'gateway' : 'wss://testnetpublicgateway1.fusionnetwork.io:10001',", "'IPC' 'gateway' : 'wss://mainnetpublicgateway1.fusionnetwork.io:10001', #'gateway' : 'wss://testnetpublicgateway1.fusionnetwork.io:10001', } web3fsn = Fsn(linkToChain) pub_key =", "web3fsn = Fsn(linkToChain) pub_key = \"0x3333333333333333333333333333333333333333\" Tckts = web3fsn.ticketsByAddress(pub_key) #print(Tckts) print('Total number of", "'wss://testnetpublicgateway1.fusionnetwork.io:10001', } web3fsn = Fsn(linkToChain) pub_key = \"0x3333333333333333333333333333333333333333\" Tckts = web3fsn.ticketsByAddress(pub_key) #print(Tckts) print('Total", "'gateway' : 'wss://mainnetpublicgateway1.fusionnetwork.io:10001', #'gateway' : 'wss://testnetpublicgateway1.fusionnetwork.io:10001', } web3fsn = Fsn(linkToChain) pub_key = \"0x3333333333333333333333333333333333333333\"", "tickets: ',len(Tckts)) print('\\nor using totalNumberOfTicketsByAddress: ',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n') for a in Tckts: tck = Tckts[a]", "One of 'WebSocket', 'HTTP', or 'IPC' 'gateway' : 'wss://mainnetpublicgateway1.fusionnetwork.io:10001', #'gateway' : 'wss://testnetpublicgateway1.fusionnetwork.io:10001', }", "datetime.fromtimestamp(tck.StartTime).strftime('%c') ex = datetime.fromtimestamp(tck.ExpireTime).strftime('%c') print('Block Height: ',tck.Height,' Start Time: ',st,' Expiry Time: ',ex)", "linkToChain = { 'network' : 'mainnet', # One of 'testnet', or 'mainnet' 'provider'", "'WebSocket', # One of 'WebSocket', 'HTTP', or 'IPC' 'gateway' : 'wss://mainnetpublicgateway1.fusionnetwork.io:10001', #'gateway' :", "web3fsn.ticketsByAddress(pub_key) #print(Tckts) print('Total number of tickets: ',len(Tckts)) print('\\nor using totalNumberOfTicketsByAddress: ',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n') for a", "from datetime import datetime #web3fusion from web3fsnpy import Fsn linkToChain = { 'network'", "#print(Tckts) print('Total number of tickets: ',len(Tckts)) print('\\nor using totalNumberOfTicketsByAddress: ',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n') for a in", "number of tickets: ',len(Tckts)) print('\\nor using totalNumberOfTicketsByAddress: ',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n') for a in Tckts: tck", "using totalNumberOfTicketsByAddress: ',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n') for a in Tckts: tck = Tckts[a] st = datetime.fromtimestamp(tck.StartTime).strftime('%c')", "'WebSocket', 'HTTP', or 'IPC' 'gateway' : 'wss://mainnetpublicgateway1.fusionnetwork.io:10001', #'gateway' : 'wss://testnetpublicgateway1.fusionnetwork.io:10001', } web3fsn =", "'network' : 'mainnet', # One of 'testnet', or 'mainnet' 'provider' : 'WebSocket', #", "} web3fsn = Fsn(linkToChain) pub_key = \"0x3333333333333333333333333333333333333333\" Tckts = web3fsn.ticketsByAddress(pub_key) #print(Tckts) print('Total number", "web3fsnpy import Fsn linkToChain = { 'network' : 'mainnet', # One of 'testnet',", "a in Tckts: tck = Tckts[a] st = datetime.fromtimestamp(tck.StartTime).strftime('%c') ex = datetime.fromtimestamp(tck.ExpireTime).strftime('%c') print('Block", "= { 'network' : 'mainnet', # One of 'testnet', or 'mainnet' 'provider' :", "'HTTP', or 'IPC' 'gateway' : 'wss://mainnetpublicgateway1.fusionnetwork.io:10001', #'gateway' : 'wss://testnetpublicgateway1.fusionnetwork.io:10001', } web3fsn = Fsn(linkToChain)", "#'gateway' : 'wss://testnetpublicgateway1.fusionnetwork.io:10001', } web3fsn = Fsn(linkToChain) pub_key = \"0x3333333333333333333333333333333333333333\" Tckts = web3fsn.ticketsByAddress(pub_key)", "= \"0x3333333333333333333333333333333333333333\" Tckts = web3fsn.ticketsByAddress(pub_key) #print(Tckts) print('Total number of tickets: ',len(Tckts)) print('\\nor using", "of tickets: ',len(Tckts)) print('\\nor using totalNumberOfTicketsByAddress: ',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n') for a in Tckts: tck =", "in Tckts: tck = Tckts[a] st = datetime.fromtimestamp(tck.StartTime).strftime('%c') ex = datetime.fromtimestamp(tck.ExpireTime).strftime('%c') print('Block Height:", "tck = Tckts[a] st = datetime.fromtimestamp(tck.StartTime).strftime('%c') ex = datetime.fromtimestamp(tck.ExpireTime).strftime('%c') print('Block Height: ',tck.Height,' Start", "totalNumberOfTicketsByAddress: ',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n') for a in Tckts: tck = Tckts[a] st = datetime.fromtimestamp(tck.StartTime).strftime('%c') ex", "st = datetime.fromtimestamp(tck.StartTime).strftime('%c') ex = datetime.fromtimestamp(tck.ExpireTime).strftime('%c') print('Block Height: ',tck.Height,' Start Time: ',st,' Expiry", ": 'wss://mainnetpublicgateway1.fusionnetwork.io:10001', #'gateway' : 'wss://testnetpublicgateway1.fusionnetwork.io:10001', } web3fsn = Fsn(linkToChain) pub_key = \"0x3333333333333333333333333333333333333333\" Tckts", ": 'wss://testnetpublicgateway1.fusionnetwork.io:10001', } web3fsn = Fsn(linkToChain) pub_key = \"0x3333333333333333333333333333333333333333\" Tckts = web3fsn.ticketsByAddress(pub_key) #print(Tckts)", "or 'mainnet' 'provider' : 'WebSocket', # One of 'WebSocket', 'HTTP', or 'IPC' 'gateway'", "datetime import datetime #web3fusion from web3fsnpy import Fsn linkToChain = { 'network' :", "'provider' : 'WebSocket', # One of 'WebSocket', 'HTTP', or 'IPC' 'gateway' : 'wss://mainnetpublicgateway1.fusionnetwork.io:10001',", "of 'testnet', or 'mainnet' 'provider' : 'WebSocket', # One of 'WebSocket', 'HTTP', or", "= datetime.fromtimestamp(tck.StartTime).strftime('%c') ex = datetime.fromtimestamp(tck.ExpireTime).strftime('%c') print('Block Height: ',tck.Height,' Start Time: ',st,' Expiry Time:", "import Fsn linkToChain = { 'network' : 'mainnet', # One of 'testnet', or", "or 'IPC' 'gateway' : 'wss://mainnetpublicgateway1.fusionnetwork.io:10001', #'gateway' : 'wss://testnetpublicgateway1.fusionnetwork.io:10001', } web3fsn = Fsn(linkToChain) pub_key", "#!/usr/bin/env python3 from datetime import datetime #web3fusion from web3fsnpy import Fsn linkToChain =", "Tckts[a] st = datetime.fromtimestamp(tck.StartTime).strftime('%c') ex = datetime.fromtimestamp(tck.ExpireTime).strftime('%c') print('Block Height: ',tck.Height,' Start Time: ',st,'", "'wss://mainnetpublicgateway1.fusionnetwork.io:10001', #'gateway' : 'wss://testnetpublicgateway1.fusionnetwork.io:10001', } web3fsn = Fsn(linkToChain) pub_key = \"0x3333333333333333333333333333333333333333\" Tckts =", "= Fsn(linkToChain) pub_key = \"0x3333333333333333333333333333333333333333\" Tckts = web3fsn.ticketsByAddress(pub_key) #print(Tckts) print('Total number of tickets:", "Tckts: tck = Tckts[a] st = datetime.fromtimestamp(tck.StartTime).strftime('%c') ex = datetime.fromtimestamp(tck.ExpireTime).strftime('%c') print('Block Height: ',tck.Height,'", "Fsn(linkToChain) pub_key = \"0x3333333333333333333333333333333333333333\" Tckts = web3fsn.ticketsByAddress(pub_key) #print(Tckts) print('Total number of tickets: ',len(Tckts))", "',web3fsn.totalNumberOfTicketsByAddress(pub_key),'\\n') for a in Tckts: tck = Tckts[a] st = datetime.fromtimestamp(tck.StartTime).strftime('%c') ex =" ]
[ "links'.format(day)) print('----------------------') if rx_list is None: rx_list=dct[day].keys() for rx in rx_list: print('Rx {}", "= dct[day][rx][tx_g][1] total_size= total_size + dct[day][rx][tx_g][2] print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk)) print('') print('') print('') print('Total download size", "def provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)): total_size = 0 with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) for", "import pickle import os import scipy.optimize # In[3]: import os GPU = \"\"", "dct[day].keys(): for tx_g in tx_groups: if tx_g in dct[day][rx].keys(): lnk = dct[day][rx][tx_g][1] total_size=", "provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)): total_size = 0 with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) for day", "# In[9]: with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) # In[7]: print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH')) #", "lnk = dct[day][rx][tx_g][1] total_size= total_size + dct[day][rx][tx_g][2] print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk)) print('') print('') print('') print('Total download", "dct = pickle.load(f) for day in day_list: print('Day {} links'.format(day)) print('----------------------') if rx_list", "as plt import numpy as np import pickle import os import scipy.optimize #", "with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) for day in day_list: print('Day {}", "utf-8 # In[2]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import matplotlib.pyplot as plt import numpy", "<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # In[2]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import", "In[17]: def provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)): total_size = 0 with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f)", "os import scipy.optimize # In[3]: import os GPU = \"\" os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU #", "pickle.load(f) for day in day_list: print('Day {} links'.format(day)) print('----------------------') if rx_list is None:", "rx in rx_list: print('Rx {} links'.format(rx)) if rx in dct[day].keys(): for tx_g in", "rx_list: print('Rx {} links'.format(rx)) if rx in dct[day].keys(): for tx_g in tx_groups: if", "print('----------------------') if rx_list is None: rx_list=dct[day].keys() for rx in rx_list: print('Rx {} links'.format(rx))", "dct[day][rx][tx_g][2] print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk)) print('') print('') print('') print('Total download size is {} GB'.format(total_size/1e9)) # In[22]:", "# In[7]: print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH')) # In[17]: def provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)): total_size = 0 with open('raw_info_dct.pkl','rb') as", "# In[2]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import matplotlib.pyplot as plt import numpy as", "tx_groups: if tx_g in dct[day][rx].keys(): lnk = dct[day][rx][tx_g][1] total_size= total_size + dct[day][rx][tx_g][2] print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk))", "links'.format(rx)) if rx in dct[day].keys(): for tx_g in tx_groups: if tx_g in dct[day][rx].keys():", "pickle import os import scipy.optimize # In[3]: import os GPU = \"\" os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"", "In[9]: with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) # In[7]: print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH')) # In[17]:", "python # coding: utf-8 # In[2]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import matplotlib.pyplot as", "if rx_list is None: rx_list=dct[day].keys() for rx in rx_list: print('Rx {} links'.format(rx)) if", "dct[day][rx].keys(): lnk = dct[day][rx][tx_g][1] total_size= total_size + dct[day][rx][tx_g][2] print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk)) print('') print('') print('') print('Total", "print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH')) # In[17]: def provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)): total_size = 0 with open('raw_info_dct.pkl','rb') as f: dct", "is None: rx_list=dct[day].keys() for rx in rx_list: print('Rx {} links'.format(rx)) if rx in", "total_size = 0 with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) for day in", "{} links'.format(day)) print('----------------------') if rx_list is None: rx_list=dct[day].keys() for rx in rx_list: print('Rx", "total_size + dct[day][rx][tx_g][2] print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk)) print('') print('') print('') print('Total download size is {} GB'.format(total_size/1e9))", "#!/usr/bin/env python # coding: utf-8 # In[2]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import matplotlib.pyplot", "as np import pickle import os import scipy.optimize # In[3]: import os GPU", "GPU = \"\" os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU # In[9]: with open('raw_info_dct.pkl','rb') as f: dct =", "= pickle.load(f) for day in day_list: print('Day {} links'.format(day)) print('----------------------') if rx_list is", "numpy as np import pickle import os import scipy.optimize # In[3]: import os", "tx_g in dct[day][rx].keys(): lnk = dct[day][rx][tx_g][1] total_size= total_size + dct[day][rx][tx_g][2] print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk)) print('') print('')", "dct[day][rx][tx_g][1] total_size= total_size + dct[day][rx][tx_g][2] print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk)) print('') print('') print('') print('Total download size is", "coding: utf-8 # In[2]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import matplotlib.pyplot as plt import", "as f: dct = pickle.load(f) # In[7]: print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH')) # In[17]: def provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)): total_size", "rx_list=dct[day].keys() for rx in rx_list: print('Rx {} links'.format(rx)) if rx in dct[day].keys(): for", "open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) # In[7]: print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH')) # In[17]: def provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)):", "# In[17]: def provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)): total_size = 0 with open('raw_info_dct.pkl','rb') as f: dct =", "dct = pickle.load(f) # In[7]: print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH')) # In[17]: def provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)): total_size = 0", "In[3]: import os GPU = \"\" os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU # In[9]: with open('raw_info_dct.pkl','rb') as", "if rx in dct[day].keys(): for tx_g in tx_groups: if tx_g in dct[day][rx].keys(): lnk", "print('') print('') print('') print('Total download size is {} GB'.format(total_size/1e9)) # In[22]: provide_links() #", "for day in day_list: print('Day {} links'.format(day)) print('----------------------') if rx_list is None: rx_list=dct[day].keys()", "None: rx_list=dct[day].keys() for rx in rx_list: print('Rx {} links'.format(rx)) if rx in dct[day].keys():", "# In[3]: import os GPU = \"\" os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU # In[9]: with open('raw_info_dct.pkl','rb')", "= 0 with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) for day in day_list:", "rx_list is None: rx_list=dct[day].keys() for rx in rx_list: print('Rx {} links'.format(rx)) if rx", "print('') print('Total download size is {} GB'.format(total_size/1e9)) # In[22]: provide_links() # In[ ]:", "as f: dct = pickle.load(f) for day in day_list: print('Day {} links'.format(day)) print('----------------------')", "0 with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) for day in day_list: print('Day", "f: dct = pickle.load(f) # In[7]: print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH')) # In[17]: def provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)): total_size =", "in day_list: print('Day {} links'.format(day)) print('----------------------') if rx_list is None: rx_list=dct[day].keys() for rx", "matplotlib.pyplot as plt import numpy as np import pickle import os import scipy.optimize", "np import pickle import os import scipy.optimize # In[3]: import os GPU =", "get_ipython().run_line_magic('autoreload', '2') import matplotlib.pyplot as plt import numpy as np import pickle import", "import scipy.optimize # In[3]: import os GPU = \"\" os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU # In[9]:", "day_list: print('Day {} links'.format(day)) print('----------------------') if rx_list is None: rx_list=dct[day].keys() for rx in", "in rx_list: print('Rx {} links'.format(rx)) if rx in dct[day].keys(): for tx_g in tx_groups:", "if tx_g in dct[day][rx].keys(): lnk = dct[day][rx][tx_g][1] total_size= total_size + dct[day][rx][tx_g][2] print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk)) print('')", "total_size= total_size + dct[day][rx][tx_g][2] print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk)) print('') print('') print('') print('Total download size is {}", "print('Rx {} links'.format(rx)) if rx in dct[day].keys(): for tx_g in tx_groups: if tx_g", "print('') print('') print('Total download size is {} GB'.format(total_size/1e9)) # In[22]: provide_links() # In[", "import os GPU = \"\" os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU # In[9]: with open('raw_info_dct.pkl','rb') as f:", "'2') import matplotlib.pyplot as plt import numpy as np import pickle import os", "{} links'.format(rx)) if rx in dct[day].keys(): for tx_g in tx_groups: if tx_g in", "f: dct = pickle.load(f) for day in day_list: print('Day {} links'.format(day)) print('----------------------') if", "for rx in rx_list: print('Rx {} links'.format(rx)) if rx in dct[day].keys(): for tx_g", "in dct[day][rx].keys(): lnk = dct[day][rx][tx_g][1] total_size= total_size + dct[day][rx][tx_g][2] print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk)) print('') print('') print('')", "import numpy as np import pickle import os import scipy.optimize # In[3]: import", "for tx_g in tx_groups: if tx_g in dct[day][rx].keys(): lnk = dct[day][rx][tx_g][1] total_size= total_size", "os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU # In[9]: with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) # In[7]:", "tx_g in tx_groups: if tx_g in dct[day][rx].keys(): lnk = dct[day][rx][tx_g][1] total_size= total_size +", "in tx_groups: if tx_g in dct[day][rx].keys(): lnk = dct[day][rx][tx_g][1] total_size= total_size + dct[day][rx][tx_g][2]", "print('Day {} links'.format(day)) print('----------------------') if rx_list is None: rx_list=dct[day].keys() for rx in rx_list:", "with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) # In[7]: print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH')) # In[17]: def", "get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import matplotlib.pyplot as plt import numpy as np import", "# coding: utf-8 # In[2]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import matplotlib.pyplot as plt", "print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk)) print('') print('') print('') print('Total download size is {} GB'.format(total_size/1e9)) # In[22]: provide_links()", "\"\" os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU # In[9]: with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) #", "rx in dct[day].keys(): for tx_g in tx_groups: if tx_g in dct[day][rx].keys(): lnk =", "day in day_list: print('Day {} links'.format(day)) print('----------------------') if rx_list is None: rx_list=dct[day].keys() for", "In[7]: print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH')) # In[17]: def provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)): total_size = 0 with open('raw_info_dct.pkl','rb') as f:", "in dct[day].keys(): for tx_g in tx_groups: if tx_g in dct[day][rx].keys(): lnk = dct[day][rx][tx_g][1]", "scipy.optimize # In[3]: import os GPU = \"\" os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU # In[9]: with", "import matplotlib.pyplot as plt import numpy as np import pickle import os import", "+ dct[day][rx][tx_g][2] print('https://drive.google.com/u/0/uc?export=download&id={}'.format(lnk)) print('') print('') print('') print('Total download size is {} GB'.format(total_size/1e9)) #", "In[2]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import matplotlib.pyplot as plt import numpy as np", "open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) for day in day_list: print('Day {} links'.format(day))", "plt import numpy as np import pickle import os import scipy.optimize # In[3]:", "pickle.load(f) # In[7]: print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH')) # In[17]: def provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)): total_size = 0 with open('raw_info_dct.pkl','rb')", "'autoreload') get_ipython().run_line_magic('autoreload', '2') import matplotlib.pyplot as plt import numpy as np import pickle", "= pickle.load(f) # In[7]: print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH')) # In[17]: def provide_links(day_list=['2021_03_01','2021_03_08','2021_03_15','2021_03_23'],rx_list=None,tx_groups=range(10)): total_size = 0 with", "import os import scipy.optimize # In[3]: import os GPU = \"\" os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU", "os GPU = \"\" os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU # In[9]: with open('raw_info_dct.pkl','rb') as f: dct", "os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU # In[9]: with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f) # In[7]: print('https://drive.google.com/u/0/uc?export=download&id={}'.format('1bQbswsPLZy5lSe5Lu_IpRoaV4wtlcLBH'))", "= \"\" os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" os.environ[\"CUDA_VISIBLE_DEVICES\"]=GPU # In[9]: with open('raw_info_dct.pkl','rb') as f: dct = pickle.load(f)" ]
[ "or new_date.day != old_date.day: self.stream.write(self.render_date(new_date)) # Now write the Original Content content =", "re import datetime class DateFoldStreamProxy: old_date = None date_re = re.compile(r\"(?P<year>\\d\\d\\d\\d)-(?P<month>\\d\\d)-(?P<day>\\d\\d).*\") def __init__(self,", "__init__(self, stream): self.stream = stream def close(self): self.stream.close() def render_month(self, date: datetime.date): return", "import re import datetime class DateFoldStreamProxy: old_date = None date_re = re.compile(r\"(?P<year>\\d\\d\\d\\d)-(?P<month>\\d\\d)-(?P<day>\\d\\d).*\") def", "self.stream.close() def render_month(self, date: datetime.date): return f\"* {date.strftime('%B %Y')}\\n\" def render_date(self, date: datetime.date):", "datetime.date(**g) old_date = self.old_date self.old_date = new_date if not old_date or new_date.month !=", "v in match.groupdict().items()) new_date = datetime.date(**g) old_date = self.old_date self.old_date = new_date if", "{date.strftime('%B %Y')}\\n\" def render_date(self, date: datetime.date): return f\"** {date.strftime('%Y-%m-%d - %A')}\\n\" def write(self,", "dict((k, int(v)) for k, v in match.groupdict().items()) new_date = datetime.date(**g) old_date = self.old_date", "not old_date or new_date.day != old_date.day: self.stream.write(self.render_date(new_date)) # Now write the Original Content", "or new_date.month != old_date.month: self.stream.write(self.render_month(new_date)) if not old_date or new_date.day != old_date.day: self.stream.write(self.render_date(new_date))", "for k, v in match.groupdict().items()) new_date = datetime.date(**g) old_date = self.old_date self.old_date =", "int(v)) for k, v in match.groupdict().items()) new_date = datetime.date(**g) old_date = self.old_date self.old_date", "= datetime.date(**g) old_date = self.old_date self.old_date = new_date if not old_date or new_date.month", "if not old_date or new_date.day != old_date.day: self.stream.write(self.render_date(new_date)) # Now write the Original", "close(self): self.stream.close() def render_month(self, date: datetime.date): return f\"* {date.strftime('%B %Y')}\\n\" def render_date(self, date:", "f\"** {date.strftime('%Y-%m-%d - %A')}\\n\" def write(self, content): match = self.date_re.match(content) if match: g", "render_month(self, date: datetime.date): return f\"* {date.strftime('%B %Y')}\\n\" def render_date(self, date: datetime.date): return f\"**", "class DateFoldStreamProxy: old_date = None date_re = re.compile(r\"(?P<year>\\d\\d\\d\\d)-(?P<month>\\d\\d)-(?P<day>\\d\\d).*\") def __init__(self, stream): self.stream =", "if not old_date or new_date.month != old_date.month: self.stream.write(self.render_month(new_date)) if not old_date or new_date.day", "g = dict((k, int(v)) for k, v in match.groupdict().items()) new_date = datetime.date(**g) old_date", "old_date or new_date.month != old_date.month: self.stream.write(self.render_month(new_date)) if not old_date or new_date.day != old_date.day:", "stream def close(self): self.stream.close() def render_month(self, date: datetime.date): return f\"* {date.strftime('%B %Y')}\\n\" def", "def close(self): self.stream.close() def render_month(self, date: datetime.date): return f\"* {date.strftime('%B %Y')}\\n\" def render_date(self,", "datetime.date): return f\"* {date.strftime('%B %Y')}\\n\" def render_date(self, date: datetime.date): return f\"** {date.strftime('%Y-%m-%d -", "datetime.date): return f\"** {date.strftime('%Y-%m-%d - %A')}\\n\" def write(self, content): match = self.date_re.match(content) if", "return f\"* {date.strftime('%B %Y')}\\n\" def render_date(self, date: datetime.date): return f\"** {date.strftime('%Y-%m-%d - %A')}\\n\"", "new_date.month != old_date.month: self.stream.write(self.render_month(new_date)) if not old_date or new_date.day != old_date.day: self.stream.write(self.render_date(new_date)) #", "def write(self, content): match = self.date_re.match(content) if match: g = dict((k, int(v)) for", "self.date_re.match(content) if match: g = dict((k, int(v)) for k, v in match.groupdict().items()) new_date", "not old_date or new_date.month != old_date.month: self.stream.write(self.render_month(new_date)) if not old_date or new_date.day !=", "date: datetime.date): return f\"** {date.strftime('%Y-%m-%d - %A')}\\n\" def write(self, content): match = self.date_re.match(content)", "= self.old_date self.old_date = new_date if not old_date or new_date.month != old_date.month: self.stream.write(self.render_month(new_date))", "!= old_date.month: self.stream.write(self.render_month(new_date)) if not old_date or new_date.day != old_date.day: self.stream.write(self.render_date(new_date)) # Now", "def render_date(self, date: datetime.date): return f\"** {date.strftime('%Y-%m-%d - %A')}\\n\" def write(self, content): match", "self.stream = stream def close(self): self.stream.close() def render_month(self, date: datetime.date): return f\"* {date.strftime('%B", "match: g = dict((k, int(v)) for k, v in match.groupdict().items()) new_date = datetime.date(**g)", "date: datetime.date): return f\"* {date.strftime('%B %Y')}\\n\" def render_date(self, date: datetime.date): return f\"** {date.strftime('%Y-%m-%d", "in match.groupdict().items()) new_date = datetime.date(**g) old_date = self.old_date self.old_date = new_date if not", "self.stream.write(self.render_month(new_date)) if not old_date or new_date.day != old_date.day: self.stream.write(self.render_date(new_date)) # Now write the", "render_date(self, date: datetime.date): return f\"** {date.strftime('%Y-%m-%d - %A')}\\n\" def write(self, content): match =", "return f\"** {date.strftime('%Y-%m-%d - %A')}\\n\" def write(self, content): match = self.date_re.match(content) if match:", "old_date.month: self.stream.write(self.render_month(new_date)) if not old_date or new_date.day != old_date.day: self.stream.write(self.render_date(new_date)) # Now write", "%Y')}\\n\" def render_date(self, date: datetime.date): return f\"** {date.strftime('%Y-%m-%d - %A')}\\n\" def write(self, content):", "stream): self.stream = stream def close(self): self.stream.close() def render_month(self, date: datetime.date): return f\"*", "old_date = self.old_date self.old_date = new_date if not old_date or new_date.month != old_date.month:", "new_date if not old_date or new_date.month != old_date.month: self.stream.write(self.render_month(new_date)) if not old_date or", "old_date = None date_re = re.compile(r\"(?P<year>\\d\\d\\d\\d)-(?P<month>\\d\\d)-(?P<day>\\d\\d).*\") def __init__(self, stream): self.stream = stream def", "= new_date if not old_date or new_date.month != old_date.month: self.stream.write(self.render_month(new_date)) if not old_date", "match = self.date_re.match(content) if match: g = dict((k, int(v)) for k, v in", "import datetime class DateFoldStreamProxy: old_date = None date_re = re.compile(r\"(?P<year>\\d\\d\\d\\d)-(?P<month>\\d\\d)-(?P<day>\\d\\d).*\") def __init__(self, stream):", "{date.strftime('%Y-%m-%d - %A')}\\n\" def write(self, content): match = self.date_re.match(content) if match: g =", "DateFoldStreamProxy: old_date = None date_re = re.compile(r\"(?P<year>\\d\\d\\d\\d)-(?P<month>\\d\\d)-(?P<day>\\d\\d).*\") def __init__(self, stream): self.stream = stream", "def render_month(self, date: datetime.date): return f\"* {date.strftime('%B %Y')}\\n\" def render_date(self, date: datetime.date): return", "= re.compile(r\"(?P<year>\\d\\d\\d\\d)-(?P<month>\\d\\d)-(?P<day>\\d\\d).*\") def __init__(self, stream): self.stream = stream def close(self): self.stream.close() def render_month(self,", "!= old_date.day: self.stream.write(self.render_date(new_date)) # Now write the Original Content content = re.sub(r'\\s+\\n', r'\\n',", "new_date.day != old_date.day: self.stream.write(self.render_date(new_date)) # Now write the Original Content content = re.sub(r'\\s+\\n',", "# Now write the Original Content content = re.sub(r'\\s+\\n', r'\\n', content, 999) self.stream.write(content)", "self.old_date = new_date if not old_date or new_date.month != old_date.month: self.stream.write(self.render_month(new_date)) if not", "None date_re = re.compile(r\"(?P<year>\\d\\d\\d\\d)-(?P<month>\\d\\d)-(?P<day>\\d\\d).*\") def __init__(self, stream): self.stream = stream def close(self): self.stream.close()", "self.old_date self.old_date = new_date if not old_date or new_date.month != old_date.month: self.stream.write(self.render_month(new_date)) if", "write(self, content): match = self.date_re.match(content) if match: g = dict((k, int(v)) for k,", "content): match = self.date_re.match(content) if match: g = dict((k, int(v)) for k, v", "if match: g = dict((k, int(v)) for k, v in match.groupdict().items()) new_date =", "= self.date_re.match(content) if match: g = dict((k, int(v)) for k, v in match.groupdict().items())", "re.compile(r\"(?P<year>\\d\\d\\d\\d)-(?P<month>\\d\\d)-(?P<day>\\d\\d).*\") def __init__(self, stream): self.stream = stream def close(self): self.stream.close() def render_month(self, date:", "= dict((k, int(v)) for k, v in match.groupdict().items()) new_date = datetime.date(**g) old_date =", "datetime class DateFoldStreamProxy: old_date = None date_re = re.compile(r\"(?P<year>\\d\\d\\d\\d)-(?P<month>\\d\\d)-(?P<day>\\d\\d).*\") def __init__(self, stream): self.stream", "= stream def close(self): self.stream.close() def render_month(self, date: datetime.date): return f\"* {date.strftime('%B %Y')}\\n\"", "%A')}\\n\" def write(self, content): match = self.date_re.match(content) if match: g = dict((k, int(v))", "old_date or new_date.day != old_date.day: self.stream.write(self.render_date(new_date)) # Now write the Original Content content", "match.groupdict().items()) new_date = datetime.date(**g) old_date = self.old_date self.old_date = new_date if not old_date", "new_date = datetime.date(**g) old_date = self.old_date self.old_date = new_date if not old_date or", "def __init__(self, stream): self.stream = stream def close(self): self.stream.close() def render_month(self, date: datetime.date):", "- %A')}\\n\" def write(self, content): match = self.date_re.match(content) if match: g = dict((k,", "old_date.day: self.stream.write(self.render_date(new_date)) # Now write the Original Content content = re.sub(r'\\s+\\n', r'\\n', content,", "self.stream.write(self.render_date(new_date)) # Now write the Original Content content = re.sub(r'\\s+\\n', r'\\n', content, 999)", "f\"* {date.strftime('%B %Y')}\\n\" def render_date(self, date: datetime.date): return f\"** {date.strftime('%Y-%m-%d - %A')}\\n\" def", "k, v in match.groupdict().items()) new_date = datetime.date(**g) old_date = self.old_date self.old_date = new_date", "= None date_re = re.compile(r\"(?P<year>\\d\\d\\d\\d)-(?P<month>\\d\\d)-(?P<day>\\d\\d).*\") def __init__(self, stream): self.stream = stream def close(self):", "date_re = re.compile(r\"(?P<year>\\d\\d\\d\\d)-(?P<month>\\d\\d)-(?P<day>\\d\\d).*\") def __init__(self, stream): self.stream = stream def close(self): self.stream.close() def" ]
[ "= r[0].strip() y = r[1].strip() example = ef.extractFeatures(x) result = '{0},{1}\\n'.format( np.array2string(example, separator=','),", "for line in input_file: r = line.split(',') x = r[0].strip() y = r[1].strip()", "'{0},{1}\\n'.format( np.array2string(example, separator=','), y ) result = result.replace('[','') result = result.replace(']','') result =", "as ef import numpy as np with open('./input.csv','r',encoding='utf-8') as input_file: with open('./dataset.csv','w',encoding='utf-8') as", "ef.extractFeatures(x) result = '{0},{1}\\n'.format( np.array2string(example, separator=','), y ) result = result.replace('[','') result =", "as np with open('./input.csv','r',encoding='utf-8') as input_file: with open('./dataset.csv','w',encoding='utf-8') as dataset: for line in", "open('./input.csv','r',encoding='utf-8') as input_file: with open('./dataset.csv','w',encoding='utf-8') as dataset: for line in input_file: r =", "dataset: for line in input_file: r = line.split(',') x = r[0].strip() y =", "= r[1].strip() example = ef.extractFeatures(x) result = '{0},{1}\\n'.format( np.array2string(example, separator=','), y ) result", "np.array2string(example, separator=','), y ) result = result.replace('[','') result = result.replace(']','') result = result.replace('", "y ) result = result.replace('[','') result = result.replace(']','') result = result.replace(' ','') dataset.write(result)", "x = r[0].strip() y = r[1].strip() example = ef.extractFeatures(x) result = '{0},{1}\\n'.format( np.array2string(example,", "with open('./dataset.csv','w',encoding='utf-8') as dataset: for line in input_file: r = line.split(',') x =", "import numpy as np with open('./input.csv','r',encoding='utf-8') as input_file: with open('./dataset.csv','w',encoding='utf-8') as dataset: for", "as dataset: for line in input_file: r = line.split(',') x = r[0].strip() y", "extract_features as ef import numpy as np with open('./input.csv','r',encoding='utf-8') as input_file: with open('./dataset.csv','w',encoding='utf-8')", "= line.split(',') x = r[0].strip() y = r[1].strip() example = ef.extractFeatures(x) result =", "as input_file: with open('./dataset.csv','w',encoding='utf-8') as dataset: for line in input_file: r = line.split(',')", "= '{0},{1}\\n'.format( np.array2string(example, separator=','), y ) result = result.replace('[','') result = result.replace(']','') result", "r = line.split(',') x = r[0].strip() y = r[1].strip() example = ef.extractFeatures(x) result", "input_file: r = line.split(',') x = r[0].strip() y = r[1].strip() example = ef.extractFeatures(x)", "with open('./input.csv','r',encoding='utf-8') as input_file: with open('./dataset.csv','w',encoding='utf-8') as dataset: for line in input_file: r", "in input_file: r = line.split(',') x = r[0].strip() y = r[1].strip() example =", "np with open('./input.csv','r',encoding='utf-8') as input_file: with open('./dataset.csv','w',encoding='utf-8') as dataset: for line in input_file:", "line in input_file: r = line.split(',') x = r[0].strip() y = r[1].strip() example", "line.split(',') x = r[0].strip() y = r[1].strip() example = ef.extractFeatures(x) result = '{0},{1}\\n'.format(", "input_file: with open('./dataset.csv','w',encoding='utf-8') as dataset: for line in input_file: r = line.split(',') x", "result = '{0},{1}\\n'.format( np.array2string(example, separator=','), y ) result = result.replace('[','') result = result.replace(']','')", "r[1].strip() example = ef.extractFeatures(x) result = '{0},{1}\\n'.format( np.array2string(example, separator=','), y ) result =", "ef import numpy as np with open('./input.csv','r',encoding='utf-8') as input_file: with open('./dataset.csv','w',encoding='utf-8') as dataset:", "example = ef.extractFeatures(x) result = '{0},{1}\\n'.format( np.array2string(example, separator=','), y ) result = result.replace('[','')", "import extract_features as ef import numpy as np with open('./input.csv','r',encoding='utf-8') as input_file: with", "numpy as np with open('./input.csv','r',encoding='utf-8') as input_file: with open('./dataset.csv','w',encoding='utf-8') as dataset: for line", "open('./dataset.csv','w',encoding='utf-8') as dataset: for line in input_file: r = line.split(',') x = r[0].strip()", "separator=','), y ) result = result.replace('[','') result = result.replace(']','') result = result.replace(' ','')", "= ef.extractFeatures(x) result = '{0},{1}\\n'.format( np.array2string(example, separator=','), y ) result = result.replace('[','') result", "y = r[1].strip() example = ef.extractFeatures(x) result = '{0},{1}\\n'.format( np.array2string(example, separator=','), y )", "r[0].strip() y = r[1].strip() example = ef.extractFeatures(x) result = '{0},{1}\\n'.format( np.array2string(example, separator=','), y" ]
[ "yet). db.init_app(app) def main(): Create tables based on each table definition in `models`", "__name__ == \"__main__\": # Allows for command line interaction with Flask application with", "from models import * from flask_session import Session app = get_app() session =", "main(): Create tables based on each table definition in `models` db.drop_all() db.create_all() session.app.session_interface.db.create_all()", "import Session app = get_app() session = Session(app) # Tell Flask what SQLAlchemy", "each table definition in `models` db.drop_all() db.create_all() session.app.session_interface.db.create_all() if __name__ == \"__main__\": #", "\"__main__\": # Allows for command line interaction with Flask application with app.app_context(): main()", "run yet). db.init_app(app) def main(): Create tables based on each table definition in", "from flask_session import Session app = get_app() session = Session(app) # Tell Flask", "import get_app from models import * from flask_session import Session app = get_app()", "Link the Flask app with the database (no Flask app is actually being", "`models` db.drop_all() db.create_all() session.app.session_interface.db.create_all() if __name__ == \"__main__\": # Allows for command line", "is actually being run yet). db.init_app(app) def main(): Create tables based on each", "Flask from application import get_app from models import * from flask_session import Session", "definition in `models` db.drop_all() db.create_all() session.app.session_interface.db.create_all() if __name__ == \"__main__\": # Allows for", "if __name__ == \"__main__\": # Allows for command line interaction with Flask application", "tables based on each table definition in `models` db.drop_all() db.create_all() session.app.session_interface.db.create_all() if __name__", "app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:a1234567@localhost\" # app.config[\"SQLALCHEMY_DATABASE_URI\"] = os.getenv(\"DATABASE_URL\") # app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False # Link", "def main(): Create tables based on each table definition in `models` db.drop_all() db.create_all()", "db.create_all() session.app.session_interface.db.create_all() if __name__ == \"__main__\": # Allows for command line interaction with", "= False # Link the Flask app with the database (no Flask app", "Create tables based on each table definition in `models` db.drop_all() db.create_all() session.app.session_interface.db.create_all() if", "Tell Flask what SQLAlchemy databas to use. # app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:a1234567@localhost\" # app.config[\"SQLALCHEMY_DATABASE_URI\"]", "# app.config[\"SQLALCHEMY_DATABASE_URI\"] = os.getenv(\"DATABASE_URL\") # app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False # Link the Flask app", "# app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False # Link the Flask app with the database (no", "the database (no Flask app is actually being run yet). db.init_app(app) def main():", "session = Session(app) # Tell Flask what SQLAlchemy databas to use. # app.config[\"SQLALCHEMY_DATABASE_URI\"]", "app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False # Link the Flask app with the database (no Flask", "with the database (no Flask app is actually being run yet). db.init_app(app) def", "session.app.session_interface.db.create_all() if __name__ == \"__main__\": # Allows for command line interaction with Flask", "# Link the Flask app with the database (no Flask app is actually", "being run yet). db.init_app(app) def main(): Create tables based on each table definition", "to use. # app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:a1234567@localhost\" # app.config[\"SQLALCHEMY_DATABASE_URI\"] = os.getenv(\"DATABASE_URL\") # app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] =", "= get_app() session = Session(app) # Tell Flask what SQLAlchemy databas to use.", "= Session(app) # Tell Flask what SQLAlchemy databas to use. # app.config[\"SQLALCHEMY_DATABASE_URI\"] =", "# app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:a1234567@localhost\" # app.config[\"SQLALCHEMY_DATABASE_URI\"] = os.getenv(\"DATABASE_URL\") # app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False #", "flask_session import Session app = get_app() session = Session(app) # Tell Flask what", "app.config[\"SQLALCHEMY_DATABASE_URI\"] = os.getenv(\"DATABASE_URL\") # app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False # Link the Flask app with", "Session app = get_app() session = Session(app) # Tell Flask what SQLAlchemy databas", "table definition in `models` db.drop_all() db.create_all() session.app.session_interface.db.create_all() if __name__ == \"__main__\": # Allows", "(no Flask app is actually being run yet). db.init_app(app) def main(): Create tables", "Flask what SQLAlchemy databas to use. # app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:a1234567@localhost\" # app.config[\"SQLALCHEMY_DATABASE_URI\"] =", "db.init_app(app) def main(): Create tables based on each table definition in `models` db.drop_all()", "os.getenv(\"DATABASE_URL\") # app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False # Link the Flask app with the database", "Session(app) # Tell Flask what SQLAlchemy databas to use. # app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:a1234567@localhost\"", "get_app() session = Session(app) # Tell Flask what SQLAlchemy databas to use. #", "app = get_app() session = Session(app) # Tell Flask what SQLAlchemy databas to", "application import get_app from models import * from flask_session import Session app =", "use. # app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:a1234567@localhost\" # app.config[\"SQLALCHEMY_DATABASE_URI\"] = os.getenv(\"DATABASE_URL\") # app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False", "on each table definition in `models` db.drop_all() db.create_all() session.app.session_interface.db.create_all() if __name__ == \"__main__\":", "app with the database (no Flask app is actually being run yet). db.init_app(app)", "from flask import Flask from application import get_app from models import * from", "from application import get_app from models import * from flask_session import Session app", "= os.getenv(\"DATABASE_URL\") # app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False # Link the Flask app with the", "db.drop_all() db.create_all() session.app.session_interface.db.create_all() if __name__ == \"__main__\": # Allows for command line interaction", "what SQLAlchemy databas to use. # app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:a1234567@localhost\" # app.config[\"SQLALCHEMY_DATABASE_URI\"] = os.getenv(\"DATABASE_URL\")", "= \"postgresql://postgres:a1234567@localhost\" # app.config[\"SQLALCHEMY_DATABASE_URI\"] = os.getenv(\"DATABASE_URL\") # app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False # Link the", "app is actually being run yet). db.init_app(app) def main(): Create tables based on", "# Tell Flask what SQLAlchemy databas to use. # app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:a1234567@localhost\" #", "Flask app with the database (no Flask app is actually being run yet).", "== \"__main__\": # Allows for command line interaction with Flask application with app.app_context():", "based on each table definition in `models` db.drop_all() db.create_all() session.app.session_interface.db.create_all() if __name__ ==", "database (no Flask app is actually being run yet). db.init_app(app) def main(): Create", "get_app from models import * from flask_session import Session app = get_app() session", "models import * from flask_session import Session app = get_app() session = Session(app)", "the Flask app with the database (no Flask app is actually being run", "import * from flask_session import Session app = get_app() session = Session(app) #", "* from flask_session import Session app = get_app() session = Session(app) # Tell", "import os from flask import Flask from application import get_app from models import", "actually being run yet). db.init_app(app) def main(): Create tables based on each table", "flask import Flask from application import get_app from models import * from flask_session", "Flask app is actually being run yet). db.init_app(app) def main(): Create tables based", "databas to use. # app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:a1234567@localhost\" # app.config[\"SQLALCHEMY_DATABASE_URI\"] = os.getenv(\"DATABASE_URL\") # app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"]", "import Flask from application import get_app from models import * from flask_session import", "os from flask import Flask from application import get_app from models import *", "SQLAlchemy databas to use. # app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:a1234567@localhost\" # app.config[\"SQLALCHEMY_DATABASE_URI\"] = os.getenv(\"DATABASE_URL\") #", "in `models` db.drop_all() db.create_all() session.app.session_interface.db.create_all() if __name__ == \"__main__\": # Allows for command", "\"postgresql://postgres:a1234567@localhost\" # app.config[\"SQLALCHEMY_DATABASE_URI\"] = os.getenv(\"DATABASE_URL\") # app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False # Link the Flask", "False # Link the Flask app with the database (no Flask app is" ]
[ "# type: pd.DataFrame def read_source_file(self, *args, **kwargs) -> pd.DataFrame: return pd.read_csv(self.input_path, sep=self.separator, index_col='ID')", "def __init__(self, input_path: str, label_id_mapper: dict, separator: str = ',', images_folder: str =", "classification: dict) -> tuple: title = classification['title'] if 'answers' in classification: # self.has_key(classification,", "tuple: title = classification['title'] if 'answers' in classification: # self.has_key(classification, 'answers') return title,", "dict) -> list: return [classification['value']] @classmethod def get_object_labels(cls, classifications: list) -> list: return", "label_id def get_classification_values(self, classification: dict) -> tuple: title = classification['title'] if 'answers' in", "super(LabelBoxLabelReader, self).__init__(input_path, label_id_mapper) self.data = self.read_source_file() # type: pd.DataFrame def read_source_file(self, *args, **kwargs)", "classification: # self.has_key(classification, 'answers') return title, self.get_object_labels(classification['answers']) elif 'answer' in classification: return title,", "self.data = self.read_source_file() # type: pd.DataFrame def read_source_file(self, *args, **kwargs) -> pd.DataFrame: return", "-> pd.DataFrame: return pd.read_csv(self.input_path, sep=self.separator, index_col='ID') def next_labels(self) -> tuple: for index, row", "labels = self.extract_object_labels(obj) if labels is None: continue objects_to_be_yielded += [labels] yield os.path.join(self.images_folder,", "LabelBoxLabelReader(LabelReader): def __init__(self, input_path: str, label_id_mapper: dict, separator: str = ',', images_folder: str", "classification: dict) -> list: return [classification['value']] @classmethod def get_object_labels(cls, classifications: list) -> list:", "yolo_labels.shared import LabelReader class LabelBoxLabelReader(LabelReader): def __init__(self, input_path: str, label_id_mapper: dict, separator: str", "row['External ID']), objects_to_be_yielded def extract_object_labels(self, obj) -> Union[tuple, None]: label_id = self.get_label_id(obj['title']) if", "bbox = obj['bbox'] x, y, h, w = bbox['top'], bbox['left'], bbox['height'], bbox['width'] #", "= obj['bbox'] x, y, h, w = bbox['top'], bbox['left'], bbox['height'], bbox['width'] # example", "return title, self.get_object_labels(classification['answers']) elif 'answer' in classification: return title, self.get_object_label(classification['answer']) return title, []", "get_classification_values(self, classification: dict) -> tuple: title = classification['title'] if 'answers' in classification: #", "self.images_folder = images_folder self.ignore_unmapped_labels = ignore_unmapped_labels super(LabelBoxLabelReader, self).__init__(input_path, label_id_mapper) self.data = self.read_source_file() #", "ignore_unmapped_labels: bool = True): self.input_path = input_path self.separator = separator self.images_folder = images_folder", "elif 'answer' in classification: return title, self.get_object_label(classification['answer']) return title, [] @classmethod def get_object_label(cls,", "-> tuple: for index, row in self.data.iterrows(): objects = json.loads(row['Label'])['objects'] objects_to_be_yielded = []", "['sidewalk', 'reserved_parking_space']), ('is_well_parked', ['yes'])] # labels = [self.get_classification_values(cls) for cls in obj['classifications']] return", "LabelReader class LabelBoxLabelReader(LabelReader): def __init__(self, input_path: str, label_id_mapper: dict, separator: str = ',',", "if labels is None: continue objects_to_be_yielded += [labels] yield os.path.join(self.images_folder, row['External ID']), objects_to_be_yielded", "return None bbox = obj['bbox'] x, y, h, w = bbox['top'], bbox['left'], bbox['height'],", "label_id_mapper) self.data = self.read_source_file() # type: pd.DataFrame def read_source_file(self, *args, **kwargs) -> pd.DataFrame:", "in classifications] @classmethod def has_key(cls, obj: dict, key: str): try: _ = obj[key]", "= [] for obj in objects: labels = self.extract_object_labels(obj) if labels is None:", "objects_to_be_yielded += [labels] yield os.path.join(self.images_folder, row['External ID']), objects_to_be_yielded def extract_object_labels(self, obj) -> Union[tuple,", "def get_object_labels(cls, classifications: list) -> list: return [cls['value'] for cls in classifications] @classmethod", "separator self.images_folder = images_folder self.ignore_unmapped_labels = ignore_unmapped_labels super(LabelBoxLabelReader, self).__init__(input_path, label_id_mapper) self.data = self.read_source_file()", "[classification['value']] @classmethod def get_object_labels(cls, classifications: list) -> list: return [cls['value'] for cls in", "[('provider', ['evo']), # ('parking_place', ['sidewalk', 'reserved_parking_space']), ('is_well_parked', ['yes'])] # labels = [self.get_classification_values(cls) for", "None]: label_id = self.get_label_id(obj['title']) if label_id is None: return None bbox = obj['bbox']", "',', images_folder: str = '', ignore_unmapped_labels: bool = True): self.input_path = input_path self.separator", "json import os from yolo_labels.shared import LabelReader class LabelBoxLabelReader(LabelReader): def __init__(self, input_path: str,", "= True): self.input_path = input_path self.separator = separator self.images_folder = images_folder self.ignore_unmapped_labels =", "pd.DataFrame: return pd.read_csv(self.input_path, sep=self.separator, index_col='ID') def next_labels(self) -> tuple: for index, row in", "extract_object_labels(self, obj) -> Union[tuple, None]: label_id = self.get_label_id(obj['title']) if label_id is None: return", "# ('parking_place', ['sidewalk', 'reserved_parking_space']), ('is_well_parked', ['yes'])] # labels = [self.get_classification_values(cls) for cls in", "in objects: labels = self.extract_object_labels(obj) if labels is None: continue objects_to_be_yielded += [labels]", "('is_well_parked', ['yes'])] # labels = [self.get_classification_values(cls) for cls in obj['classifications']] return x, y,", "**kwargs) -> pd.DataFrame: return pd.read_csv(self.input_path, sep=self.separator, index_col='ID') def next_labels(self) -> tuple: for index,", "title, self.get_object_labels(classification['answers']) elif 'answer' in classification: return title, self.get_object_label(classification['answer']) return title, [] @classmethod", "index_col='ID') def next_labels(self) -> tuple: for index, row in self.data.iterrows(): objects = json.loads(row['Label'])['objects']", "w, label_id def get_classification_values(self, classification: dict) -> tuple: title = classification['title'] if 'answers'", "bbox['height'], bbox['width'] # example of labels: [('provider', ['evo']), # ('parking_place', ['sidewalk', 'reserved_parking_space']), ('is_well_parked',", "return title, [] @classmethod def get_object_label(cls, classification: dict) -> list: return [classification['value']] @classmethod", "= classification['title'] if 'answers' in classification: # self.has_key(classification, 'answers') return title, self.get_object_labels(classification['answers']) elif", "for index, row in self.data.iterrows(): objects = json.loads(row['Label'])['objects'] objects_to_be_yielded = [] for obj", "= ignore_unmapped_labels super(LabelBoxLabelReader, self).__init__(input_path, label_id_mapper) self.data = self.read_source_file() # type: pd.DataFrame def read_source_file(self,", "next_labels(self) -> tuple: for index, row in self.data.iterrows(): objects = json.loads(row['Label'])['objects'] objects_to_be_yielded =", "self.extract_object_labels(obj) if labels is None: continue objects_to_be_yielded += [labels] yield os.path.join(self.images_folder, row['External ID']),", "cls in obj['classifications']] return x, y, h, w, label_id def get_classification_values(self, classification: dict)", "images_folder self.ignore_unmapped_labels = ignore_unmapped_labels super(LabelBoxLabelReader, self).__init__(input_path, label_id_mapper) self.data = self.read_source_file() # type: pd.DataFrame", "os.path.join(self.images_folder, row['External ID']), objects_to_be_yielded def extract_object_labels(self, obj) -> Union[tuple, None]: label_id = self.get_label_id(obj['title'])", "'answer' in classification: return title, self.get_object_label(classification['answer']) return title, [] @classmethod def get_object_label(cls, classification:", "-> list: return [classification['value']] @classmethod def get_object_labels(cls, classifications: list) -> list: return [cls['value']", "get_object_label(cls, classification: dict) -> list: return [classification['value']] @classmethod def get_object_labels(cls, classifications: list) ->", "cls in classifications] @classmethod def has_key(cls, obj: dict, key: str): try: _ =", "-> list: return [cls['value'] for cls in classifications] @classmethod def has_key(cls, obj: dict,", "y, h, w, label_id def get_classification_values(self, classification: dict) -> tuple: title = classification['title']", "pd.read_csv(self.input_path, sep=self.separator, index_col='ID') def next_labels(self) -> tuple: for index, row in self.data.iterrows(): objects", "str = ',', images_folder: str = '', ignore_unmapped_labels: bool = True): self.input_path =", "example of labels: [('provider', ['evo']), # ('parking_place', ['sidewalk', 'reserved_parking_space']), ('is_well_parked', ['yes'])] # labels", "typing import Union import json import os from yolo_labels.shared import LabelReader class LabelBoxLabelReader(LabelReader):", "self.data.iterrows(): objects = json.loads(row['Label'])['objects'] objects_to_be_yielded = [] for obj in objects: labels =", "return x, y, h, w, label_id def get_classification_values(self, classification: dict) -> tuple: title", "def has_key(cls, obj: dict, key: str): try: _ = obj[key] return True except", "x, y, h, w = bbox['top'], bbox['left'], bbox['height'], bbox['width'] # example of labels:", "sep=self.separator, index_col='ID') def next_labels(self) -> tuple: for index, row in self.data.iterrows(): objects =", "of labels: [('provider', ['evo']), # ('parking_place', ['sidewalk', 'reserved_parking_space']), ('is_well_parked', ['yes'])] # labels =", "<filename>yolo_labels/LabelBox/reader.py import pandas as pd from typing import Union import json import os", "'', ignore_unmapped_labels: bool = True): self.input_path = input_path self.separator = separator self.images_folder =", "h, w = bbox['top'], bbox['left'], bbox['height'], bbox['width'] # example of labels: [('provider', ['evo']),", "has_key(cls, obj: dict, key: str): try: _ = obj[key] return True except KeyError:", "os from yolo_labels.shared import LabelReader class LabelBoxLabelReader(LabelReader): def __init__(self, input_path: str, label_id_mapper: dict,", "read_source_file(self, *args, **kwargs) -> pd.DataFrame: return pd.read_csv(self.input_path, sep=self.separator, index_col='ID') def next_labels(self) -> tuple:", "def next_labels(self) -> tuple: for index, row in self.data.iterrows(): objects = json.loads(row['Label'])['objects'] objects_to_be_yielded", "= input_path self.separator = separator self.images_folder = images_folder self.ignore_unmapped_labels = ignore_unmapped_labels super(LabelBoxLabelReader, self).__init__(input_path,", "obj['classifications']] return x, y, h, w, label_id def get_classification_values(self, classification: dict) -> tuple:", "[] @classmethod def get_object_label(cls, classification: dict) -> list: return [classification['value']] @classmethod def get_object_labels(cls,", "pandas as pd from typing import Union import json import os from yolo_labels.shared", "True): self.input_path = input_path self.separator = separator self.images_folder = images_folder self.ignore_unmapped_labels = ignore_unmapped_labels", "*args, **kwargs) -> pd.DataFrame: return pd.read_csv(self.input_path, sep=self.separator, index_col='ID') def next_labels(self) -> tuple: for", "= self.extract_object_labels(obj) if labels is None: continue objects_to_be_yielded += [labels] yield os.path.join(self.images_folder, row['External", "list: return [cls['value'] for cls in classifications] @classmethod def has_key(cls, obj: dict, key:", "Union import json import os from yolo_labels.shared import LabelReader class LabelBoxLabelReader(LabelReader): def __init__(self,", "[self.get_classification_values(cls) for cls in obj['classifications']] return x, y, h, w, label_id def get_classification_values(self,", "self.ignore_unmapped_labels = ignore_unmapped_labels super(LabelBoxLabelReader, self).__init__(input_path, label_id_mapper) self.data = self.read_source_file() # type: pd.DataFrame def", "from typing import Union import json import os from yolo_labels.shared import LabelReader class", "dict) -> tuple: title = classification['title'] if 'answers' in classification: # self.has_key(classification, 'answers')", "from yolo_labels.shared import LabelReader class LabelBoxLabelReader(LabelReader): def __init__(self, input_path: str, label_id_mapper: dict, separator:", "+= [labels] yield os.path.join(self.images_folder, row['External ID']), objects_to_be_yielded def extract_object_labels(self, obj) -> Union[tuple, None]:", "for cls in obj['classifications']] return x, y, h, w, label_id def get_classification_values(self, classification:", "classification: return title, self.get_object_label(classification['answer']) return title, [] @classmethod def get_object_label(cls, classification: dict) ->", "in classification: return title, self.get_object_label(classification['answer']) return title, [] @classmethod def get_object_label(cls, classification: dict)", "is None: continue objects_to_be_yielded += [labels] yield os.path.join(self.images_folder, row['External ID']), objects_to_be_yielded def extract_object_labels(self,", "title, [] @classmethod def get_object_label(cls, classification: dict) -> list: return [classification['value']] @classmethod def", "str = '', ignore_unmapped_labels: bool = True): self.input_path = input_path self.separator = separator", "bbox['width'] # example of labels: [('provider', ['evo']), # ('parking_place', ['sidewalk', 'reserved_parking_space']), ('is_well_parked', ['yes'])]", "classifications: list) -> list: return [cls['value'] for cls in classifications] @classmethod def has_key(cls,", "list) -> list: return [cls['value'] for cls in classifications] @classmethod def has_key(cls, obj:", "import pandas as pd from typing import Union import json import os from", "objects = json.loads(row['Label'])['objects'] objects_to_be_yielded = [] for obj in objects: labels = self.extract_object_labels(obj)", "h, w, label_id def get_classification_values(self, classification: dict) -> tuple: title = classification['title'] if", "ID']), objects_to_be_yielded def extract_object_labels(self, obj) -> Union[tuple, None]: label_id = self.get_label_id(obj['title']) if label_id", "self.separator = separator self.images_folder = images_folder self.ignore_unmapped_labels = ignore_unmapped_labels super(LabelBoxLabelReader, self).__init__(input_path, label_id_mapper) self.data", "objects_to_be_yielded def extract_object_labels(self, obj) -> Union[tuple, None]: label_id = self.get_label_id(obj['title']) if label_id is", "if 'answers' in classification: # self.has_key(classification, 'answers') return title, self.get_object_labels(classification['answers']) elif 'answer' in", "list: return [classification['value']] @classmethod def get_object_labels(cls, classifications: list) -> list: return [cls['value'] for", "obj) -> Union[tuple, None]: label_id = self.get_label_id(obj['title']) if label_id is None: return None", "tuple: for index, row in self.data.iterrows(): objects = json.loads(row['Label'])['objects'] objects_to_be_yielded = [] for", "= '', ignore_unmapped_labels: bool = True): self.input_path = input_path self.separator = separator self.images_folder", "classifications] @classmethod def has_key(cls, obj: dict, key: str): try: _ = obj[key] return", "['yes'])] # labels = [self.get_classification_values(cls) for cls in obj['classifications']] return x, y, h,", "'reserved_parking_space']), ('is_well_parked', ['yes'])] # labels = [self.get_classification_values(cls) for cls in obj['classifications']] return x,", "__init__(self, input_path: str, label_id_mapper: dict, separator: str = ',', images_folder: str = '',", "input_path self.separator = separator self.images_folder = images_folder self.ignore_unmapped_labels = ignore_unmapped_labels super(LabelBoxLabelReader, self).__init__(input_path, label_id_mapper)", "as pd from typing import Union import json import os from yolo_labels.shared import", "return [classification['value']] @classmethod def get_object_labels(cls, classifications: list) -> list: return [cls['value'] for cls", "['evo']), # ('parking_place', ['sidewalk', 'reserved_parking_space']), ('is_well_parked', ['yes'])] # labels = [self.get_classification_values(cls) for cls", "is None: return None bbox = obj['bbox'] x, y, h, w = bbox['top'],", "None: continue objects_to_be_yielded += [labels] yield os.path.join(self.images_folder, row['External ID']), objects_to_be_yielded def extract_object_labels(self, obj)", "self.get_object_labels(classification['answers']) elif 'answer' in classification: return title, self.get_object_label(classification['answer']) return title, [] @classmethod def", "y, h, w = bbox['top'], bbox['left'], bbox['height'], bbox['width'] # example of labels: [('provider',", "# example of labels: [('provider', ['evo']), # ('parking_place', ['sidewalk', 'reserved_parking_space']), ('is_well_parked', ['yes'])] #", "x, y, h, w, label_id def get_classification_values(self, classification: dict) -> tuple: title =", "None: return None bbox = obj['bbox'] x, y, h, w = bbox['top'], bbox['left'],", "-> Union[tuple, None]: label_id = self.get_label_id(obj['title']) if label_id is None: return None bbox", "@classmethod def has_key(cls, obj: dict, key: str): try: _ = obj[key] return True", "def get_classification_values(self, classification: dict) -> tuple: title = classification['title'] if 'answers' in classification:", "dict, key: str): try: _ = obj[key] return True except KeyError: return False", "type: pd.DataFrame def read_source_file(self, *args, **kwargs) -> pd.DataFrame: return pd.read_csv(self.input_path, sep=self.separator, index_col='ID') def", "objects_to_be_yielded = [] for obj in objects: labels = self.extract_object_labels(obj) if labels is", "[labels] yield os.path.join(self.images_folder, row['External ID']), objects_to_be_yielded def extract_object_labels(self, obj) -> Union[tuple, None]: label_id", "title, self.get_object_label(classification['answer']) return title, [] @classmethod def get_object_label(cls, classification: dict) -> list: return", "Union[tuple, None]: label_id = self.get_label_id(obj['title']) if label_id is None: return None bbox =", "separator: str = ',', images_folder: str = '', ignore_unmapped_labels: bool = True): self.input_path", "self.get_object_label(classification['answer']) return title, [] @classmethod def get_object_label(cls, classification: dict) -> list: return [classification['value']]", "if label_id is None: return None bbox = obj['bbox'] x, y, h, w", "labels: [('provider', ['evo']), # ('parking_place', ['sidewalk', 'reserved_parking_space']), ('is_well_parked', ['yes'])] # labels = [self.get_classification_values(cls)", "for cls in classifications] @classmethod def has_key(cls, obj: dict, key: str): try: _", "classification['title'] if 'answers' in classification: # self.has_key(classification, 'answers') return title, self.get_object_labels(classification['answers']) elif 'answer'", "import os from yolo_labels.shared import LabelReader class LabelBoxLabelReader(LabelReader): def __init__(self, input_path: str, label_id_mapper:", "None bbox = obj['bbox'] x, y, h, w = bbox['top'], bbox['left'], bbox['height'], bbox['width']", "# self.has_key(classification, 'answers') return title, self.get_object_labels(classification['answers']) elif 'answer' in classification: return title, self.get_object_label(classification['answer'])", "= separator self.images_folder = images_folder self.ignore_unmapped_labels = ignore_unmapped_labels super(LabelBoxLabelReader, self).__init__(input_path, label_id_mapper) self.data =", "row in self.data.iterrows(): objects = json.loads(row['Label'])['objects'] objects_to_be_yielded = [] for obj in objects:", "def get_object_label(cls, classification: dict) -> list: return [classification['value']] @classmethod def get_object_labels(cls, classifications: list)", "= json.loads(row['Label'])['objects'] objects_to_be_yielded = [] for obj in objects: labels = self.extract_object_labels(obj) if", "labels = [self.get_classification_values(cls) for cls in obj['classifications']] return x, y, h, w, label_id", "self.read_source_file() # type: pd.DataFrame def read_source_file(self, *args, **kwargs) -> pd.DataFrame: return pd.read_csv(self.input_path, sep=self.separator,", "import json import os from yolo_labels.shared import LabelReader class LabelBoxLabelReader(LabelReader): def __init__(self, input_path:", "input_path: str, label_id_mapper: dict, separator: str = ',', images_folder: str = '', ignore_unmapped_labels:", "bool = True): self.input_path = input_path self.separator = separator self.images_folder = images_folder self.ignore_unmapped_labels", "index, row in self.data.iterrows(): objects = json.loads(row['Label'])['objects'] objects_to_be_yielded = [] for obj in", "class LabelBoxLabelReader(LabelReader): def __init__(self, input_path: str, label_id_mapper: dict, separator: str = ',', images_folder:", "title = classification['title'] if 'answers' in classification: # self.has_key(classification, 'answers') return title, self.get_object_labels(classification['answers'])", "@classmethod def get_object_labels(cls, classifications: list) -> list: return [cls['value'] for cls in classifications]", "pd from typing import Union import json import os from yolo_labels.shared import LabelReader", "ignore_unmapped_labels super(LabelBoxLabelReader, self).__init__(input_path, label_id_mapper) self.data = self.read_source_file() # type: pd.DataFrame def read_source_file(self, *args,", "pd.DataFrame def read_source_file(self, *args, **kwargs) -> pd.DataFrame: return pd.read_csv(self.input_path, sep=self.separator, index_col='ID') def next_labels(self)", "label_id_mapper: dict, separator: str = ',', images_folder: str = '', ignore_unmapped_labels: bool =", "import LabelReader class LabelBoxLabelReader(LabelReader): def __init__(self, input_path: str, label_id_mapper: dict, separator: str =", "dict, separator: str = ',', images_folder: str = '', ignore_unmapped_labels: bool = True):", "self.input_path = input_path self.separator = separator self.images_folder = images_folder self.ignore_unmapped_labels = ignore_unmapped_labels super(LabelBoxLabelReader,", "import Union import json import os from yolo_labels.shared import LabelReader class LabelBoxLabelReader(LabelReader): def", "= images_folder self.ignore_unmapped_labels = ignore_unmapped_labels super(LabelBoxLabelReader, self).__init__(input_path, label_id_mapper) self.data = self.read_source_file() # type:", "self).__init__(input_path, label_id_mapper) self.data = self.read_source_file() # type: pd.DataFrame def read_source_file(self, *args, **kwargs) ->", "[] for obj in objects: labels = self.extract_object_labels(obj) if labels is None: continue", "obj in objects: labels = self.extract_object_labels(obj) if labels is None: continue objects_to_be_yielded +=", "objects: labels = self.extract_object_labels(obj) if labels is None: continue objects_to_be_yielded += [labels] yield", "= bbox['top'], bbox['left'], bbox['height'], bbox['width'] # example of labels: [('provider', ['evo']), # ('parking_place',", "self.get_label_id(obj['title']) if label_id is None: return None bbox = obj['bbox'] x, y, h,", "obj['bbox'] x, y, h, w = bbox['top'], bbox['left'], bbox['height'], bbox['width'] # example of", "json.loads(row['Label'])['objects'] objects_to_be_yielded = [] for obj in objects: labels = self.extract_object_labels(obj) if labels", "self.has_key(classification, 'answers') return title, self.get_object_labels(classification['answers']) elif 'answer' in classification: return title, self.get_object_label(classification['answer']) return", "@classmethod def get_object_label(cls, classification: dict) -> list: return [classification['value']] @classmethod def get_object_labels(cls, classifications:", "labels is None: continue objects_to_be_yielded += [labels] yield os.path.join(self.images_folder, row['External ID']), objects_to_be_yielded def", "return [cls['value'] for cls in classifications] @classmethod def has_key(cls, obj: dict, key: str):", "# labels = [self.get_classification_values(cls) for cls in obj['classifications']] return x, y, h, w,", "yield os.path.join(self.images_folder, row['External ID']), objects_to_be_yielded def extract_object_labels(self, obj) -> Union[tuple, None]: label_id =", "def read_source_file(self, *args, **kwargs) -> pd.DataFrame: return pd.read_csv(self.input_path, sep=self.separator, index_col='ID') def next_labels(self) ->", "obj: dict, key: str): try: _ = obj[key] return True except KeyError: return", "= ',', images_folder: str = '', ignore_unmapped_labels: bool = True): self.input_path = input_path", "for obj in objects: labels = self.extract_object_labels(obj) if labels is None: continue objects_to_be_yielded", "continue objects_to_be_yielded += [labels] yield os.path.join(self.images_folder, row['External ID']), objects_to_be_yielded def extract_object_labels(self, obj) ->", "get_object_labels(cls, classifications: list) -> list: return [cls['value'] for cls in classifications] @classmethod def", "w = bbox['top'], bbox['left'], bbox['height'], bbox['width'] # example of labels: [('provider', ['evo']), #", "= self.read_source_file() # type: pd.DataFrame def read_source_file(self, *args, **kwargs) -> pd.DataFrame: return pd.read_csv(self.input_path,", "in self.data.iterrows(): objects = json.loads(row['Label'])['objects'] objects_to_be_yielded = [] for obj in objects: labels", "-> tuple: title = classification['title'] if 'answers' in classification: # self.has_key(classification, 'answers') return", "def extract_object_labels(self, obj) -> Union[tuple, None]: label_id = self.get_label_id(obj['title']) if label_id is None:", "return title, self.get_object_label(classification['answer']) return title, [] @classmethod def get_object_label(cls, classification: dict) -> list:", "bbox['top'], bbox['left'], bbox['height'], bbox['width'] # example of labels: [('provider', ['evo']), # ('parking_place', ['sidewalk',", "in classification: # self.has_key(classification, 'answers') return title, self.get_object_labels(classification['answers']) elif 'answer' in classification: return", "return pd.read_csv(self.input_path, sep=self.separator, index_col='ID') def next_labels(self) -> tuple: for index, row in self.data.iterrows():", "str, label_id_mapper: dict, separator: str = ',', images_folder: str = '', ignore_unmapped_labels: bool", "'answers') return title, self.get_object_labels(classification['answers']) elif 'answer' in classification: return title, self.get_object_label(classification['answer']) return title,", "images_folder: str = '', ignore_unmapped_labels: bool = True): self.input_path = input_path self.separator =", "bbox['left'], bbox['height'], bbox['width'] # example of labels: [('provider', ['evo']), # ('parking_place', ['sidewalk', 'reserved_parking_space']),", "[cls['value'] for cls in classifications] @classmethod def has_key(cls, obj: dict, key: str): try:", "'answers' in classification: # self.has_key(classification, 'answers') return title, self.get_object_labels(classification['answers']) elif 'answer' in classification:", "= [self.get_classification_values(cls) for cls in obj['classifications']] return x, y, h, w, label_id def", "label_id = self.get_label_id(obj['title']) if label_id is None: return None bbox = obj['bbox'] x,", "label_id is None: return None bbox = obj['bbox'] x, y, h, w =", "('parking_place', ['sidewalk', 'reserved_parking_space']), ('is_well_parked', ['yes'])] # labels = [self.get_classification_values(cls) for cls in obj['classifications']]", "in obj['classifications']] return x, y, h, w, label_id def get_classification_values(self, classification: dict) ->", "= self.get_label_id(obj['title']) if label_id is None: return None bbox = obj['bbox'] x, y," ]
[ "distribution.pop(\"description\") result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante el año 2015\\n\\n'", "{\"title\": \"Convocatorias abiertas durante el año 2015\", \"description\": \"Listado de las convocatorias abiertas", "el \" \"sistema de contrataciones \" \"electrónicas\", }]} result = dataset_to_markdown(dataset) expected =", "campos no obligatiorios distribution.pop(\"field\") distribution.pop(\"description\") result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas", "electrónicas\\n\\n'\\ 'Datos correspondientes al Sistema de Contrataciones ' \\ 'Electrónicas (Argentina Compra)\\n\\n'\\ '##", "\"description\": \"Identificador único de la \" \"unidad operativa de \" \"contrataciones\"}]} result =", "del dataset\\n\\n\\n'\\ '### Convocatorias abiertas durante el año 2015\\n\\n'\\ 'Listado de las convocatorias", "abiertas durante el \" \"año 2016\", \"description\": \"Listado de las convocatorias \" \"abiertas", "de \" \"contrataciones\"}]}, {\"title\": \"Convocatorias abiertas durante el \" \"año 2016\", \"description\": \"Listado", "\"abiertas durante el año 2015 en el \" \"sistema de contrataciones \" \"electrónicas\",", "recurso\\n\\n' \\ '- **procedimiento_id** (integer): Identificador único ' \\ 'del procedimiento\\n' \\ '-", "(integer): \" \\ \"Identificador único del procedimiento\" self.assertEqual(result, expected) # elimino campo de", "\"description\": \"Listado de las convocatorias \" \"abiertas durante el año 2016 en el", "abiertas durante el año ' \\ '2015 en el sistema de contrataciones electrónicas\\n\\n'", "procedimiento\" self.assertEqual(result, expected) # elimino campo de type field.pop(\"type\") result = field_to_markdown(field) expected", "\"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de la\" \" unidad", "\"**procedimiento_id** (integer): \" \\ \"Identificador único del procedimiento\" self.assertEqual(result, expected) # elimino campo", "recurso\\n\\n'\\ '- **procedimiento_id** (integer): Identificador ' \\ 'único del procedimiento\\n'\\ '- **unidad_operativa_contrataciones_id** (integer):", "de contrataciones electrónicas\\n\\n'\\ 'Datos correspondientes al Sistema de Contrataciones ' \\ 'Electrónicas (Argentina", "\"sistema de contrataciones \" \"electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único", "el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso' self.assertEqual.__self__.maxDiff = None self.assertEqual(result.strip(),", "procedimiento\\n'\\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de la unidad operativa de", "(Argentina Compra)\", \"distribution\": [{\"title\": \"Convocatorias abiertas durante \" \"el año 2015\", \"description\": \"Listado", "\"Convocatorias abiertas durante el año 2015\", \"description\": \"Listado de las convocatorias abiertas \"", "-*- coding: utf-8 -*- \"\"\"Tests del modulo pydatajson.\"\"\" from __future__ import unicode_literals from", "(integer): Identificador único ' \\ 'del procedimiento\\n' \\ '- **unidad_operativa_contrataciones_id** (integer): ' \\", "pydatajson.documentation import dataset_to_markdown class DocumentationTestCase(unittest.TestCase): SAMPLES_DIR = os.path.join(\"tests\", \"samples\") RESULTS_DIR = os.path.join(\"tests\", \"results\")", "{\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de la\" \" unidad operativa", "\" \"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de la \"", "de ' \\ 'contrataciones\\n\\n'\\ '### Convocatorias abiertas durante el año 2016\\n\\n'\\ 'Listado de", "'\\n### Convocatorias abiertas durante el año 2015\\n\\n' \\ 'Listado de las convocatorias abiertas", "utf-8 -*- \"\"\"Tests del modulo pydatajson.\"\"\" from __future__ import unicode_literals from __future__ import", "def test_distribution_to_markdown(self): distribution = {\"title\": \"Convocatorias abiertas durante el año 2015\", \"description\": \"Listado", "de las convocatorias abiertas \" \"durante el año 2015 en el sistema de", "convocatorias \" \"abiertas durante el año 2016 en el \" \"sistema de contrataciones", "= {\"title\": \"Sistema de contrataciones electrónicas\", \"description\": \"Datos correspondientes al Sistema de \"", "en el sistema de \" \"contrataciones electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\":", "\" \"contrataciones\"}]} result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante el año", "durante el año 2015 en el \" \"sistema de contrataciones \" \"electrónicas\", \"field\":", "\"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de la \" \"unidad operativa de \"", "Recursos del dataset\\n\\n\\n'\\ '### Convocatorias abiertas durante el año 2015\\n\\n'\\ 'Listado de las", "result = field_to_markdown(field) expected = \"**procedimiento_id** (integer): \" \\ \"Identificador único del procedimiento\"", "\"\"\"Tests del modulo pydatajson.\"\"\" from __future__ import unicode_literals from __future__ import print_function from", "electrónicas\\n\\n'\\ '#### Campos del recurso' self.assertEqual.__self__.maxDiff = None self.assertEqual(result.strip(), expected.strip()) if __name__ ==", "{ \"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del procedimiento\" } result =", "el sistema de \" \"contrataciones electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador", "elimino campo de description field.pop(\"description\") result = field_to_markdown(field) expected = \"**procedimiento_id**\" self.assertEqual(result, expected)", "field = { \"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del procedimiento\" }", "\\ '2015 en el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso\\n\\n'\\ '-", "\\ '#### Campos del recurso\\n\\n' \\ '- **procedimiento_id** (integer): Identificador único ' \\", "Campos del recurso\\n\\n'\\ '- **procedimiento_id** (integer): Identificador ' \\ 'único del procedimiento\\n'\\ '-", "\\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de la unidad operativa de'", "del procedimiento\" self.assertEqual(result, expected) # elimino campo de type field.pop(\"type\") result = field_to_markdown(field)", "\"contrataciones\"}]} result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante el año 2015\\n\\n'", "# elimino campos no obligatiorios distribution.pop(\"field\") distribution.pop(\"description\") result = distribution_to_markdown(distribution) expected = '\\n###", "el año ' \\ '2015 en el sistema de contrataciones electrónicas\\n\\n' \\ '####", "\"integer\", \"description\": \"Identificador único del \" \"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\":", "field.pop(\"type\") result = field_to_markdown(field) expected = \"**procedimiento_id**: \" \\ \"Identificador único del procedimiento\"", "distribution = {\"title\": \"Convocatorias abiertas durante el año 2015\", \"description\": \"Listado de las", "\"description\": \"Listado de las convocatorias \" \"abiertas durante el año 2015 en el", "\" \"contrataciones\"}]}, {\"title\": \"Convocatorias abiertas durante el \" \"año 2016\", \"description\": \"Listado de", "de la\" \" unidad operativa de \" \"contrataciones\"}]}, {\"title\": \"Convocatorias abiertas durante el", "abiertas durante el año 2015\\n\\n'\\ 'Listado de las convocatorias abiertas durante el año", "= dataset_to_markdown(dataset) expected = '\\n# Sistema de contrataciones electrónicas\\n\\n'\\ 'Datos correspondientes al Sistema", "\"**procedimiento_id**\" self.assertEqual(result, expected) def test_distribution_to_markdown(self): distribution = {\"title\": \"Convocatorias abiertas durante el año", "'2015 en el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso\\n\\n'\\ '- **procedimiento_id**", "2015\\n\\n'\\ 'Listado de las convocatorias abiertas durante el año ' \\ '2015 en", "único del procedimiento\" self.assertEqual(result, expected) # elimino campo de description field.pop(\"description\") result =", "del procedimiento\\n'\\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de la unidad operativa", "el año 2015 en el \" \"sistema de contrataciones \" \"electrónicas\", \"field\": [{\"title\":", "os.path import unittest import nose from .context import pydatajson from pydatajson.documentation import field_to_markdown", "}]} result = dataset_to_markdown(dataset) expected = '\\n# Sistema de contrataciones electrónicas\\n\\n'\\ 'Datos correspondientes", "\"type\": \"integer\", \"description\": \"Identificador único de la\" \" unidad operativa de \" \"contrataciones\"}]},", "{\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de la \" \"unidad operativa", "en el sistema de contrataciones electrónicas\\n\\n' \\ '#### Campos del recurso\\n\\n' \\ '-", "expected.strip()) def test_dataset_to_markdown(self): dataset = {\"title\": \"Sistema de contrataciones electrónicas\", \"description\": \"Datos correspondientes", "\"samples\") RESULTS_DIR = os.path.join(\"tests\", \"results\") def test_field_to_markdown(self): field = { \"title\": \"procedimiento_id\", \"type\":", "año 2015\\n\\n' \\ '\\n\\n#### Campos del recurso' print(result) self.assertEqual(result.strip(), expected.strip()) def test_dataset_to_markdown(self): dataset", "description field.pop(\"description\") result = field_to_markdown(field) expected = \"**procedimiento_id**\" self.assertEqual(result, expected) def test_distribution_to_markdown(self): distribution", "print(result) self.assertEqual(result.strip(), expected.strip()) def test_dataset_to_markdown(self): dataset = {\"title\": \"Sistema de contrataciones electrónicas\", \"description\":", "del procedimiento\" } result = field_to_markdown(field) expected = \"**procedimiento_id** (integer): \" \\ \"Identificador", "'\\n### Convocatorias abiertas durante el año 2015\\n\\n' \\ '\\n\\n#### Campos del recurso' print(result)", "unittest import nose from .context import pydatajson from pydatajson.documentation import field_to_markdown from pydatajson.documentation", "de contrataciones \" \"electrónicas\", }]} result = dataset_to_markdown(dataset) expected = '\\n# Sistema de", "durante el año ' \\ '2015 en el sistema de contrataciones electrónicas\\n\\n'\\ '####", "\"año 2016\", \"description\": \"Listado de las convocatorias \" \"abiertas durante el año 2016", "distribution.pop(\"field\") distribution.pop(\"description\") result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante el año", "result = field_to_markdown(field) expected = \"**procedimiento_id**\" self.assertEqual(result, expected) def test_distribution_to_markdown(self): distribution = {\"title\":", "año 2015 en el \" \"sistema de contrataciones \" \"electrónicas\", \"field\": [{\"title\": \"procedimiento_id\",", "de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso\\n\\n'\\ '- **procedimiento_id** (integer): Identificador ' \\", "pydatajson.\"\"\" from __future__ import unicode_literals from __future__ import print_function from __future__ import with_statement", "año 2015 en el sistema de \" \"contrataciones electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\":", "\\ 'Listado de las convocatorias abiertas durante el año ' \\ '2015 en", "abiertas \" \"durante el año 2015 en el sistema de \" \"contrataciones electrónicas\",", "contrataciones electrónicas\\n\\n'\\ 'Datos correspondientes al Sistema de Contrataciones ' \\ 'Electrónicas (Argentina Compra)\\n\\n'\\", "\"integer\", \"description\": \"Identificador único del procedimiento\" } result = field_to_markdown(field) expected = \"**procedimiento_id**", "[{\"title\": \"Convocatorias abiertas durante \" \"el año 2015\", \"description\": \"Listado de las convocatorias", "\"Convocatorias abiertas durante el \" \"año 2016\", \"description\": \"Listado de las convocatorias \"", "def test_dataset_to_markdown(self): dataset = {\"title\": \"Sistema de contrataciones electrónicas\", \"description\": \"Datos correspondientes al", "\"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del \" \"procedimiento\"}, {\"title\": \"unidad_operativa_\"", "os.path.join(\"tests\", \"samples\") RESULTS_DIR = os.path.join(\"tests\", \"results\") def test_field_to_markdown(self): field = { \"title\": \"procedimiento_id\",", "field_to_markdown(field) expected = \"**procedimiento_id** (integer): \" \\ \"Identificador único del procedimiento\" self.assertEqual(result, expected)", "'único del procedimiento\\n'\\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de la unidad", "de contrataciones electrónicas\\n\\n' \\ '#### Campos del recurso\\n\\n' \\ '- **procedimiento_id** (integer): Identificador", "durante el año 2015\\n\\n' \\ '\\n\\n#### Campos del recurso' print(result) self.assertEqual(result.strip(), expected.strip()) def", "\" \"electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del \" \"procedimiento\"},", "sistema de contrataciones electrónicas\\n\\n' \\ '#### Campos del recurso\\n\\n' \\ '- **procedimiento_id** (integer):", "} result = field_to_markdown(field) expected = \"**procedimiento_id** (integer): \" \\ \"Identificador único del", "'Identificador único de la unidad operativa de ' \\ 'contrataciones\\n\\n'\\ '### Convocatorias abiertas", "\" unidad operativa de \" \"contrataciones\"}]}, {\"title\": \"Convocatorias abiertas durante el \" \"año", "en el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso' self.assertEqual.__self__.maxDiff = None", "'## Recursos del dataset\\n\\n\\n'\\ '### Convocatorias abiertas durante el año 2015\\n\\n'\\ 'Listado de", "'- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de la unidad operativa de '", "abiertas durante el año 2015\\n\\n' \\ 'Listado de las convocatorias abiertas durante el", "import os.path import unittest import nose from .context import pydatajson from pydatajson.documentation import", "coding: utf-8 -*- \"\"\"Tests del modulo pydatajson.\"\"\" from __future__ import unicode_literals from __future__", "__future__ import print_function from __future__ import with_statement import os.path import unittest import nose", "de las convocatorias abiertas durante el año ' \\ '2015 en el sistema", "correspondientes al Sistema de \" \"Contrataciones Electrónicas (Argentina Compra)\", \"distribution\": [{\"title\": \"Convocatorias abiertas", "dataset_to_markdown(dataset) expected = '\\n# Sistema de contrataciones electrónicas\\n\\n'\\ 'Datos correspondientes al Sistema de", "de type field.pop(\"type\") result = field_to_markdown(field) expected = \"**procedimiento_id**: \" \\ \"Identificador único", "correspondientes al Sistema de Contrataciones ' \\ 'Electrónicas (Argentina Compra)\\n\\n'\\ '## Recursos del", "\\ 'único del procedimiento\\n'\\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de la", "result = field_to_markdown(field) expected = \"**procedimiento_id**: \" \\ \"Identificador único del procedimiento\" self.assertEqual(result,", "contrataciones electrónicas\", \"description\": \"Datos correspondientes al Sistema de \" \"Contrataciones Electrónicas (Argentina Compra)\",", "pydatajson from pydatajson.documentation import field_to_markdown from pydatajson.documentation import distribution_to_markdown from pydatajson.documentation import dataset_to_markdown", "modulo pydatajson.\"\"\" from __future__ import unicode_literals from __future__ import print_function from __future__ import", "os.path.join(\"tests\", \"results\") def test_field_to_markdown(self): field = { \"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador", "\"Identificador único del procedimiento\" } result = field_to_markdown(field) expected = \"**procedimiento_id** (integer): \"", "= distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante el año 2015\\n\\n' \\ '\\n\\n####", "\" \"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de la\" \"", "distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante el año 2015\\n\\n' \\ '\\n\\n#### Campos", "de Contrataciones ' \\ 'Electrónicas (Argentina Compra)\\n\\n'\\ '## Recursos del dataset\\n\\n\\n'\\ '### Convocatorias", "expected = \"**procedimiento_id**\" self.assertEqual(result, expected) def test_distribution_to_markdown(self): distribution = {\"title\": \"Convocatorias abiertas durante", "el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso\\n\\n'\\ '- **procedimiento_id** (integer): Identificador", "durante el año ' \\ '2016 en el sistema de contrataciones electrónicas\\n\\n'\\ '####", "__future__ import with_statement import os.path import unittest import nose from .context import pydatajson", "\" \"el año 2015\", \"description\": \"Listado de las convocatorias \" \"abiertas durante el", "elimino campo de type field.pop(\"type\") result = field_to_markdown(field) expected = \"**procedimiento_id**: \" \\", "\" \\ \"Identificador único del procedimiento\" self.assertEqual(result, expected) # elimino campo de description", "from __future__ import print_function from __future__ import with_statement import os.path import unittest import", "'Datos correspondientes al Sistema de Contrataciones ' \\ 'Electrónicas (Argentina Compra)\\n\\n'\\ '## Recursos", "de la \" \"unidad operativa de \" \"contrataciones\"}]} result = distribution_to_markdown(distribution) expected =", "python # -*- coding: utf-8 -*- \"\"\"Tests del modulo pydatajson.\"\"\" from __future__ import", "Compra)\", \"distribution\": [{\"title\": \"Convocatorias abiertas durante \" \"el año 2015\", \"description\": \"Listado de", "\\ ' contrataciones\\n' self.assertEqual(result, expected) # elimino campos no obligatiorios distribution.pop(\"field\") distribution.pop(\"description\") result", "\\ '\\n\\n#### Campos del recurso' print(result) self.assertEqual(result.strip(), expected.strip()) def test_dataset_to_markdown(self): dataset = {\"title\":", "self.assertEqual(result, expected) # elimino campos no obligatiorios distribution.pop(\"field\") distribution.pop(\"description\") result = distribution_to_markdown(distribution) expected", "de las convocatorias abiertas durante el año ' \\ '2016 en el sistema", "import with_statement import os.path import unittest import nose from .context import pydatajson from", "= \"**procedimiento_id**: \" \\ \"Identificador único del procedimiento\" self.assertEqual(result, expected) # elimino campo", "test_field_to_markdown(self): field = { \"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del procedimiento\"", "unicode_literals from __future__ import print_function from __future__ import with_statement import os.path import unittest", "campo de type field.pop(\"type\") result = field_to_markdown(field) expected = \"**procedimiento_id**: \" \\ \"Identificador", "contrataciones electrónicas\\n\\n' \\ '#### Campos del recurso\\n\\n' \\ '- **procedimiento_id** (integer): Identificador único", "el año 2016 en el \" \"sistema de contrataciones \" \"electrónicas\", }]} result", "SAMPLES_DIR = os.path.join(\"tests\", \"samples\") RESULTS_DIR = os.path.join(\"tests\", \"results\") def test_field_to_markdown(self): field = {", "' \\ 'Identificador único de la unidad operativa de ' \\ 'contrataciones\\n\\n'\\ '###", "' \\ 'único del procedimiento\\n'\\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de", "from pydatajson.documentation import distribution_to_markdown from pydatajson.documentation import dataset_to_markdown class DocumentationTestCase(unittest.TestCase): SAMPLES_DIR = os.path.join(\"tests\",", "**procedimiento_id** (integer): Identificador único ' \\ 'del procedimiento\\n' \\ '- **unidad_operativa_contrataciones_id** (integer): '", "'2015 en el sistema de contrataciones electrónicas\\n\\n' \\ '#### Campos del recurso\\n\\n' \\", "\" \"sistema de contrataciones \" \"electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador", "{\"title\": \"Convocatorias abiertas durante el \" \"año 2016\", \"description\": \"Listado de las convocatorias", "\"Listado de las convocatorias abiertas \" \"durante el año 2015 en el sistema", "\\ 'contrataciones\\n\\n'\\ '### Convocatorias abiertas durante el año 2016\\n\\n'\\ 'Listado de las convocatorias", "único de la\" \" unidad operativa de \" \"contrataciones\"}]}, {\"title\": \"Convocatorias abiertas durante", "Compra)\\n\\n'\\ '## Recursos del dataset\\n\\n\\n'\\ '### Convocatorias abiertas durante el año 2015\\n\\n'\\ 'Listado", "self.assertEqual(result, expected) # elimino campo de type field.pop(\"type\") result = field_to_markdown(field) expected =", "\"Sistema de contrataciones electrónicas\", \"description\": \"Datos correspondientes al Sistema de \" \"Contrataciones Electrónicas", "\"Identificador único de la \" \"unidad operativa de \" \"contrataciones\"}]} result = distribution_to_markdown(distribution)", "(integer): ' \\ 'Identificador único de la unidad operativa de ' \\ 'contrataciones\\n\\n'\\", "Sistema de \" \"Contrataciones Electrónicas (Argentina Compra)\", \"distribution\": [{\"title\": \"Convocatorias abiertas durante \"", "= field_to_markdown(field) expected = \"**procedimiento_id**: \" \\ \"Identificador único del procedimiento\" self.assertEqual(result, expected)", "**unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de la unidad operativa de ' \\", "abiertas durante el año ' \\ '2016 en el sistema de contrataciones electrónicas\\n\\n'\\", "de' \\ ' contrataciones\\n' self.assertEqual(result, expected) # elimino campos no obligatiorios distribution.pop(\"field\") distribution.pop(\"description\")", "único del procedimiento\" } result = field_to_markdown(field) expected = \"**procedimiento_id** (integer): \" \\", "durante el año 2015\\n\\n' \\ 'Listado de las convocatorias abiertas durante el año", "'contrataciones\\n\\n'\\ '### Convocatorias abiertas durante el año 2016\\n\\n'\\ 'Listado de las convocatorias abiertas", "# elimino campo de type field.pop(\"type\") result = field_to_markdown(field) expected = \"**procedimiento_id**: \"", "contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso\\n\\n'\\ '- **procedimiento_id** (integer): Identificador ' \\ 'único", "import unittest import nose from .context import pydatajson from pydatajson.documentation import field_to_markdown from", "\"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de la\" \" unidad operativa de \"", "\"abiertas durante el año 2016 en el \" \"sistema de contrataciones \" \"electrónicas\",", "del recurso\\n\\n'\\ '- **procedimiento_id** (integer): Identificador ' \\ 'único del procedimiento\\n'\\ '- **unidad_operativa_contrataciones_id**", "class DocumentationTestCase(unittest.TestCase): SAMPLES_DIR = os.path.join(\"tests\", \"samples\") RESULTS_DIR = os.path.join(\"tests\", \"results\") def test_field_to_markdown(self): field", "' \\ '2015 en el sistema de contrataciones electrónicas\\n\\n' \\ '#### Campos del", "expected) # elimino campo de description field.pop(\"description\") result = field_to_markdown(field) expected = \"**procedimiento_id**\"", "en el \" \"sistema de contrataciones \" \"electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\",", "' \\ 'Identificador único de la unidad operativa de' \\ ' contrataciones\\n' self.assertEqual(result,", "abiertas durante el año 2016\\n\\n'\\ 'Listado de las convocatorias abiertas durante el año", "convocatorias abiertas \" \"durante el año 2015 en el sistema de \" \"contrataciones", "Campos del recurso\\n\\n' \\ '- **procedimiento_id** (integer): Identificador único ' \\ 'del procedimiento\\n'", "al Sistema de \" \"Contrataciones Electrónicas (Argentina Compra)\", \"distribution\": [{\"title\": \"Convocatorias abiertas durante", "\" \\ \"Identificador único del procedimiento\" self.assertEqual(result, expected) # elimino campo de type", "distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante el año 2015\\n\\n' \\ 'Listado de", "de \" \"Contrataciones Electrónicas (Argentina Compra)\", \"distribution\": [{\"title\": \"Convocatorias abiertas durante \" \"el", "2016 en el \" \"sistema de contrataciones \" \"electrónicas\", }]} result = dataset_to_markdown(dataset)", "\"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del procedimiento\" } result = field_to_markdown(field) expected", "de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso' self.assertEqual.__self__.maxDiff = None self.assertEqual(result.strip(), expected.strip()) if", "\"Identificador único del \" \"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único", "las convocatorias \" \"abiertas durante el año 2016 en el \" \"sistema de", "__future__ import unicode_literals from __future__ import print_function from __future__ import with_statement import os.path", "self.assertEqual(result.strip(), expected.strip()) def test_dataset_to_markdown(self): dataset = {\"title\": \"Sistema de contrataciones electrónicas\", \"description\": \"Datos", "contrataciones \" \"electrónicas\", }]} result = dataset_to_markdown(dataset) expected = '\\n# Sistema de contrataciones", "Convocatorias abiertas durante el año 2015\\n\\n'\\ 'Listado de las convocatorias abiertas durante el", "'- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de la unidad operativa de' \\", "\" \"abiertas durante el año 2016 en el \" \"sistema de contrataciones \"", "'### Convocatorias abiertas durante el año 2016\\n\\n'\\ 'Listado de las convocatorias abiertas durante", "' \\ '2015 en el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso\\n\\n'\\", "= os.path.join(\"tests\", \"results\") def test_field_to_markdown(self): field = { \"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\":", "durante el año ' \\ '2015 en el sistema de contrataciones electrónicas\\n\\n' \\", "las convocatorias abiertas durante el año ' \\ '2016 en el sistema de", "RESULTS_DIR = os.path.join(\"tests\", \"results\") def test_field_to_markdown(self): field = { \"title\": \"procedimiento_id\", \"type\": \"integer\",", "las convocatorias abiertas durante el año ' \\ '2015 en el sistema de", "durante el \" \"año 2016\", \"description\": \"Listado de las convocatorias \" \"abiertas durante", "\"Identificador único del procedimiento\" self.assertEqual(result, expected) # elimino campo de description field.pop(\"description\") result", "el año 2015 en el sistema de \" \"contrataciones electrónicas\", \"field\": [{\"title\": \"procedimiento_id\",", "al Sistema de Contrataciones ' \\ 'Electrónicas (Argentina Compra)\\n\\n'\\ '## Recursos del dataset\\n\\n\\n'\\", "de description field.pop(\"description\") result = field_to_markdown(field) expected = \"**procedimiento_id**\" self.assertEqual(result, expected) def test_distribution_to_markdown(self):", "Convocatorias abiertas durante el año 2015\\n\\n' \\ 'Listado de las convocatorias abiertas durante", "expected = '\\n### Convocatorias abiertas durante el año 2015\\n\\n' \\ '\\n\\n#### Campos del", "recurso' print(result) self.assertEqual(result.strip(), expected.strip()) def test_dataset_to_markdown(self): dataset = {\"title\": \"Sistema de contrataciones electrónicas\",", "\"description\": \"Identificador único del \" \"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador", "del \" \"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de la", "\"durante el año 2015 en el sistema de \" \"contrataciones electrónicas\", \"field\": [{\"title\":", "del modulo pydatajson.\"\"\" from __future__ import unicode_literals from __future__ import print_function from __future__", "= field_to_markdown(field) expected = \"**procedimiento_id** (integer): \" \\ \"Identificador único del procedimiento\" self.assertEqual(result,", "pydatajson.documentation import distribution_to_markdown from pydatajson.documentation import dataset_to_markdown class DocumentationTestCase(unittest.TestCase): SAMPLES_DIR = os.path.join(\"tests\", \"samples\")", "el año ' \\ '2016 en el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos", "2015 en el \" \"sistema de contrataciones \" \"electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\":", "import unicode_literals from __future__ import print_function from __future__ import with_statement import os.path import", "\"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del \" \"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\":", "from pydatajson.documentation import field_to_markdown from pydatajson.documentation import distribution_to_markdown from pydatajson.documentation import dataset_to_markdown class", "del \" \"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de la\"", "[{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del \" \"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\",", "from pydatajson.documentation import dataset_to_markdown class DocumentationTestCase(unittest.TestCase): SAMPLES_DIR = os.path.join(\"tests\", \"samples\") RESULTS_DIR = os.path.join(\"tests\",", "de contrataciones \" \"electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del", "' \\ '2016 en el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso'", "import nose from .context import pydatajson from pydatajson.documentation import field_to_markdown from pydatajson.documentation import", ".context import pydatajson from pydatajson.documentation import field_to_markdown from pydatajson.documentation import distribution_to_markdown from pydatajson.documentation", "\"results\") def test_field_to_markdown(self): field = { \"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único", "Sistema de contrataciones electrónicas\\n\\n'\\ 'Datos correspondientes al Sistema de Contrataciones ' \\ 'Electrónicas", "\\ '- **procedimiento_id** (integer): Identificador único ' \\ 'del procedimiento\\n' \\ '- **unidad_operativa_contrataciones_id**", "expected = '\\n### Convocatorias abiertas durante el año 2015\\n\\n' \\ 'Listado de las", "from .context import pydatajson from pydatajson.documentation import field_to_markdown from pydatajson.documentation import distribution_to_markdown from", "**unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de la unidad operativa de' \\ '", "\"unidad operativa de \" \"contrataciones\"}]} result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas", "el sistema de contrataciones electrónicas\\n\\n' \\ '#### Campos del recurso\\n\\n' \\ '- **procedimiento_id**", "result = dataset_to_markdown(dataset) expected = '\\n# Sistema de contrataciones electrónicas\\n\\n'\\ 'Datos correspondientes al", "\"distribution\": [{\"title\": \"Convocatorias abiertas durante \" \"el año 2015\", \"description\": \"Listado de las", "unidad operativa de' \\ ' contrataciones\\n' self.assertEqual(result, expected) # elimino campos no obligatiorios", "-*- \"\"\"Tests del modulo pydatajson.\"\"\" from __future__ import unicode_literals from __future__ import print_function", "\"description\": \"Listado de las convocatorias abiertas \" \"durante el año 2015 en el", "<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\"Tests del modulo pydatajson.\"\"\" from", "sistema de \" \"contrataciones electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único", "# elimino campo de description field.pop(\"description\") result = field_to_markdown(field) expected = \"**procedimiento_id**\" self.assertEqual(result,", "expected) def test_distribution_to_markdown(self): distribution = {\"title\": \"Convocatorias abiertas durante el año 2015\", \"description\":", "electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del \" \"procedimiento\"}, {\"title\":", "Convocatorias abiertas durante el año 2016\\n\\n'\\ 'Listado de las convocatorias abiertas durante el", "convocatorias abiertas durante el año ' \\ '2016 en el sistema de contrataciones", "'Electrónicas (Argentina Compra)\\n\\n'\\ '## Recursos del dataset\\n\\n\\n'\\ '### Convocatorias abiertas durante el año", "año 2015\", \"description\": \"Listado de las convocatorias abiertas \" \"durante el año 2015", "en el \" \"sistema de contrataciones \" \"electrónicas\", }]} result = dataset_to_markdown(dataset) expected", "' \\ 'contrataciones\\n\\n'\\ '### Convocatorias abiertas durante el año 2016\\n\\n'\\ 'Listado de las", "'2016 en el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso' self.assertEqual.__self__.maxDiff =", "**procedimiento_id** (integer): Identificador ' \\ 'único del procedimiento\\n'\\ '- **unidad_operativa_contrataciones_id** (integer): ' \\", "durante el año 2016\\n\\n'\\ 'Listado de las convocatorias abiertas durante el año '", "type field.pop(\"type\") result = field_to_markdown(field) expected = \"**procedimiento_id**: \" \\ \"Identificador único del", "' \\ 'Electrónicas (Argentina Compra)\\n\\n'\\ '## Recursos del dataset\\n\\n\\n'\\ '### Convocatorias abiertas durante", "\"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de la \" \"unidad operativa de", "único del procedimiento\" self.assertEqual(result, expected) # elimino campo de type field.pop(\"type\") result =", "sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso\\n\\n'\\ '- **procedimiento_id** (integer): Identificador '", "la unidad operativa de ' \\ 'contrataciones\\n\\n'\\ '### Convocatorias abiertas durante el año", "print_function from __future__ import with_statement import os.path import unittest import nose from .context", "contrataciones\\n' self.assertEqual(result, expected) # elimino campos no obligatiorios distribution.pop(\"field\") distribution.pop(\"description\") result = distribution_to_markdown(distribution)", "abiertas durante el año 2015\", \"description\": \"Listado de las convocatorias abiertas \" \"durante", "\"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de la\" \" unidad operativa de", "operativa de \" \"contrataciones\"}]}, {\"title\": \"Convocatorias abiertas durante el \" \"año 2016\", \"description\":", "año ' \\ '2015 en el sistema de contrataciones electrónicas\\n\\n' \\ '#### Campos", "único de la \" \"unidad operativa de \" \"contrataciones\"}]} result = distribution_to_markdown(distribution) expected", "nose from .context import pydatajson from pydatajson.documentation import field_to_markdown from pydatajson.documentation import distribution_to_markdown", "el año 2015\\n\\n'\\ 'Listado de las convocatorias abiertas durante el año ' \\", "\" \"Contrataciones Electrónicas (Argentina Compra)\", \"distribution\": [{\"title\": \"Convocatorias abiertas durante \" \"el año", "\" \"unidad operativa de \" \"contrataciones\"}]} result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias", "el año 2015\\n\\n' \\ '\\n\\n#### Campos del recurso' print(result) self.assertEqual(result.strip(), expected.strip()) def test_dataset_to_markdown(self):", "(Argentina Compra)\\n\\n'\\ '## Recursos del dataset\\n\\n\\n'\\ '### Convocatorias abiertas durante el año 2015\\n\\n'\\", "\"type\": \"integer\", \"description\": \"Identificador único del \" \"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\",", "no obligatiorios distribution.pop(\"field\") distribution.pop(\"description\") result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante", "2016\", \"description\": \"Listado de las convocatorias \" \"abiertas durante el año 2016 en", "= { \"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del procedimiento\" } result", "\\ '2016 en el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso' self.assertEqual.__self__.maxDiff", "self.assertEqual(result, expected) def test_distribution_to_markdown(self): distribution = {\"title\": \"Convocatorias abiertas durante el año 2015\",", "DocumentationTestCase(unittest.TestCase): SAMPLES_DIR = os.path.join(\"tests\", \"samples\") RESULTS_DIR = os.path.join(\"tests\", \"results\") def test_field_to_markdown(self): field =", "durante el año 2015\", \"description\": \"Listado de las convocatorias abiertas \" \"durante el", "campo de description field.pop(\"description\") result = field_to_markdown(field) expected = \"**procedimiento_id**\" self.assertEqual(result, expected) def", "\"contrataciones\"}]}, {\"title\": \"Convocatorias abiertas durante el \" \"año 2016\", \"description\": \"Listado de las", "procedimiento\" } result = field_to_markdown(field) expected = \"**procedimiento_id** (integer): \" \\ \"Identificador único", "Campos del recurso' print(result) self.assertEqual(result.strip(), expected.strip()) def test_dataset_to_markdown(self): dataset = {\"title\": \"Sistema de", "abiertas durante el año 2015\\n\\n' \\ '\\n\\n#### Campos del recurso' print(result) self.assertEqual(result.strip(), expected.strip())", "en el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso\\n\\n'\\ '- **procedimiento_id** (integer):", "'Identificador único de la unidad operativa de' \\ ' contrataciones\\n' self.assertEqual(result, expected) #", "\\ 'Identificador único de la unidad operativa de' \\ ' contrataciones\\n' self.assertEqual(result, expected)", "\"el año 2015\", \"description\": \"Listado de las convocatorias \" \"abiertas durante el año", "= {\"title\": \"Convocatorias abiertas durante el año 2015\", \"description\": \"Listado de las convocatorias", "' \\ 'del procedimiento\\n' \\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de", "from __future__ import with_statement import os.path import unittest import nose from .context import", "result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante el año 2015\\n\\n' \\", "de \" \"contrataciones\"}]} result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante el", "' contrataciones\\n' self.assertEqual(result, expected) # elimino campos no obligatiorios distribution.pop(\"field\") distribution.pop(\"description\") result =", "operativa de \" \"contrataciones\"}]} result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante", "\\ 'Electrónicas (Argentina Compra)\\n\\n'\\ '## Recursos del dataset\\n\\n\\n'\\ '### Convocatorias abiertas durante el", "la unidad operativa de' \\ ' contrataciones\\n' self.assertEqual(result, expected) # elimino campos no", "2015 en el sistema de \" \"contrataciones electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\",", "las convocatorias \" \"abiertas durante el año 2015 en el \" \"sistema de", "\" \"contrataciones electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del \"", "with_statement import os.path import unittest import nose from .context import pydatajson from pydatajson.documentation", "expected = \"**procedimiento_id**: \" \\ \"Identificador único del procedimiento\" self.assertEqual(result, expected) # elimino", "= \"**procedimiento_id** (integer): \" \\ \"Identificador único del procedimiento\" self.assertEqual(result, expected) # elimino", "\"type\": \"integer\", \"description\": \"Identificador único del procedimiento\" } result = field_to_markdown(field) expected =", "'\\n\\n#### Campos del recurso' print(result) self.assertEqual(result.strip(), expected.strip()) def test_dataset_to_markdown(self): dataset = {\"title\": \"Sistema", "elimino campos no obligatiorios distribution.pop(\"field\") distribution.pop(\"description\") result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias", "\"description\": \"Identificador único del procedimiento\" } result = field_to_markdown(field) expected = \"**procedimiento_id** (integer):", "\"Contrataciones Electrónicas (Argentina Compra)\", \"distribution\": [{\"title\": \"Convocatorias abiertas durante \" \"el año 2015\",", "from __future__ import unicode_literals from __future__ import print_function from __future__ import with_statement import", "de la unidad operativa de' \\ ' contrataciones\\n' self.assertEqual(result, expected) # elimino campos", "2015\\n\\n' \\ 'Listado de las convocatorias abiertas durante el año ' \\ '2015", "2016\\n\\n'\\ 'Listado de las convocatorias abiertas durante el año ' \\ '2016 en", "del recurso' print(result) self.assertEqual(result.strip(), expected.strip()) def test_dataset_to_markdown(self): dataset = {\"title\": \"Sistema de contrataciones", "\" \"electrónicas\", }]} result = dataset_to_markdown(dataset) expected = '\\n# Sistema de contrataciones electrónicas\\n\\n'\\", "durante \" \"el año 2015\", \"description\": \"Listado de las convocatorias \" \"abiertas durante", "field.pop(\"description\") result = field_to_markdown(field) expected = \"**procedimiento_id**\" self.assertEqual(result, expected) def test_distribution_to_markdown(self): distribution =", "'del procedimiento\\n' \\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de la unidad", "año 2015\\n\\n'\\ 'Listado de las convocatorias abiertas durante el año ' \\ '2015", "self.assertEqual(result, expected) # elimino campo de description field.pop(\"description\") result = field_to_markdown(field) expected =", "durante el año 2016 en el \" \"sistema de contrataciones \" \"electrónicas\", }]}", "el año 2015\", \"description\": \"Listado de las convocatorias abiertas \" \"durante el año", "año ' \\ '2016 en el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del", "'Listado de las convocatorias abiertas durante el año ' \\ '2016 en el", "del recurso\\n\\n' \\ '- **procedimiento_id** (integer): Identificador único ' \\ 'del procedimiento\\n' \\", "obligatiorios distribution.pop(\"field\") distribution.pop(\"description\") result = distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante el", "el año 2016\\n\\n'\\ 'Listado de las convocatorias abiertas durante el año ' \\", "\"integer\", \"description\": \"Identificador único de la\" \" unidad operativa de \" \"contrataciones\"}]}, {\"title\":", "= \"**procedimiento_id**\" self.assertEqual(result, expected) def test_distribution_to_markdown(self): distribution = {\"title\": \"Convocatorias abiertas durante el", "(integer): ' \\ 'Identificador único de la unidad operativa de' \\ ' contrataciones\\n'", "\"Datos correspondientes al Sistema de \" \"Contrataciones Electrónicas (Argentina Compra)\", \"distribution\": [{\"title\": \"Convocatorias", "dataset = {\"title\": \"Sistema de contrataciones electrónicas\", \"description\": \"Datos correspondientes al Sistema de", "de la unidad operativa de ' \\ 'contrataciones\\n\\n'\\ '### Convocatorias abiertas durante el", "abiertas durante \" \"el año 2015\", \"description\": \"Listado de las convocatorias \" \"abiertas", "Identificador ' \\ 'único del procedimiento\\n'\\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único", "expected = \"**procedimiento_id** (integer): \" \\ \"Identificador único del procedimiento\" self.assertEqual(result, expected) #", "\"**procedimiento_id**: \" \\ \"Identificador único del procedimiento\" self.assertEqual(result, expected) # elimino campo de", "field_to_markdown(field) expected = \"**procedimiento_id**\" self.assertEqual(result, expected) def test_distribution_to_markdown(self): distribution = {\"title\": \"Convocatorias abiertas", "el año ' \\ '2015 en el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos", "\" \"durante el año 2015 en el sistema de \" \"contrataciones electrónicas\", \"field\":", "\"Convocatorias abiertas durante \" \"el año 2015\", \"description\": \"Listado de las convocatorias \"", "#!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\"Tests del modulo pydatajson.\"\"\" from __future__", "durante el año 2015\\n\\n'\\ 'Listado de las convocatorias abiertas durante el año '", "= field_to_markdown(field) expected = \"**procedimiento_id**\" self.assertEqual(result, expected) def test_distribution_to_markdown(self): distribution = {\"title\": \"Convocatorias", "año ' \\ '2015 en el sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del", "\" \"abiertas durante el año 2015 en el \" \"sistema de contrataciones \"", "\" \"sistema de contrataciones \" \"electrónicas\", }]} result = dataset_to_markdown(dataset) expected = '\\n#", "único de la unidad operativa de ' \\ 'contrataciones\\n\\n'\\ '### Convocatorias abiertas durante", "import dataset_to_markdown class DocumentationTestCase(unittest.TestCase): SAMPLES_DIR = os.path.join(\"tests\", \"samples\") RESULTS_DIR = os.path.join(\"tests\", \"results\") def", "\\ \"Identificador único del procedimiento\" self.assertEqual(result, expected) # elimino campo de description field.pop(\"description\")", "'Listado de las convocatorias abiertas durante el año ' \\ '2015 en el", "Identificador único ' \\ 'del procedimiento\\n' \\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador", "sistema de contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso' self.assertEqual.__self__.maxDiff = None self.assertEqual(result.strip(), expected.strip())", "electrónicas\\n\\n'\\ '#### Campos del recurso\\n\\n'\\ '- **procedimiento_id** (integer): Identificador ' \\ 'único del", "Electrónicas (Argentina Compra)\", \"distribution\": [{\"title\": \"Convocatorias abiertas durante \" \"el año 2015\", \"description\":", "unidad operativa de \" \"contrataciones\"}]}, {\"title\": \"Convocatorias abiertas durante el \" \"año 2016\",", "import print_function from __future__ import with_statement import os.path import unittest import nose from", "unidad operativa de ' \\ 'contrataciones\\n\\n'\\ '### Convocatorias abiertas durante el año 2016\\n\\n'\\", "expected) # elimino campo de type field.pop(\"type\") result = field_to_markdown(field) expected = \"**procedimiento_id**:", "\"description\": \"Datos correspondientes al Sistema de \" \"Contrataciones Electrónicas (Argentina Compra)\", \"distribution\": [{\"title\":", "\"Listado de las convocatorias \" \"abiertas durante el año 2015 en el \"", "import field_to_markdown from pydatajson.documentation import distribution_to_markdown from pydatajson.documentation import dataset_to_markdown class DocumentationTestCase(unittest.TestCase): SAMPLES_DIR", "field_to_markdown(field) expected = \"**procedimiento_id**: \" \\ \"Identificador único del procedimiento\" self.assertEqual(result, expected) #", "'- **procedimiento_id** (integer): Identificador ' \\ 'único del procedimiento\\n'\\ '- **unidad_operativa_contrataciones_id** (integer): '", "único del \" \"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de", "Contrataciones ' \\ 'Electrónicas (Argentina Compra)\\n\\n'\\ '## Recursos del dataset\\n\\n\\n'\\ '### Convocatorias abiertas", "2015\", \"description\": \"Listado de las convocatorias \" \"abiertas durante el año 2015 en", "año 2016\\n\\n'\\ 'Listado de las convocatorias abiertas durante el año ' \\ '2016", "\"sistema de contrataciones \" \"electrónicas\", }]} result = dataset_to_markdown(dataset) expected = '\\n# Sistema", "import distribution_to_markdown from pydatajson.documentation import dataset_to_markdown class DocumentationTestCase(unittest.TestCase): SAMPLES_DIR = os.path.join(\"tests\", \"samples\") RESULTS_DIR", "Convocatorias abiertas durante el año 2015\\n\\n' \\ '\\n\\n#### Campos del recurso' print(result) self.assertEqual(result.strip(),", "contrataciones electrónicas\\n\\n'\\ '#### Campos del recurso' self.assertEqual.__self__.maxDiff = None self.assertEqual(result.strip(), expected.strip()) if __name__", "pydatajson.documentation import field_to_markdown from pydatajson.documentation import distribution_to_markdown from pydatajson.documentation import dataset_to_markdown class DocumentationTestCase(unittest.TestCase):", "año 2015\", \"description\": \"Listado de las convocatorias \" \"abiertas durante el año 2015", "{\"title\": \"Sistema de contrataciones electrónicas\", \"description\": \"Datos correspondientes al Sistema de \" \"Contrataciones", "= '\\n### Convocatorias abiertas durante el año 2015\\n\\n' \\ 'Listado de las convocatorias", "= '\\n# Sistema de contrataciones electrónicas\\n\\n'\\ 'Datos correspondientes al Sistema de Contrataciones '", "operativa de' \\ ' contrataciones\\n' self.assertEqual(result, expected) # elimino campos no obligatiorios distribution.pop(\"field\")", "operativa de ' \\ 'contrataciones\\n\\n'\\ '### Convocatorias abiertas durante el año 2016\\n\\n'\\ 'Listado", "año 2016 en el \" \"sistema de contrataciones \" \"electrónicas\", }]} result =", "el \" \"sistema de contrataciones \" \"electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\":", "del procedimiento\" self.assertEqual(result, expected) # elimino campo de description field.pop(\"description\") result = field_to_markdown(field)", "Sistema de Contrataciones ' \\ 'Electrónicas (Argentina Compra)\\n\\n'\\ '## Recursos del dataset\\n\\n\\n'\\ '###", "expected = '\\n# Sistema de contrataciones electrónicas\\n\\n'\\ 'Datos correspondientes al Sistema de Contrataciones", "\"Identificador único de la\" \" unidad operativa de \" \"contrataciones\"}]}, {\"title\": \"Convocatorias abiertas", "electrónicas\\n\\n' \\ '#### Campos del recurso\\n\\n' \\ '- **procedimiento_id** (integer): Identificador único '", "'#### Campos del recurso\\n\\n'\\ '- **procedimiento_id** (integer): Identificador ' \\ 'único del procedimiento\\n'\\", "= '\\n### Convocatorias abiertas durante el año 2015\\n\\n' \\ '\\n\\n#### Campos del recurso'", "\"description\": \"Identificador único de la\" \" unidad operativa de \" \"contrataciones\"}]}, {\"title\": \"Convocatorias", "año 2015\\n\\n' \\ 'Listado de las convocatorias abiertas durante el año ' \\", "las convocatorias abiertas \" \"durante el año 2015 en el sistema de \"", "distribution_to_markdown from pydatajson.documentation import dataset_to_markdown class DocumentationTestCase(unittest.TestCase): SAMPLES_DIR = os.path.join(\"tests\", \"samples\") RESULTS_DIR =", "\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del procedimiento\" } result = field_to_markdown(field)", "\"Listado de las convocatorias \" \"abiertas durante el año 2016 en el \"", "de contrataciones electrónicas\", \"description\": \"Datos correspondientes al Sistema de \" \"Contrataciones Electrónicas (Argentina", "test_dataset_to_markdown(self): dataset = {\"title\": \"Sistema de contrataciones electrónicas\", \"description\": \"Datos correspondientes al Sistema", "\\ '2015 en el sistema de contrataciones electrónicas\\n\\n' \\ '#### Campos del recurso\\n\\n'", "dataset\\n\\n\\n'\\ '### Convocatorias abiertas durante el año 2015\\n\\n'\\ 'Listado de las convocatorias abiertas", "field_to_markdown from pydatajson.documentation import distribution_to_markdown from pydatajson.documentation import dataset_to_markdown class DocumentationTestCase(unittest.TestCase): SAMPLES_DIR =", "\\ 'del procedimiento\\n' \\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de la", "contrataciones \" \"electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del \"", "\" \"año 2016\", \"description\": \"Listado de las convocatorias \" \"abiertas durante el año", "convocatorias \" \"abiertas durante el año 2015 en el \" \"sistema de contrataciones", "'\\n# Sistema de contrataciones electrónicas\\n\\n'\\ 'Datos correspondientes al Sistema de Contrataciones ' \\", "Campos del recurso' self.assertEqual.__self__.maxDiff = None self.assertEqual(result.strip(), expected.strip()) if __name__ == '__main__': nose.run(defaultTest=__name__)", "único ' \\ 'del procedimiento\\n' \\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único", "convocatorias abiertas durante el año ' \\ '2015 en el sistema de contrataciones", "def test_field_to_markdown(self): field = { \"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del", "de \" \"contrataciones electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del", "abiertas durante el año ' \\ '2015 en el sistema de contrataciones electrónicas\\n\\n'\\", "\"electrónicas\", }]} result = dataset_to_markdown(dataset) expected = '\\n# Sistema de contrataciones electrónicas\\n\\n'\\ 'Datos", "2015\\n\\n' \\ '\\n\\n#### Campos del recurso' print(result) self.assertEqual(result.strip(), expected.strip()) def test_dataset_to_markdown(self): dataset =", "de las convocatorias \" \"abiertas durante el año 2016 en el \" \"sistema", "electrónicas\", \"description\": \"Datos correspondientes al Sistema de \" \"Contrataciones Electrónicas (Argentina Compra)\", \"distribution\":", "test_distribution_to_markdown(self): distribution = {\"title\": \"Convocatorias abiertas durante el año 2015\", \"description\": \"Listado de", "\"integer\", \"description\": \"Identificador único de la \" \"unidad operativa de \" \"contrataciones\"}]} result", "\\ 'Identificador único de la unidad operativa de ' \\ 'contrataciones\\n\\n'\\ '### Convocatorias", "la \" \"unidad operativa de \" \"contrataciones\"}]} result = distribution_to_markdown(distribution) expected = '\\n###", "= os.path.join(\"tests\", \"samples\") RESULTS_DIR = os.path.join(\"tests\", \"results\") def test_field_to_markdown(self): field = { \"title\":", "la\" \" unidad operativa de \" \"contrataciones\"}]}, {\"title\": \"Convocatorias abiertas durante el \"", "\"electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del \" \"procedimiento\"}, {\"title\":", "\\ \"Identificador único del procedimiento\" self.assertEqual(result, expected) # elimino campo de type field.pop(\"type\")", "2015\", \"description\": \"Listado de las convocatorias abiertas \" \"durante el año 2015 en", "= distribution_to_markdown(distribution) expected = '\\n### Convocatorias abiertas durante el año 2015\\n\\n' \\ 'Listado", "\"Identificador único del procedimiento\" self.assertEqual(result, expected) # elimino campo de type field.pop(\"type\") result", "'#### Campos del recurso' self.assertEqual.__self__.maxDiff = None self.assertEqual(result.strip(), expected.strip()) if __name__ == '__main__':", "\"procedimiento\"}, {\"title\": \"unidad_operativa_\" \"contrataciones_id\", \"type\": \"integer\", \"description\": \"Identificador único de la \" \"unidad", "el \" \"año 2016\", \"description\": \"Listado de las convocatorias \" \"abiertas durante el", "\"type\": \"integer\", \"description\": \"Identificador único de la \" \"unidad operativa de \" \"contrataciones\"}]}", "'### Convocatorias abiertas durante el año 2015\\n\\n'\\ 'Listado de las convocatorias abiertas durante", "procedimiento\" self.assertEqual(result, expected) # elimino campo de description field.pop(\"description\") result = field_to_markdown(field) expected", "# -*- coding: utf-8 -*- \"\"\"Tests del modulo pydatajson.\"\"\" from __future__ import unicode_literals", "el año 2015\\n\\n' \\ 'Listado de las convocatorias abiertas durante el año '", "\"contrataciones electrónicas\", \"field\": [{\"title\": \"procedimiento_id\", \"type\": \"integer\", \"description\": \"Identificador único del \" \"procedimiento\"},", "(integer): Identificador ' \\ 'único del procedimiento\\n'\\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador", "procedimiento\\n' \\ '- **unidad_operativa_contrataciones_id** (integer): ' \\ 'Identificador único de la unidad operativa", "expected) # elimino campos no obligatiorios distribution.pop(\"field\") distribution.pop(\"description\") result = distribution_to_markdown(distribution) expected =", "de las convocatorias \" \"abiertas durante el año 2015 en el \" \"sistema", "dataset_to_markdown class DocumentationTestCase(unittest.TestCase): SAMPLES_DIR = os.path.join(\"tests\", \"samples\") RESULTS_DIR = os.path.join(\"tests\", \"results\") def test_field_to_markdown(self):", "'#### Campos del recurso\\n\\n' \\ '- **procedimiento_id** (integer): Identificador único ' \\ 'del", "import pydatajson from pydatajson.documentation import field_to_markdown from pydatajson.documentation import distribution_to_markdown from pydatajson.documentation import", "único de la unidad operativa de' \\ ' contrataciones\\n' self.assertEqual(result, expected) # elimino", "'- **procedimiento_id** (integer): Identificador único ' \\ 'del procedimiento\\n' \\ '- **unidad_operativa_contrataciones_id** (integer):" ]
[ "choice = raw_input(\"Which mail box do you want to open: \") try: if", "the email list in the format (box number or uid number): Subject: This", "= int(choice) if mail_type == 0: recv_body = imap_fetch(str(ch) + \" BODY[1]\") recv_header", "\"2\": date_opt = \"ON\" elif when_ch == \"3\": date_opt = \"SINCE\" cmd =", "while still getting data else: time.sleep(0.1)#give a slight pause before trying to read", "= imap_create(name) if recv.find(\"OK Success\") != -1: print \"Created \" + name +", "get_mail_boxnum() elif choice == \"6\": if currentFolder == \"None\": print \"\\nNo mail box", "raw_input(\"Which mail box do you want to open: \") try: if int(choice) <", "+ \":\" + mailbox_list[index] + \" \" + info[index] index = index +", "+ str(current_page+1) + '/' + str(max_pages) print_mail_list_with_subject(mail_nums, mailboxes_info, start, end) print \"\\nTo view", "= raw_input(\"Are you sure you want to delete \" + name + \"", "== 0: recv = imap_search(str(ch) + ' SEEN') else: recv = imap_uid_search(str(ch) +", "-1: print \"Successfully logged in to: \" + username + \"\\n\" return 1", "reversed(range(len(recv))): #Loop from the end til it find the A if recv[index] ==", "imap_uid_store(x): print 'A003 UID STORE ' + x + '\\r\\n' sslSocket.send('A003 UID STORE", "recv = imap_examine(x) tmp = recv.split(\" \") amtExist = 'N/A' amtRecent = 'N/A'", "raw_input(\"Which email do you want to open? \") if choice == 'NEXT' or", "date_opt = \"SINCE\" cmd = date_opt + ' ' + date_ch if search_type", "recv_body = imap_fetch(str(ch) + \" BODY[1]\") recv_header = imap_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE", "def imap_examine(x): sslSocket.send('A900 EXAMINE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) return", "[\"All\", \"Unread\", \"Old\", \"Drafts\", \"Text\", \"Date\"] print \"\\n------------------------------\" print \"Search by:\" inc =", "Create socket called clientSocket and establish a TCP connection with mailserver #Fill in", "= 1 while again == 1: again = 1 start = current_page *", "= sslSocket.recv(1024) if data: #if there is some data that was received then", "recv = imap_uid_store(msg_uid + ' -FLAGS (\\seen)') elif choice == \"2\": #delete recv", "#Mail Client Methods ################################# def view_mailboxes(): mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info", "if the mail box has child boxes def has_children(strg, mailbox_list): for s in", "\"What would you like to do? (0 to quit.)\" print \"1: View all", "== 'NEXT' or choice == 'next': again = 1 if current_page < max_pages-1:", "+ \" and all children.(1=yes, 2=no)\") if decision == \"1\": delete_all_children_with_child(name, mail_list) cmd", "== search #1 == UID search imap_examine(currentFolder) options = [\"All\", \"Unread\", \"Old\", \"Drafts\",", "filter_list_of_subjects(subject_list) max_pages = int(len(mail_nums)/email_list_length) if (len(mail_nums)%email_list_length) > 0: max_pages += 1 current_page =", "is empty.\" choice = raw_input('\\nWhich email do you want to copy: ') choice_dest", "again = 1 start = current_page * email_list_length + 1 end = start", "#Create def imap_create(x): sslSocket.send('A401 CREATE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024)", "print_mailboxes_list_with_info(mail_list, mailboxes_info) def examine_mailbox(): global currentFolder mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info", "+= str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] subject_list = imap_uid_fetch(string_list +", "== \"2\": examine_mailbox() elif choice == \"3\": if currentFolder == \"None\": print \"\\nNo", "elif when_ch == \"2\": date_opt = \"ON\" elif when_ch == \"3\": date_opt =", "recv_body = imap_uid_fetch(str(ch) + \" BODY[1]\") recv_header = imap_uid_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE", "imap_uid_search(x): sslSocket.send('A999 UID SEARCH ' + x + '\\r\\n') recv = recv_all() return", "pass return temp_list #Return the text of the email body def format_email_body(recv): first", "= l.find('\\nSubject: ')+1 pos2 = l.find('\\r') new = l[pos1:pos2] if new != '':", "do? (0 to quit.)\" print \"1: View all mail boxes\" print \"2: Examine", "again = 1 if current_page > 0: current_page-=1 else: again = 0 else:", "pos2 = recv.find('\\r') r = recv[pos1:pos2] tmp = r.split(' ') temp_list = []", "(len(mail_nums)%email_list_length) > 0: max_pages += 1 current_page = 0 again = 1 while", "+ ' Recent: ' + amtRecent + ')')#Add the formated string to the", "# Choose a mail server (e.g. Google mail server) and call it mailserver", "'OLD' #drafts elif choice == \"3\": cmd = 'DRAFT' #text elif choice ==", "mail server) and call it mailserver mailserver = ('imap.163.com', 143) # Create socket", "new != '': li.append(new) l = l[pos2+1:] return li def email_is_read(mail_type, ch):#0 ==", "l.find('\\nSubject: ') != -1: pos1 = l.find('\\nSubject: ')+1 pos2 = l.find('\\r') new =", "print \"\\nNot a valid mail box.\" def get_mail_boxnum(): get_mail(0) def get_mail_uid(): get_mail(1) def", "search_mail(search_type):#0 == search #1 == UID search imap_examine(currentFolder) options = [\"All\", \"Unread\", \"Old\",", "pos2 = recv.find('\\r') r = recv[pos1:pos2] if r != '': return True else:", "if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails:' string_list = '' for x in range(len(mail_nums)):", "\"---------------------------------\" #Print the email list in the format (box number or uid number):", "sure you want to delete \" + name + \" and all children.(1=yes,", "get_mail_numbers_from_search(recv) if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails:' string_list = '' for x in", "+ x + '\"\\r\\n') recv = sslSocket.recv(1024) return recv #Delete def imap_delete(x): print", "for t in tmp: try: temp_list.append(int(t)) except: pass return temp_list #Return the text", "the end til it find the A if recv[index] == 'A': last =", "elif choice == \"3\": if currentFolder == \"None\": print \"\\nNo mail box selected.\"", "print \"---------------------------------\" print \"Mail Boxes:\" index = 0 while index < len(mailbox_list): print", "set it to the end of the list end = len(subs) while start", "\"\\n\" return 1 else: print \"Login failed!\\n\" return -1 #List def imap_list(dir =", "\"1\": view_mailboxes() elif choice == \"2\": examine_mailbox() elif choice == \"3\": if currentFolder", "delete_all_children_with_child(strg, mailbox_list): for s in mailbox_list: if s.find(strg) != -1: imap_delete(s) def filter_list_of_subjects(l):", "new mailbox to create:\") recv = imap_create(name) if recv.find(\"OK Success\") != -1: print", "== \"None\": print \"\\nNo mail box selected.\" else: search_mail_uid_search() elif choice == \"5\":", "= \"SINCE\" cmd = date_opt + ' ' + date_ch if search_type ==", "probably nothing to get, so stop elif time.time()-begin > timeout*2: break #try and", "UID search imap_examine(currentFolder) options = [\"All\", \"Unread\", \"Old\", \"Drafts\", \"Text\", \"Date\"] print \"\\n------------------------------\"", "subject def print_mail_list_with_subject(nums, subs, start = 1, end = -1):#nums = the numbers", "= \"ON\" elif when_ch == \"3\": date_opt = \"SINCE\" cmd = date_opt +", "box (AND) doesn't contain the /Noselect flag (And) isn't the all mail folder", "' + username + ' ' + password + '\\r\\n') recv = sslSocket.recv(1024)", "information def print_mailboxes_list_with_info(mailbox_list, info): print \"\" print \"---------------------------------\" print \"Mail Boxes:\" index =", "Delete = 2, Leave as is = 3\" choice = raw_input(\"Choice: \") if", "read print email_read if email_read: print \"\\nMark as unread = 1, Delete =", "str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] if mail_type == 0: subject_list", "server try: data = sslSocket.recv(1024) if data: #if there is some data that", "is the string returned from the imap_list command def get_mailbox_list_array(mailbox_string): temp_list = mailbox_string.split('\\r\\n')#Split", "<= end:#Print the specified elements of the lists print str(nums[start-1]) + \": \"", "\"all\" else: cmd = \"\" else: cmd = name except: cmd = \"\"", "cmd = 'TEXT \"' + search_text + '\"' #date elif choice == \"5\":", "[] if l.find('\\nSubject: ') != -1: tmp = l.find('\\nSubject: ') l = l[tmp:]", "timeout: break #If no data has been retrieved and it has passed the", "mailbox_string = imap_list(\"/\", \"*\") mail_list = get_mailbox_list_array(mailbox_string) print_mailboxes_list(mail_list) choice = raw_input(\"Enter the number", "server (e.g. Google mail server) and call it mailserver mailserver = ('imap.163.com', 143)", "'A501 DELETE \"' + x + '\"\\r\\n' sslSocket.send('A501 DELETE \"' + x +", "pos2 = recv_uid.find(')') msg_uid = recv_uid[pos:pos2] print \"Email UID: \" + msg_uid pos", "DELETE \"' + x + '\"\\r\\n' sslSocket.send('A501 DELETE \"' + x + '\"\\r\\n')", "\" \" + info[index] index = index + 1 print \"---------------------------------\" #Print the", "mailboxes_info) choice = raw_input(\"Which mail box do you want to open: \") try:", "Delete a mail box\" print \"9: Copy email from selected mail box to", "= \"*\"):#return list of mailboxes with optional parameters to change what is listed", "l.find('\\nSubject: ') l = l[tmp:] while l.find('\\nSubject: ') != -1: pos1 = l.find('\\nSubject:", "UID recv = '' if mail_type == 0: recv = imap_search(str(ch) + '", "+' '+ type + '\\r\\n') recv = recv_all() return recv #Search def imap_search(x):", "search_mail_search() elif choice == \"4\": if currentFolder == \"None\": print \"\\nNo mail box", "print recv imap_expunge() else: print \"\\nMark as read = 1, Delete = 2,", "ssl, base64, sys, time, math print \"Connecting..\" username = \"\" password = \"\"", "and x.find('[Gmail]/All Mail') == -1:#The line has a mail box (AND) doesn't contain", "= imap_uid_store(msg_uid + ' -FLAGS (\\seen)') elif choice == \"2\": #delete recv =", "\"9\": copy_mail() elif choice == \"10\": testing() if choice == \"0\": close_mail() if", "else: recv = imap_uid_search(cmd) mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0: string_list =", "you like to do? (0 to quit.)\" print \"1: View all mail boxes\"", "r != '': return True else: return False ################################# #Mail Client Methods #################################", "True return False def delete_all_children_with_child(strg, mailbox_list): for s in mailbox_list: if s.find(strg) !=", "\" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid = imap_uid_fetch(str(ch) + \" (UID)\") print", "mail_type == 0: recv = imap_search(str(ch) + ' SEEN') else: recv = imap_uid_search(str(ch)", "so that it doesn't timeout while still getting data else: time.sleep(0.1)#give a slight", "'\\n-------------------------------\\nEmails~ Page: ' + str(current_page+1) + '/' + str(max_pages) print_mail_list_with_subject(mail_nums, mailboxes_info, start, end)", "# Create socket called clientSocket and establish a TCP connection with mailserver #Fill", "you want to delete \" + name + \" and all children.(1=yes, 2=no)\")", "#Done connecting ################################# ################################# #Global Variables ################################# currentFolder = \"None\" #Stores the currently", "from') != -1: print \"Connected.\\n\" else: print \"Problem connecting.\\n\" ################################# #Done connecting #################################", "has been retrieved and it has passed the timeout by 2, then there", "the currently selected mail box ################################# #imap Methods ################################# def imap_login():#login print(\"Login information:\")", "\":\" + mailbox_list[index] index = index + 1 print \"---------------------------------\" #Print the mailbox", "to copy: ') choice_dest = raw_input('To which folder: ') try: if len(mail_nums)+2 >", "to another\" choice = raw_input(\"Choice: \") if choice == \"1\": view_mailboxes() elif choice", "' SEEN') else: recv = imap_uid_search(str(ch) + ' SEEN') pos1 = recv.find('SEARCH')+7 pos2", "= l.find('\\nSubject: ') l = l[tmp:] while l.find('\\nSubject: ') != -1: pos1 =", "if recv.find(\"completed\") != -1: print \"Successfully logged in to: \" + username +", "print \"Created \" + name + \"!\" else: print \"Failed to create.\" def", "def search_mail_uid_search(): search_mail(1) def search_mail(search_type):#0 == search #1 == UID search imap_examine(currentFolder) options", "string returned from the imap_list command def get_mailbox_list_array(mailbox_string): temp_list = mailbox_string.split('\\r\\n')#Split the returned", "date_opt = \"BEFORE\" elif when_ch == \"2\": date_opt = \"ON\" elif when_ch ==", "connecting.\\n\" ################################# #Done connecting ################################# ################################# #Global Variables ################################# currentFolder = \"None\" #Stores", "start <= end:#Print the specified elements of the lists print str(nums[start-1]) + \":", "print \"\" print \"---------------------------------\" print \"Mail Boxes:\" index = 0 while index <", "= raw_input(\"(Before date = 1)(On date = 2)(Since date = 3):\") date_ch =", "connecting ################################# ################################# #Global Variables ################################# currentFolder = \"None\" #Stores the currently selected", "\"\" #The main loop while choice != \"0\": print \"\\n\" print \"---------------------------------------------\" print", "if mail_type == 0: recv = imap_search(str(ch) + ' SEEN') else: recv =", "temp_list = mailbox_string.split('\\r\\n')#Split the returned string by the new line indicators del temp_list[len(temp_list)-1]#The", "ready for requests from') != -1: print \"Connected.\\n\" else: print \"Problem connecting.\\n\" #################################", "################################# #Receive using a timeout def recv_all(timeout = 2):#can either pass a different", "\"0\": print \"\\n\" print \"---------------------------------------------\" print \"-- Currently Selected Mailbox: \" + currentFolder", "the list of info for the emails for x in mail_list: recv =", "+FLAGS (\\deleted)') print recv imap_expunge() except: print \"Email not available.\" def create_dir(): name", "x + '\"\\r\\n') recv = sslSocket.recv(1024) return recv #Fetch def imap_fetch(x): sslSocket.send('A301 FETCH", "a mail server (e.g. Google mail server) and call it mailserver mailserver =", "in a list def print_mailboxes_list(mailbox_list): print \"\" print \"---------------------------------\" print \"Mail Boxes:\" index", "mail_list): decision = raw_input(\"Are you sure you want to delete \" + name", "imap_delete(s) def filter_list_of_subjects(l): li = [] if l.find('\\nSubject: ') != -1: tmp =", "print \"-- Currently Selected Mailbox: \" + currentFolder print \"---------------------------------------------\" print \"What would", "+ name + \" and all children.(1=yes, 2=no)\") if decision == \"1\": delete_all_children_with_child(name,", "\" + name + \"!\" else: print \"Failed to delete.\" def search_mail_search(): search_mail(0)", "string_list[:-1] if search_type == 0: subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") else:", "################################# currentFolder = \"None\" #Stores the currently selected mail box ################################# #imap Methods", "= \"\" # Choose a mail server (e.g. Google mail server) and call", "1 #Get how many emails each mailbox contains def get_mailboxes_info_array(mail_list): mail_info_list = []", "== \"1\": #mark as unread recv = imap_uid_store(msg_uid + ' -FLAGS (\\seen)') elif", "if string_list: string_list = string_list[:-1] subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info", "== \"5\": if currentFolder == \"None\": print \"\\nNo mail box selected.\" else: get_mail_boxnum()", "print \"Mail Boxes:\" index = 0 while index < len(mailbox_list): print str(index) +", "type = \"*\"):#return list of mailboxes with optional parameters to change what is", "mail box\" print \"9: Copy email from selected mail box to another\" choice", "global sslSocket #set the socket to non-blocking sslSocket.setblocking(0) #array of the data received", "box is empty.\" choice = raw_input('\\nWhich email do you want to copy: ')", "#just let it reloop if there was an error thrown #set the socket", "text: \") cmd = 'TEXT \"' + search_text + '\"' #date elif choice", "int(choice) > 0: print imap_uid_copy(choice + ' ' + choice_dest) else: print \"Not", "+ '\"\\r\\n') recv = sslSocket.recv(1024) return recv #Fetch def imap_fetch(x): sslSocket.send('A301 FETCH '", "a slight pause before trying to read again except: pass #just let it", "when_ch == \"3\": date_opt = \"SINCE\" cmd = date_opt + ' ' +", "the emails, subs = the subjects of the emails if end == -1:#If", "ssl.PROTOCOL_SSLv23) sslSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sslSocket.connect(mailserver) recv = sslSocket.recv(1024) if recv.find('OK Gimap ready", "do you want to open? \") if choice == 'NEXT' or choice ==", "sslSocket.send('A999 UID SEARCH ' + x + '\\r\\n') recv = recv_all() return recv", "recv[index] == 'A': last = index - 5 break return recv[first:last] #Return true", "tmp = l.find('\\nSubject: ') l = l[tmp:] while l.find('\\nSubject: ') != -1: pos1", "!= -1: print \"Deleted \" + name + \"!\" else: print \"Failed to", "recv #Fetch def imap_fetch(x): sslSocket.send('A301 FETCH ' + x + '\\r\\n') recv =", "before trying to read again except: pass #just let it reloop if there", "max_pages += 1 current_page = 0 again = 1 while again == 1:", "mail boxes\" print \"2: Examine a mail box\" print \"3: Search selected mail", "email from selected mail box to another\" choice = raw_input(\"Choice: \") if choice", "print \"6: Get mail from selected mail box using unique id\" print \"7:", "else: return False ################################# #Mail Client Methods ################################# def view_mailboxes(): mailbox_string = imap_list()", "amtRecent = tmp[19] except: pass mail_info_list.append('(Emails: ' + amtExist + ' Recent: '", "+ currentFolder print \"---------------------------------------------\" print \"What would you like to do? (0 to", "= raw_input(\"Enter the number for the box to delete: \") try: ch_num =", "[] for t in tmp: try: temp_list.append(int(t)) except: pass return temp_list #Return the", "SUBJECT FROM TO)]\") recv_uid = imap_uid_fetch(str(ch) + \" (UID)\") print \"\\n===============================================================================\" pos =", "print '\\n-------------------------------\\nEmails:' string_list = '' for x in range(len(mail_nums)): string_list += str(mail_nums[x]) +", "= recv_uid.find('(UID')+5 pos2 = recv_uid.find(')') msg_uid = recv_uid[pos:pos2] print \"Email UID: \" +", "2):#can either pass a different timeout or use the default set in the", "\"--------------------------------------------------------------------\" print format_email_body(recv_body) print \"===============================================================================\\n\" email_read = email_is_read(mail_type, ch)#0 == norm #1 ==", "choice == \"2\": examine_mailbox() elif choice == \"3\": if currentFolder == \"None\": print", "again == 1: again = 1 start = current_page * email_list_length + 1", "begin = time.time() #loop till the timeout has passed while True: #If some", "= sslSocket.recv(1024) if recv.find('OK Gimap ready for requests from') != -1: print \"Connected.\\n\"", "with additional information def print_mailboxes_list_with_info(mailbox_list, info): print \"\" print \"---------------------------------\" print \"Mail Boxes:\"", "print \"What would you like to do? (0 to quit.)\" print \"1: View", "is probably nothing to get, so stop elif time.time()-begin > timeout*2: break #try", "len(mail_list): currentFolder = mail_list[int(choice)] print \"\\nSelected \" + currentFolder else: print \"\\nNot a", "1 if current_page < max_pages-1: current_page+=1 elif choice == 'PREV' or choice ==", "else: again = 0 else: print \"Mail box is empty.\" again = 0", "max_pages = int(len(mail_nums)/email_list_length) if (len(mail_nums)%email_list_length) > 0: max_pages += 1 current_page = 0", "info): print \"\" print \"---------------------------------\" print \"Mail Boxes:\" index = 0 while index", "box ################################# #imap Methods ################################# def imap_login():#login print(\"Login information:\") username = \"<EMAIL>\" password", "mailboxes_info) def examine_mailbox(): global currentFolder mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info =", "= recv.split(\" \") amtExist = 'N/A' amtRecent = 'N/A' try: amtExist = tmp[17]", "there was an error thrown #set the socket back to blocking since only", "to the end of the list end = len(subs) while start <= len(nums)", "default set in the parameter global sslSocket #set the socket to non-blocking sslSocket.setblocking(0)", "print_mailboxes_list(mail_list) choice = raw_input(\"Enter the number for the box to delete: \") try:", "has passed the timeout by 2, then there is probably nothing to get,", "some data that was received then store that data data_str += data begin=time.time()#reset", "of the email body def format_email_body(recv): first = 0 last = len(recv)-1 if", "recv = sslSocket.recv(1024) return recv #Fetch def imap_fetch(x): sslSocket.send('A301 FETCH ' + x", "if currentFolder == \"None\": print \"\\nNo mail box selected.\" else: get_mail_uid() elif choice", "print recv #Select def imap_select(x): sslSocket.send('A142 SELECT \"' + x + '\"\\r\\n') recv", "of the line containing the mailbox name return mail_list #Print the mailbox names", "== \"\": print \"\\nNo Box chosen\" if cmd == \"all\": print \"Deleted\" else:", "data = sslSocket.recv(1024) if data: #if there is some data that was received", "method is designed for non=blocking sslSocket.setblocking(1) return data_str #Returns a list containing the", "sslSocket.setblocking(1) return data_str #Returns a list containing the mailbox names #The parameter is", "+ name + \"!\" else: print \"Failed to delete.\" def search_mail_search(): search_mail(0) def", "selected mail box ################################# #imap Methods ################################# def imap_login():#login print(\"Login information:\") username =", "BODY[1]\") recv_header = imap_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid =", "cmd == \"all\": print \"Deleted\" else: imap_delete(cmd) if recv.find(\"OK Success\") != -1: print", "sslSocket.send('A003 UID STORE ' + x + '\\r\\n') recv = sslSocket.recv(1024) print recv", "\"4: Search using message unique id\" print \"5: Get mail from selected mail", "* email_list_length + 1 end = start + email_list_length - 1 if len(mail_nums)", "the A if recv[index] == 'A': last = index - 5 break return", "format (box number or uid number): Subject: This is the email subject def", "name + \"!\" else: print \"Failed to create.\" def delete_dir(): mailbox_string = imap_list(\"/\",", "\"Email not available.\" def create_dir(): name = raw_input(\"\\nName of new mailbox to create:\")", "line containing the mailbox name return mail_list #Print the mailbox names in a", "View all mail boxes\" print \"2: Examine a mail box\" print \"3: Search", "as is = 3\" choice = raw_input(\"Choice: \") if choice == \"1\": #mark", "log_success == -1: close_mail() return 0 choice = \"\" #The main loop while", "= get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) def examine_mailbox(): global currentFolder mailbox_string =", "\"3\": date_opt = \"SINCE\" cmd = date_opt + ' ' + date_ch if", "in the parameter global sslSocket #set the socket to non-blocking sslSocket.setblocking(0) #array of", "of mailboxes with optional parameters to change what is listed sslSocket.send('A101 List '", "for text: \") cmd = 'TEXT \"' + search_text + '\"' #date elif", "1, end = -1):#nums = the numbers of the emails, subs = the", "to catch errors with getting data from the server try: data = sslSocket.recv(1024)", "list end = len(subs) while start <= len(nums) and start <= end:#Print the", "A if recv[index] == 'A': last = index - 5 break return recv[first:last]", "date_ch = raw_input(\"Date(dd-mm-yyyy)(ex. 1-Sep-2013):\") date_opt = \"ON\" if when_ch == \"1\": date_opt =", "= index - 5 break return recv[first:last] #Return true if the mail box", "NEXT or PREV\" choice = raw_input(\"Which email do you want to open? \")", "raw_input(\"Search for text: \") cmd = 'TEXT \"' + search_text + '\"' #date", "(AND) doesn't contain the /Noselect flag (And) isn't the all mail folder pos", "!= -1: print \"Successfully logged in to: \" + username + \"\\n\" return", "\"Mail box is empty.\" again = 0 if len(mail_nums) > 0: try: ch", "\"Problem connecting.\\n\" ################################# #Done connecting ################################# ################################# #Global Variables ################################# currentFolder = \"None\"", "= imap_login() if log_success == -1: close_mail() return 0 choice = \"\" #The", "== 1: again = 1 start = current_page * email_list_length + 1 end", "imap_fetch(str(ch) + \" (UID)\") else: recv_body = imap_uid_fetch(str(ch) + \" BODY[1]\") recv_header =", "print \"\\nNo mail box selected.\" else: get_mail_uid() elif choice == \"7\": create_dir() elif", "= \"all\" else: cmd = \"\" else: cmd = name except: cmd =", "current_page * email_list_length + 1 end = start + email_list_length - 1 if", "\") if choice == \"1\": view_mailboxes() elif choice == \"2\": examine_mailbox() elif choice", "+ \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid = imap_fetch(str(ch) + \" (UID)\")", "\"Deleted \" + name + \"!\" else: print \"Failed to delete.\" def search_mail_search():", "isn't the all mail folder pos = x.find('/\" \"')+4 mail_list.append(x[pos:-1]) #Store the substring", "+ '\\r\\n') recv = recv_all() return recv #Search def imap_search(x): sslSocket.send('A201 SEARCH '", "mail_list: recv = imap_examine(x) tmp = recv.split(\" \") amtExist = 'N/A' amtRecent =", "\"5: Get mail from selected mail box\" print \"6: Get mail from selected", "+ ' -FLAGS (\\seen)') elif choice == \"2\": #delete recv = imap_uid_store(msg_uid +", "that data data_str += data begin=time.time()#reset the begin time so that it doesn't", "non-blocking sslSocket.setblocking(0) #array of the data received data_str = '' #time this method", "open? \") if choice == 'NEXT' or choice == 'next': again = 1", "x + '\\r\\n') recv = recv_all() return recv #Examine def imap_examine(x): sslSocket.send('A900 EXAMINE", "+ date_ch if search_type == 0: recv = imap_search(cmd) else: recv = imap_uid_search(cmd)", "in the params, set it to the end of the list end =", "cmd = 'DRAFT' #text elif choice == \"4\": search_text = raw_input(\"Search for text:", "imap_fetch(str(ch) + \" BODY[1]\") recv_header = imap_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM", "\"Failed to create.\" def delete_dir(): mailbox_string = imap_list(\"/\", \"*\") mail_list = get_mailbox_list_array(mailbox_string) print_mailboxes_list(mail_list)", "sslSocket.send('A900 EXAMINE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) return recv #Fetch", "get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) def examine_mailbox(): global currentFolder mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string)", "+ \"\\n\" return 1 else: print \"Login failed!\\n\" return -1 #List def imap_list(dir", "= \"\" #all if choice == \"0\": cmd = 'ALL' #unread elif choice", "print \"Successfully logged in to: \" + username + \"\\n\" return 1 else:", "for index in reversed(range(len(recv))): #Loop from the end til it find the A", "#Returns a list containing the mailbox names #The parameter is the string returned", "'A': last = index - 5 break return recv[first:last] #Return true if the", "decision = raw_input(\"Are you sure you want to delete \" + name +", "== \"all\": print \"Deleted\" else: imap_delete(cmd) if recv.find(\"OK Success\") != -1: print \"Deleted", "= 'N/A' try: amtExist = tmp[17] amtRecent = tmp[19] except: pass mail_info_list.append('(Emails: '", "search_mail_search(): search_mail(0) def search_mail_uid_search(): search_mail(1) def search_mail(search_type):#0 == search #1 == UID search", "slight pause before trying to read again except: pass #just let it reloop", "= imap_examine(x) tmp = recv.split(\" \") amtExist = 'N/A' amtRecent = 'N/A' try:", "recv_all() return recv #UID Fetch def imap_uid_fetch(x): sslSocket.send('A999 UID FETCH ' + x", "in the list wasn't specified in the params, set it to the end", "using message unique id\" print \"5: Get mail from selected mail box\" print", "r = recv[pos1:pos2] if r != '': return True else: return False #################################", "folder pos = x.find('/\" \"')+4 mail_list.append(x[pos:-1]) #Store the substring of the line containing", "str(subs[start-1]) start += 1 #Get how many emails each mailbox contains def get_mailboxes_info_array(mail_list):", "recv_header.find('OK Success\\r\\n')-11 print recv_header[pos:pos2] print \"--------------------------------------------------------------------\" print format_email_body(recv_body) print \"===============================================================================\\n\" email_read = email_is_read(mail_type,", "to change what is listed sslSocket.send('A101 List ' + \"\\\"\\\"\" +' '+ type", "str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] if search_type == 0: subject_list", "else: recv_body = imap_uid_fetch(str(ch) + \" BODY[1]\") recv_header = imap_uid_fetch(str(ch) + \" BODY[HEADER.FIELDS", "\"\\nNo mail box selected.\" else: search_mail_uid_search() elif choice == \"5\": if currentFolder ==", "\"Done.\" #Main Method def main(): log_success = imap_login() if log_success == -1: close_mail()", "\": \" + str(subs[start-1]) start += 1 #Get how many emails each mailbox", "the first } first = recv.find('}') + 3 for index in reversed(range(len(recv))): #Loop", "[]#Will hold the list of mailbox names to be returned for x in", "def imap_uid_store(x): print 'A003 UID STORE ' + x + '\\r\\n' sslSocket.send('A003 UID", "the end of the list end = len(subs) while start <= len(nums) and", "get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) choice = raw_input(\"Which mail box do you", "= recv_all() return recv #UID Store def imap_uid_store(x): print 'A003 UID STORE '", "\"\\n\" print \"---------------------------------------------\" print \"-- Currently Selected Mailbox: \" + currentFolder print \"---------------------------------------------\"", "= ('imap.163.com', 143) # Create socket called clientSocket and establish a TCP connection", "!= '': return True else: return False ################################# #Mail Client Methods ################################# def", "date = 3):\") date_ch = raw_input(\"Date(dd-mm-yyyy)(ex. 1-Sep-2013):\") date_opt = \"ON\" if when_ch ==", "try: data = sslSocket.recv(1024) if data: #if there is some data that was", "SEARCH ' + x + '\\r\\n') recv = recv_all() return recv #Expunge def", "-1 and x.find('\\Noselect') == -1 and x.find('[Gmail]/All Mail') == -1:#The line has a", "(\\seen)') elif choice == \"2\": #delete recv = imap_uid_store(msg_uid + ' +FLAGS (\\deleted)')", "to create:\") recv = imap_create(name) if recv.find(\"OK Success\") != -1: print \"Created \"", "get_mailboxes_info_array(mail_list): mail_info_list = [] #Holds the list of info for the emails for", "+ str(max_pages) print_mail_list_with_subject(mail_nums, mailboxes_info, start, end) print \"\\nTo view more mail type, NEXT", "#Extra Methods ################################# #Receive using a timeout def recv_all(timeout = 2):#can either pass", "from the search command def get_mail_numbers_from_search(recv): pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r", "recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2] if r != '': return True", "index + 1 print \"---------------------------------\" #Print the email list in the format (box", "recv #UID Copy def imap_uid_copy(x): sslSocket.send('A300 COPY \"' + x + '\"\\r\\n') recv", "data received data_str = '' #time this method started begin = time.time() #loop", "STORE ' + x + '\\r\\n') recv = sslSocket.recv(1024) print recv return recv", "\"---------------------------------------------\" print \"-- Currently Selected Mailbox: \" + currentFolder print \"---------------------------------------------\" print \"What", "' + str(current_page+1) + '/' + str(max_pages) print_mail_list_with_subject(mail_nums, mailboxes_info, start, end) print \"\\nTo", "line has a mail box (AND) doesn't contain the /Noselect flag (And) isn't", "time.time() #loop till the timeout has passed while True: #If some data was", "number or uid number): Subject: This is the email subject def print_mail_list_with_subject(nums, subs,", "= \"\" print \"Checking: \" + cmd if cmd == \"\": print \"\\nNo", "has child boxes def has_children(strg, mailbox_list): for s in mailbox_list: if s.find(strg) !=", "x + '\\r\\n') recv = recv_all() return recv #UID Store def imap_uid_store(x): print", "if mail_type == 0: recv_body = imap_fetch(str(ch) + \" BODY[1]\") recv_header = imap_fetch(str(ch)", "time so that it doesn't timeout while still getting data else: time.sleep(0.1)#give a", "def search_mail(search_type):#0 == search #1 == UID search imap_examine(currentFolder) options = [\"All\", \"Unread\",", "again except: pass #just let it reloop if there was an error thrown", "print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box is empty.\" def copy_mail(): imap_examine(currentFolder) recv =", "end = len(subs) while start <= len(nums) and start <= end:#Print the specified", "#unread elif choice == \"1\": cmd = 'UNSEEN' #old elif choice == \"2\":", "-1 #List def imap_list(dir = \"\", type = \"*\"):#return list of mailboxes with", "mail_type == 0: subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") else: subject_list =", "2, then there is probably nothing to get, so stop elif time.time()-begin >", "the params, set it to the end of the list end = len(subs)", "imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print recv imap_expunge() except: print \"Email not available.\"", "list return mail_info_list #Return a string of the numbers returned from the search", "<= len(nums) and start <= end:#Print the specified elements of the lists print", "imap_list(\"/\", \"*\") mail_list = get_mailbox_list_array(mailbox_string) print_mailboxes_list(mail_list) choice = raw_input(\"Enter the number for the", "\"Connecting..\" username = \"\" password = \"\" # Choose a mail server (e.g.", "search imap_examine(currentFolder) options = [\"All\", \"Unread\", \"Old\", \"Drafts\", \"Text\", \"Date\"] print \"\\n------------------------------\" print", "if data: #if there is some data that was received then store that", "currently selected mail box ################################# #imap Methods ################################# def imap_login():#login print(\"Login information:\") username", "0: recv = imap_search(str(ch) + ' SEEN') else: recv = imap_uid_search(str(ch) + '", "unique id\" print \"7: Create a mail box\" print \"8: Delete a mail", "pos1 = l.find('\\nSubject: ')+1 pos2 = l.find('\\r') new = l[pos1:pos2] if new !=", "#UID Search def imap_uid_search(x): sslSocket.send('A999 UID SEARCH ' + x + '\\r\\n') recv", "sslSocket.send('A301 FETCH ' + x + '\\r\\n') recv = recv_all() return recv #Create", "for s in mailbox_list: if s.find(strg) != -1 and strg != s: return", "search #1 == UID search imap_select(currentFolder) email_list_length = 10 if mail_type == 0:", "+ username + ' ' + password + '\\r\\n') recv = sslSocket.recv(1024) if", "delete_dir() elif choice == \"9\": copy_mail() elif choice == \"10\": testing() if choice", "'\\r\\n') recv = recv_all() return recv #Search def imap_search(x): sslSocket.send('A201 SEARCH ' +", "\"None\": print \"\\nNo mail box selected.\" else: get_mail_boxnum() elif choice == \"6\": if", "to delete.\" def search_mail_search(): search_mail(0) def search_mail_uid_search(): search_mail(1) def search_mail(search_type):#0 == search #1", "UID SEARCH ' + x + '\\r\\n') recv = recv_all() return recv #Expunge", "' + x + '\\r\\n') recv = recv_all() return recv #Examine def imap_examine(x):", "\"4\": if currentFolder == \"None\": print \"\\nNo mail box selected.\" else: search_mail_uid_search() elif", "from selected mail box using unique id\" print \"7: Create a mail box\"", "mailbox name return mail_list #Print the mailbox names in a list def print_mailboxes_list(mailbox_list):", "returned for x in temp_list: if x.find('/\" \"') != -1 and x.find('\\Noselect') ==", "+ '\\r\\n') recv = recv_all() return recv #Examine def imap_examine(x): sslSocket.send('A900 EXAMINE \"'", "of the numbers returned from the search command def get_mail_numbers_from_search(recv): pos1 = recv.find('SEARCH')+7", "socket.SOCK_STREAM) sslSocket.connect(mailserver) recv = sslSocket.recv(1024) if recv.find('OK Gimap ready for requests from') !=", "= r.split(' ') temp_list = [] for t in tmp: try: temp_list.append(int(t)) except:", "print(\"Attempting to login.\\n\") sslSocket.send('A001 LOGIN ' + username + ' ' + password", "box selected.\" else: get_mail_boxnum() elif choice == \"6\": if currentFolder == \"None\": print", "s: return True return False def delete_all_children_with_child(strg, mailbox_list): for s in mailbox_list: if", "' +FLAGS (\\deleted)') print recv imap_expunge() except: print \"Email not available.\" def create_dir():", "parameter global sslSocket #set the socket to non-blocking sslSocket.setblocking(0) #array of the data", "it has passed the timeout by 2, then there is probably nothing to", "pos = x.find('/\" \"')+4 mail_list.append(x[pos:-1]) #Store the substring of the line containing the", "= [\"All\", \"Unread\", \"Old\", \"Drafts\", \"Text\", \"Date\"] print \"\\n------------------------------\" print \"Search by:\" inc", "index in reversed(range(len(recv))): #Loop from the end til it find the A if", "r.split(' ') temp_list = [] for t in tmp: try: temp_list.append(int(t)) except: pass", "format_email_body(recv): first = 0 last = len(recv)-1 if recv.find('}') != -1:#Find the first", "getting data else: time.sleep(0.1)#give a slight pause before trying to read again except:", "= inc + 1 print \"------------------------------\" choice = raw_input(\"Choice: \") cmd = \"\"", "> 0: string_list = '' for x in range(len(mail_nums)): string_list += str(mail_nums[x]) +", "username + \"\\n\" return 1 else: print \"Login failed!\\n\" return -1 #List def", "s in mailbox_list: if s.find(strg) != -1 and strg != s: return True", "information:\") username = \"<EMAIL>\" password = \"password\" print(\"Attempting to login.\\n\") sslSocket.send('A001 LOGIN '", "email_list_length + 1 end = start + email_list_length - 1 if len(mail_nums) >", "or choice == 'prev': again = 1 if current_page > 0: current_page-=1 else:", "#Select def imap_select(x): sslSocket.send('A142 SELECT \"' + x + '\"\\r\\n') recv = recv_all()", "names in a list def print_mailboxes_list(mailbox_list): print \"\" print \"---------------------------------\" print \"Mail Boxes:\"", "2=no)\") if decision == \"1\": delete_all_children_with_child(name, mail_list) cmd = \"all\" else: cmd =", "TCP connection with mailserver #Fill in start #sslSocket = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), #ssl_version =", "3):\") date_ch = raw_input(\"Date(dd-mm-yyyy)(ex. 1-Sep-2013):\") date_opt = \"ON\" if when_ch == \"1\": date_opt", "= l.find('\\r') new = l[pos1:pos2] if new != '': li.append(new) l = l[pos2+1:]", "if recv.find('OK Gimap ready for requests from') != -1: print \"Connected.\\n\" else: print", "range(len(mail_nums)): string_list += str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] subject_list =", "recv.find('\\r') r = recv[pos1:pos2] if r != '': return True else: return False", "= 2)(Since date = 3):\") date_ch = raw_input(\"Date(dd-mm-yyyy)(ex. 1-Sep-2013):\") date_opt = \"ON\" if", "+ '\\r\\n') recv = recv_all() return recv #UID Store def imap_uid_store(x): print 'A003", "date_ch if search_type == 0: recv = imap_search(cmd) else: recv = imap_uid_search(cmd) mail_nums", "def imap_create(x): sslSocket.send('A401 CREATE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) return", "reloop if there was an error thrown #set the socket back to blocking", "a timeout def recv_all(timeout = 2):#can either pass a different timeout or use", "print \"\\n===============================================================================\" pos = recv_uid.find('(UID')+5 pos2 = recv_uid.find(')') msg_uid = recv_uid[pos:pos2] print \"Email", "use the default set in the parameter global sslSocket #set the socket to", "sslSocket.recv(1024) return recv #Fetch def imap_fetch(x): sslSocket.send('A301 FETCH ' + x + '\\r\\n')", "= imap_uid_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid = imap_uid_fetch(str(ch) +", "delete \" + name + \" and all children.(1=yes, 2=no)\") if decision ==", "if s.find(strg) != -1: imap_delete(s) def filter_list_of_subjects(l): li = [] if l.find('\\nSubject: ')", "#mark as unread recv = imap_uid_store(msg_uid + ' -FLAGS (\\seen)') elif choice ==", "\"<EMAIL>\" password = \"password\" print(\"Attempting to login.\\n\") sslSocket.send('A001 LOGIN ' + username +", "2, Leave as is = 3\" choice = raw_input(\"Choice: \") if choice ==", "+ \"\\\"\\\"\" +' '+ type + '\\r\\n') recv = recv_all() return recv #Search", "\") if choice == \"1\": #mark as unread recv = imap_uid_store(msg_uid + '", "else: print \"Login failed!\\n\" return -1 #List def imap_list(dir = \"\", type =", "'A003 UID STORE ' + x + '\\r\\n' sslSocket.send('A003 UID STORE ' +", "and it passed the timeout, then stop if data_str and time.time()-begin > timeout:", "choice = \"\" #The main loop while choice != \"0\": print \"\\n\" print", "= imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) string_list = '' for x in range(len(mail_nums)): string_list", "email list in the format (box number or uid number): Subject: This is", "if choice == 'NEXT' or choice == 'next': again = 1 if current_page", "== \"10\": testing() if choice == \"0\": close_mail() if __name__ == '__main__': main()", "current_page = 0 again = 1 while again == 1: again = 1", "FETCH ' + x + '\\r\\n') recv = recv_all() return recv #UID Store", "= \"password\" print(\"Attempting to login.\\n\") sslSocket.send('A001 LOGIN ' + username + ' '", "the numbers returned from the search command def get_mail_numbers_from_search(recv): pos1 = recv.find('SEARCH')+7 pos2", "mailbox contains def get_mailboxes_info_array(mail_list): mail_info_list = [] #Holds the list of info for", "+ 3 for index in reversed(range(len(recv))): #Loop from the end til it find", "\"\\nNot a valid mail box.\" except: print \"\\nNot a valid mail box.\" def", "it doesn't timeout while still getting data else: time.sleep(0.1)#give a slight pause before", "pos2 = recv_header.find('OK Success\\r\\n')-11 print recv_header[pos:pos2] print \"--------------------------------------------------------------------\" print format_email_body(recv_body) print \"===============================================================================\\n\" email_read", "choice = raw_input('\\nWhich email do you want to copy: ') choice_dest = raw_input('To", "\"None\": print \"\\nNo mail box selected.\" else: search_mail_search() elif choice == \"4\": if", "'\"\\r\\n') recv = recv_all() return recv ################################# #Extra Methods ################################# #Receive using a", "= '' #time this method started begin = time.time() #loop till the timeout", "\" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box is", "print 'A501 DELETE \"' + x + '\"\\r\\n' sslSocket.send('A501 DELETE \"' + x", "is the email subject def print_mail_list_with_subject(nums, subs, start = 1, end = -1):#nums", "else: print \"Not a valid email.\" except: print \"Invalid input.\" def testing(): imap_expunge()", "= len(recv)-1 if recv.find('}') != -1:#Find the first } first = recv.find('}') +", "tmp = recv.split(\" \") amtExist = 'N/A' amtRecent = 'N/A' try: amtExist =", "mailserver mailserver = ('imap.163.com', 143) # Create socket called clientSocket and establish a", "if new != '': li.append(new) l = l[pos2+1:] return li def email_is_read(mail_type, ch):#0", "1 if current_page > 0: current_page-=1 else: again = 0 else: print \"Mail", "print \"Not a valid email.\" except: print \"Invalid input.\" def testing(): imap_expunge() #Done", "box is empty.\" def copy_mail(): imap_examine(currentFolder) recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) if", "#Delete def imap_delete(x): print 'A501 DELETE \"' + x + '\"\\r\\n' sslSocket.send('A501 DELETE", "for x in temp_list: if x.find('/\" \"') != -1 and x.find('\\Noselect') == -1", "' + amtRecent + ')')#Add the formated string to the list return mail_info_list", "li def email_is_read(mail_type, ch):#0 == norm #1 == UID recv = '' if", "name + \"!\" else: print \"Failed to delete.\" def search_mail_search(): search_mail(0) def search_mail_uid_search():", "'\"\\r\\n') recv = recv_all() return recv #UID Fetch def imap_uid_fetch(x): sslSocket.send('A999 UID FETCH", "empty.\" def copy_mail(): imap_examine(currentFolder) recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) >", "except: pass #just let it reloop if there was an error thrown #set", "in mailbox_list: if s.find(strg) != -1 and strg != s: return True return", "FROM TO)]\") recv_uid = imap_uid_fetch(str(ch) + \" (UID)\") print \"\\n===============================================================================\" pos = recv_uid.find('(UID')+5", "s in mailbox_list: if s.find(strg) != -1: imap_delete(s) def filter_list_of_subjects(l): li = []", "sslSocket.send('A101 List ' + \"\\\"\\\"\" +' '+ type + '\\r\\n') recv = recv_all()", "\"Old\", \"Drafts\", \"Text\", \"Date\"] print \"\\n------------------------------\" print \"Search by:\" inc = 0 while", "int(choice) if mail_type == 0: recv_body = imap_fetch(str(ch) + \" BODY[1]\") recv_header =", "0: print '\\n-------------------------------\\nEmails~ Page: ' + str(current_page+1) + '/' + str(max_pages) print_mail_list_with_subject(mail_nums, mailboxes_info,", "\"\\nMark as read = 1, Delete = 2, Leave as is = 3\"", "s.find(strg) != -1 and strg != s: return True return False def delete_all_children_with_child(strg,", "element is an empty string, so it isn't needed mail_list = []#Will hold", "max_pages-1: current_page+=1 elif choice == 'PREV' or choice == 'prev': again = 1", "recv = sslSocket.recv(1024) return recv #Delete def imap_delete(x): print 'A501 DELETE \"' +", "choice == \"1\": cmd = 'UNSEEN' #old elif choice == \"2\": cmd =", "data_str and time.time()-begin > timeout: break #If no data has been retrieved and", "') l = l[tmp:] while l.find('\\nSubject: ') != -1: pos1 = l.find('\\nSubject: ')+1", "' + choice_dest) else: print \"Not a valid email.\" except: print \"Invalid input.\"", "print \"---------------------------------\" #Print the email list in the format (box number or uid", "\") cmd = \"\" #all if choice == \"0\": cmd = 'ALL' #unread", "return recv #UID Fetch def imap_uid_fetch(x): sslSocket.send('A999 UID FETCH ' + x +", "unique id\" print \"5: Get mail from selected mail box\" print \"6: Get", "== 0: recv_body = imap_fetch(str(ch) + \" BODY[1]\") recv_header = imap_fetch(str(ch) + \"", "print \"Search by:\" inc = 0 while inc < len(options): print str(inc) +", "or PREV\" choice = raw_input(\"Which email do you want to open? \") if", "#old elif choice == \"2\": cmd = 'OLD' #drafts elif choice == \"3\":", "\"Mail Boxes:\" index = 0 while index < len(mailbox_list): print str(index) + \":\"", "> 0: try: ch = int(choice) if mail_type == 0: recv_body = imap_fetch(str(ch)", "pos2 = l.find('\\r') new = l[pos1:pos2] if new != '': li.append(new) l =", "(DATE SUBJECT FROM TO)]\") recv_uid = imap_fetch(str(ch) + \" (UID)\") else: recv_body =", "return recv #UID Store def imap_uid_store(x): print 'A003 UID STORE ' + x", "== \"0\": cmd = 'ALL' #unread elif choice == \"1\": cmd = 'UNSEEN'", "= date_opt + ' ' + date_ch if search_type == 0: recv =", "a mail box (AND) doesn't contain the /Noselect flag (And) isn't the all", "= name except: cmd = \"\" print \"Checking: \" + cmd if cmd", "= 0 while index < len(mailbox_list): print str(index) + \":\" + mailbox_list[index] +", "the returned string by the new line indicators del temp_list[len(temp_list)-1]#The last element is", "line indicators del temp_list[len(temp_list)-1]#The last element is an empty string, so it isn't", "boxes def has_children(strg, mailbox_list): for s in mailbox_list: if s.find(strg) != -1 and", "def get_mail_boxnum(): get_mail(0) def get_mail_uid(): get_mail(1) def get_mail(mail_type):#0 == search #1 == UID", "#false = unread true = read print email_read if email_read: print \"\\nMark as", "would you like to do? (0 to quit.)\" print \"1: View all mail", "socket print \"Done.\" #Main Method def main(): log_success = imap_login() if log_success ==", "the mail box has child boxes def has_children(strg, mailbox_list): for s in mailbox_list:", "len(subs) while start <= len(nums) and start <= end:#Print the specified elements of", "if (len(mail_nums)%email_list_length) > 0: max_pages += 1 current_page = 0 again = 1", "-1: pos1 = l.find('\\nSubject: ')+1 pos2 = l.find('\\r') new = l[pos1:pos2] if new", "imap_login() if log_success == -1: close_mail() return 0 choice = \"\" #The main", "mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) choice =", "text of the email body def format_email_body(recv): first = 0 last = len(recv)-1", "def create_dir(): name = raw_input(\"\\nName of new mailbox to create:\") recv = imap_create(name)", "timeout, then stop if data_str and time.time()-begin > timeout: break #If no data", "mailbox names #The parameter is the string returned from the imap_list command def", "mail box selected.\" else: get_mail_boxnum() elif choice == \"6\": if currentFolder == \"None\":", "to create.\" def delete_dir(): mailbox_string = imap_list(\"/\", \"*\") mail_list = get_mailbox_list_array(mailbox_string) print_mailboxes_list(mail_list) choice", "print recv return recv #UID Search def imap_uid_search(x): sslSocket.send('A999 UID SEARCH ' +", "sslSocket.recv(1024) print recv return recv #UID Copy def imap_uid_copy(x): sslSocket.send('A300 COPY \"' +", "if choice == \"1\": #mark as read recv = imap_uid_store(msg_uid + ' +FLAGS", "choice != \"0\": print \"\\n\" print \"---------------------------------------------\" print \"-- Currently Selected Mailbox: \"", "catch errors with getting data from the server try: data = sslSocket.recv(1024) if", "\"Unread\", \"Old\", \"Drafts\", \"Text\", \"Date\"] print \"\\n------------------------------\" print \"Search by:\" inc = 0", "#try and get the data using a try/except to catch errors with getting", "running def close_mail(): sslSocket.close() #close the socket print \"Done.\" #Main Method def main():", "return True return False def delete_all_children_with_child(strg, mailbox_list): for s in mailbox_list: if s.find(strg)", "command def get_mail_numbers_from_search(recv): pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2] tmp", "'+ type + '\\r\\n') recv = recv_all() return recv #Search def imap_search(x): sslSocket.send('A201", "0: subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") else: subject_list = imap_uid_fetch(string_list +", "name = raw_input(\"\\nName of new mailbox to create:\") recv = imap_create(name) if recv.find(\"OK", "a list def print_mailboxes_list(mailbox_list): print \"\" print \"---------------------------------\" print \"Mail Boxes:\" index =", "EXPUNGE\\r\\n') recv = sslSocket.recv(1024) print recv #Select def imap_select(x): sslSocket.send('A142 SELECT \"' +", "additional information def print_mailboxes_list_with_info(mailbox_list, info): print \"\" print \"---------------------------------\" print \"Mail Boxes:\" index", "amtExist + ' Recent: ' + amtRecent + ')')#Add the formated string to", "recv = sslSocket.recv(1024) print recv return recv #UID Copy def imap_uid_copy(x): sslSocket.send('A300 COPY", "recv #Create def imap_create(x): sslSocket.send('A401 CREATE \"' + x + '\"\\r\\n') recv =", "if x.find('/\" \"') != -1 and x.find('\\Noselect') == -1 and x.find('[Gmail]/All Mail') ==", "#Loop from the end til it find the A if recv[index] == 'A':", "choice_dest) else: print \"Not a valid email.\" except: print \"Invalid input.\" def testing():", "many emails each mailbox contains def get_mailboxes_info_array(mail_list): mail_info_list = [] #Holds the list", "choice == \"6\": if currentFolder == \"None\": print \"\\nNo mail box selected.\" else:", "it to the end of the list end = len(subs) while start <=", "'\"\\r\\n') recv = sslSocket.recv(1024) print recv return recv #UID Copy def imap_uid_copy(x): sslSocket.send('A300", "sslSocket.connect(mailserver) recv = sslSocket.recv(1024) if recv.find('OK Gimap ready for requests from') != -1:", "BODY[1]\") recv_header = imap_uid_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid =", "'\"\\r\\n' sslSocket.send('A501 DELETE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) print recv", "5 break return recv[first:last] #Return true if the mail box has child boxes", "data_str += data begin=time.time()#reset the begin time so that it doesn't timeout while", "and int(choice) > 0: print imap_uid_copy(choice + ' ' + choice_dest) else: print", "recv[pos1:pos2] tmp = r.split(' ') temp_list = [] for t in tmp: try:", "for s in mailbox_list: if s.find(strg) != -1: imap_delete(s) def filter_list_of_subjects(l): li =", "you want to copy: ') choice_dest = raw_input('To which folder: ') try: if", "a string of the numbers returned from the search command def get_mail_numbers_from_search(recv): pos1", "print str(index) + \":\" + mailbox_list[index] index = index + 1 print \"---------------------------------\"", "message unique id\" print \"5: Get mail from selected mail box\" print \"6:", "if decision == \"1\": delete_all_children_with_child(name, mail_list) cmd = \"all\" else: cmd = \"\"", "numbers returned from the search command def get_mail_numbers_from_search(recv): pos1 = recv.find('SEARCH')+7 pos2 =", "== \"6\": if currentFolder == \"None\": print \"\\nNo mail box selected.\" else: get_mail_uid()", "index = 0 while index < len(mailbox_list): print str(index) + \":\" + mailbox_list[index]", "is designed for non=blocking sslSocket.setblocking(1) return data_str #Returns a list containing the mailbox", "\" (UID)\") else: recv_body = imap_uid_fetch(str(ch) + \" BODY[1]\") recv_header = imap_uid_fetch(str(ch) +", "print \"\\nNo Box chosen\" if cmd == \"all\": print \"Deleted\" else: imap_delete(cmd) if", "some data was receive and it passed the timeout, then stop if data_str", "number for the box to delete: \") try: ch_num = int(choice) if ch_num", "= \"ON\" if when_ch == \"1\": date_opt = \"BEFORE\" elif when_ch == \"2\":", "= ssl.PROTOCOL_SSLv23) sslSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sslSocket.connect(mailserver) recv = sslSocket.recv(1024) if recv.find('OK Gimap", "== \"9\": copy_mail() elif choice == \"10\": testing() if choice == \"0\": close_mail()", "+ amtExist + ' Recent: ' + amtRecent + ')')#Add the formated string", "= \"\" else: cmd = name except: cmd = \"\" print \"Checking: \"", "when_ch = raw_input(\"(Before date = 1)(On date = 2)(Since date = 3):\") date_ch", "if r != '': return True else: return False ################################# #Mail Client Methods", "\"')+4 mail_list.append(x[pos:-1]) #Store the substring of the line containing the mailbox name return", "id\" print \"7: Create a mail box\" print \"8: Delete a mail box\"", "' + \"\\\"\\\"\" +' '+ type + '\\r\\n') recv = recv_all() return recv", "+ ' SEEN') else: recv = imap_uid_search(str(ch) + ' SEEN') pos1 = recv.find('SEARCH')+7", "view_mailboxes(): mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) def", "name + \" and all children.(1=yes, 2=no)\") if decision == \"1\": delete_all_children_with_child(name, mail_list)", "recv return recv #UID Search def imap_uid_search(x): sslSocket.send('A999 UID SEARCH ' + x", "= imap_uid_search(cmd) mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0: string_list = '' for", "EXAMINE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) return recv #Fetch def", "Success\\r\\n')-11 print recv_header[pos:pos2] print \"--------------------------------------------------------------------\" print format_email_body(recv_body) print \"===============================================================================\\n\" email_read = email_is_read(mail_type, ch)#0", "1 while again == 1: again = 1 start = current_page * email_list_length", "else: cmd = \"\" else: cmd = name except: cmd = \"\" print", "l[pos2+1:] return li def email_is_read(mail_type, ch):#0 == norm #1 == UID recv =", "< len(mailbox_list): print str(index) + \":\" + mailbox_list[index] + \" \" + info[index]", "'/' + str(max_pages) print_mail_list_with_subject(mail_nums, mailboxes_info, start, end) print \"\\nTo view more mail type,", "= l[tmp:] while l.find('\\nSubject: ') != -1: pos1 = l.find('\\nSubject: ')+1 pos2 =", "do you want to open: \") try: if int(choice) < len(mail_list): currentFolder =", "unread recv = imap_uid_store(msg_uid + ' -FLAGS (\\seen)') elif choice == \"2\": #delete", "recv ################################# #Extra Methods ################################# #Receive using a timeout def recv_all(timeout = 2):#can", "' + x + '\\r\\n' sslSocket.send('A003 UID STORE ' + x + '\\r\\n')", "== \"3\": if currentFolder == \"None\": print \"\\nNo mail box selected.\" else: search_mail_search()", "pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2] if r != '':", "currentFolder == \"None\": print \"\\nNo mail box selected.\" else: get_mail_uid() elif choice ==", "username + ' ' + password + '\\r\\n') recv = sslSocket.recv(1024) if recv.find(\"completed\")", "print \"2: Examine a mail box\" print \"3: Search selected mail box\" print", "elif choice == \"2\": #delete recv = imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print", "= sslSocket.recv(1024) print recv return recv #UID Copy def imap_uid_copy(x): sslSocket.send('A300 COPY \"'", "= imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print recv imap_expunge() else: print \"\\nMark as", "> 0: print '\\n-------------------------------\\nEmails:' string_list = '' for x in range(len(mail_nums)): string_list +=", "passed while True: #If some data was receive and it passed the timeout,", "if recv.find('}') != -1:#Find the first } first = recv.find('}') + 3 for", "> 0: max_pages += 1 current_page = 0 again = 1 while again", "end) print \"\\nTo view more mail type, NEXT or PREV\" choice = raw_input(\"Which", "tmp[17] amtRecent = tmp[19] except: pass mail_info_list.append('(Emails: ' + amtExist + ' Recent:", "recv_all() return recv #UID Store def imap_uid_store(x): print 'A003 UID STORE ' +", "so it isn't needed mail_list = []#Will hold the list of mailbox names", "+ str(subs[start-1]) start += 1 #Get how many emails each mailbox contains def", "the number for the box to delete: \") try: ch_num = int(choice) if", "the subjects of the emails if end == -1:#If the point to stop", "\"Not a valid email.\" except: print \"Invalid input.\" def testing(): imap_expunge() #Done running", "+ email_list_length - 1 if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails~ Page: ' +", "elif choice == \"2\": examine_mailbox() elif choice == \"3\": if currentFolder == \"None\":", "str(max_pages) print_mail_list_with_subject(mail_nums, mailboxes_info, start, end) print \"\\nTo view more mail type, NEXT or", "+ '/' + str(max_pages) print_mail_list_with_subject(mail_nums, mailboxes_info, start, end) print \"\\nTo view more mail", "li.append(new) l = l[pos2+1:] return li def email_is_read(mail_type, ch):#0 == norm #1 ==", "\"Successfully logged in to: \" + username + \"\\n\" return 1 else: print", "Get mail from selected mail box\" print \"6: Get mail from selected mail", "print \"Failed to delete.\" def search_mail_search(): search_mail(0) def search_mail_uid_search(): search_mail(1) def search_mail(search_type):#0 ==", "the specified elements of the lists print str(nums[start-1]) + \": \" + str(subs[start-1])", "1 print \"------------------------------\" choice = raw_input(\"Choice: \") cmd = \"\" #all if choice", "',' if string_list: string_list = string_list[:-1] if search_type == 0: subject_list = imap_fetch(string_list", "from selected mail box\" print \"6: Get mail from selected mail box using", "+ \" BODY[HEADER.FIELDS (SUBJECT)]\") else: subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info", "'' if mail_type == 0: recv = imap_search(str(ch) + ' SEEN') else: recv", "print \"--------------------------------------------------------------------\" print format_email_body(recv_body) print \"===============================================================================\\n\" email_read = email_is_read(mail_type, ch)#0 == norm #1", "string_list = string_list[:-1] if search_type == 0: subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS", "if currentFolder == \"None\": print \"\\nNo mail box selected.\" else: get_mail_boxnum() elif choice", "returned string by the new line indicators del temp_list[len(temp_list)-1]#The last element is an", "list of mailbox names to be returned for x in temp_list: if x.find('/\"", "data: #if there is some data that was received then store that data", "+ \":\" + mailbox_list[index] index = index + 1 print \"---------------------------------\" #Print the", "of the data received data_str = '' #time this method started begin =", "-1:#Find the first } first = recv.find('}') + 3 for index in reversed(range(len(recv))):", "l = l[tmp:] while l.find('\\nSubject: ') != -1: pos1 = l.find('\\nSubject: ')+1 pos2", "sslSocket.recv(1024) print recv #Select def imap_select(x): sslSocket.send('A142 SELECT \"' + x + '\"\\r\\n')", "print \"9: Copy email from selected mail box to another\" choice = raw_input(\"Choice:", "create_dir(): name = raw_input(\"\\nName of new mailbox to create:\") recv = imap_create(name) if", "'\"\\r\\n') recv = sslSocket.recv(1024) return recv #Delete def imap_delete(x): print 'A501 DELETE \"'", "imap_expunge(): sslSocket.send('A202 EXPUNGE\\r\\n') recv = sslSocket.recv(1024) print recv #Select def imap_select(x): sslSocket.send('A142 SELECT", "+ msg_uid pos = recv_header.find(\"Date: \") pos2 = recv_header.find('OK Success\\r\\n')-11 print recv_header[pos:pos2] print", "= tmp[17] amtRecent = tmp[19] except: pass mail_info_list.append('(Emails: ' + amtExist + '", "mailboxes_info = filter_list_of_subjects(subject_list) max_pages = int(len(mail_nums)/email_list_length) if (len(mail_nums)%email_list_length) > 0: max_pages += 1", "imap_select(currentFolder) email_list_length = 10 if mail_type == 0: recv = imap_search('ALL') else: recv", "it isn't needed mail_list = []#Will hold the list of mailbox names to", "= current_page * email_list_length + 1 end = start + email_list_length - 1", "= imap_fetch(str(ch) + \" (UID)\") else: recv_body = imap_uid_fetch(str(ch) + \" BODY[1]\") recv_header", "raw_input('To which folder: ') try: if len(mail_nums)+2 > int(choice) and int(choice) > 0:", "all children.(1=yes, 2=no)\") if decision == \"1\": delete_all_children_with_child(name, mail_list) cmd = \"all\" else:", "cmd = 'ALL' #unread elif choice == \"1\": cmd = 'UNSEEN' #old elif", "= 1 if current_page > 0: current_page-=1 else: again = 0 else: print", "= recv_all() return recv #Expunge def imap_expunge(): sslSocket.send('A202 EXPUNGE\\r\\n') recv = sslSocket.recv(1024) print", "first = 0 last = len(recv)-1 if recv.find('}') != -1:#Find the first }", "print \"Failed to create.\" def delete_dir(): mailbox_string = imap_list(\"/\", \"*\") mail_list = get_mailbox_list_array(mailbox_string)", "= \"\" #The main loop while choice != \"0\": print \"\\n\" print \"---------------------------------------------\"", "= imap_uid_fetch(str(ch) + \" (UID)\") print \"\\n===============================================================================\" pos = recv_uid.find('(UID')+5 pos2 = recv_uid.find(')')", "################################# #Done connecting ################################# ################################# #Global Variables ################################# currentFolder = \"None\" #Stores the", "\"1\": cmd = 'UNSEEN' #old elif choice == \"2\": cmd = 'OLD' #drafts", "= the subjects of the emails if end == -1:#If the point to", "Box chosen\" if cmd == \"all\": print \"Deleted\" else: imap_delete(cmd) if recv.find(\"OK Success\")", "current_page+=1 elif choice == 'PREV' or choice == 'prev': again = 1 if", "mail_list #Print the mailbox names in a list def print_mailboxes_list(mailbox_list): print \"\" print", "sslSocket.send('A202 EXPUNGE\\r\\n') recv = sslSocket.recv(1024) print recv #Select def imap_select(x): sslSocket.send('A142 SELECT \"'", "cmd == \"\": print \"\\nNo Box chosen\" if cmd == \"all\": print \"Deleted\"", "list in the format (box number or uid number): Subject: This is the", "ch):#0 == norm #1 == UID recv = '' if mail_type == 0:", "!= -1: print \"Connected.\\n\" else: print \"Problem connecting.\\n\" ################################# #Done connecting ################################# #################################", "optional parameters to change what is listed sslSocket.send('A101 List ' + \"\\\"\\\"\" +'", "mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) choice = raw_input(\"Which mail box do you want", "box\" print \"9: Copy email from selected mail box to another\" choice =", "recv = imap_search(cmd) else: recv = imap_uid_search(cmd) mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) >", "point to stop printing in the list wasn't specified in the params, set", "(0 to quit.)\" print \"1: View all mail boxes\" print \"2: Examine a", "!= -1: imap_delete(s) def filter_list_of_subjects(l): li = [] if l.find('\\nSubject: ') != -1:", "break #If no data has been retrieved and it has passed the timeout", "unread true = read print email_read if email_read: print \"\\nMark as unread =", "mailbox_list[index] index = index + 1 print \"---------------------------------\" #Print the mailbox names in", "def imap_select(x): sslSocket.send('A142 SELECT \"' + x + '\"\\r\\n') recv = recv_all() return", "print \"4: Search using message unique id\" print \"5: Get mail from selected", "search imap_select(currentFolder) email_list_length = 10 if mail_type == 0: recv = imap_search('ALL') else:", "get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) def examine_mailbox(): global currentFolder mailbox_string = imap_list()", "close_mail(): sslSocket.close() #close the socket print \"Done.\" #Main Method def main(): log_success =", "return False def delete_all_children_with_child(strg, mailbox_list): for s in mailbox_list: if s.find(strg) != -1:", "def filter_list_of_subjects(l): li = [] if l.find('\\nSubject: ') != -1: tmp = l.find('\\nSubject:", "' + amtExist + ' Recent: ' + amtRecent + ')')#Add the formated", "== norm #1 == UID recv = '' if mail_type == 0: recv", "imap_expunge() else: print \"\\nMark as read = 1, Delete = 2, Leave as", "pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2] tmp = r.split(' ')", "raw_input(\"Choice: \") if choice == \"1\": view_mailboxes() elif choice == \"2\": examine_mailbox() elif", "print \"\\nMark as read = 1, Delete = 2, Leave as is =", "delete_dir(): mailbox_string = imap_list(\"/\", \"*\") mail_list = get_mailbox_list_array(mailbox_string) print_mailboxes_list(mail_list) choice = raw_input(\"Enter the", "try: if len(mail_nums)+2 > int(choice) and int(choice) > 0: print imap_uid_copy(choice + '", "= mail_list[int(choice)] print \"\\nSelected \" + currentFolder else: print \"\\nNot a valid mail", "-1: print \"Created \" + name + \"!\" else: print \"Failed to create.\"", "search_type == 0: recv = imap_search(cmd) else: recv = imap_uid_search(cmd) mail_nums = get_mail_numbers_from_search(recv)", "temp_list[len(temp_list)-1]#The last element is an empty string, so it isn't needed mail_list =", "choice == \"5\": when_ch = raw_input(\"(Before date = 1)(On date = 2)(Since date", "new line indicators del temp_list[len(temp_list)-1]#The last element is an empty string, so it", "in tmp: try: temp_list.append(int(t)) except: pass return temp_list #Return the text of the", "search_mail_uid_search(): search_mail(1) def search_mail(search_type):#0 == search #1 == UID search imap_examine(currentFolder) options =", "SEARCH ' + x + '\\r\\n') recv = recv_all() return recv #Examine def", "pass mail_info_list.append('(Emails: ' + amtExist + ' Recent: ' + amtRecent + ')')#Add", "-1: tmp = l.find('\\nSubject: ') l = l[tmp:] while l.find('\\nSubject: ') != -1:", "mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0: string_list = '' for x in", "if recv.find(\"OK Success\") != -1: print \"Created \" + name + \"!\" else:", "+ x + '\"\\r\\n') recv = sslSocket.recv(1024) return recv #Fetch def imap_fetch(x): sslSocket.send('A301", "#1 == UID recv = '' if mail_type == 0: recv = imap_search(str(ch)", "try: amtExist = tmp[17] amtRecent = tmp[19] except: pass mail_info_list.append('(Emails: ' + amtExist", "while again == 1: again = 1 start = current_page * email_list_length +", "= l[pos1:pos2] if new != '': li.append(new) l = l[pos2+1:] return li def", "= len(subs) while start <= len(nums) and start <= end:#Print the specified elements", "email do you want to open? \") if choice == 'NEXT' or choice", "if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails~ Page: ' + str(current_page+1) + '/' +", "string_list: string_list = string_list[:-1] if search_type == 0: subject_list = imap_fetch(string_list + \"", "recv = imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print recv imap_expunge() else: print \"\\nMark", "elif choice == \"4\": if currentFolder == \"None\": print \"\\nNo mail box selected.\"", "a list with additional information def print_mailboxes_list_with_info(mailbox_list, info): print \"\" print \"---------------------------------\" print", "SELECT \"' + x + '\"\\r\\n') recv = recv_all() return recv ################################# #Extra", "password + '\\r\\n') recv = sslSocket.recv(1024) if recv.find(\"completed\") != -1: print \"Successfully logged", "\") if choice == 'NEXT' or choice == 'next': again = 1 if", "was receive and it passed the timeout, then stop if data_str and time.time()-begin", "else: print \"\\nNot a valid mail box.\" except: print \"\\nNot a valid mail", "recv_all(timeout = 2):#can either pass a different timeout or use the default set", "read recv = imap_uid_store(msg_uid + ' +FLAGS (\\seen)') elif choice == \"2\": #delete", "\"\" else: cmd = name except: cmd = \"\" print \"Checking: \" +", "= imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print", "choice == \"8\": delete_dir() elif choice == \"9\": copy_mail() elif choice == \"10\":", "choice == \"1\": view_mailboxes() elif choice == \"2\": examine_mailbox() elif choice == \"3\":", "selected.\" else: get_mail_uid() elif choice == \"7\": create_dir() elif choice == \"8\": delete_dir()", "x in mail_list: recv = imap_examine(x) tmp = recv.split(\" \") amtExist = 'N/A'", "temp_list: if x.find('/\" \"') != -1 and x.find('\\Noselect') == -1 and x.find('[Gmail]/All Mail')", "the list end = len(subs) while start <= len(nums) and start <= end:#Print", "recv_uid.find(')') msg_uid = recv_uid[pos:pos2] print \"Email UID: \" + msg_uid pos = recv_header.find(\"Date:", "cmd = \"all\" else: cmd = \"\" else: cmd = name except: cmd", "',' if string_list: string_list = string_list[:-1] subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\")", "a valid email.\" except: print \"Invalid input.\" def testing(): imap_expunge() #Done running def", "= [] for t in tmp: try: temp_list.append(int(t)) except: pass return temp_list #Return", "l[pos1:pos2] if new != '': li.append(new) l = l[pos2+1:] return li def email_is_read(mail_type,", "mail box selected.\" else: search_mail_search() elif choice == \"4\": if currentFolder == \"None\":", "+ \" BODY[1]\") recv_header = imap_uid_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\")", "try: if int(choice) < len(mail_list): currentFolder = mail_list[int(choice)] print \"\\nSelected \" + currentFolder", "loop while choice != \"0\": print \"\\n\" print \"---------------------------------------------\" print \"-- Currently Selected", "\"6\": if currentFolder == \"None\": print \"\\nNo mail box selected.\" else: get_mail_uid() elif", "= recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2] if r != '': return", "= get_mail_numbers_from_search(recv) string_list = '' for x in range(len(mail_nums)): string_list += str(mail_nums[x]) +", "print \"\\n\" print \"---------------------------------------------\" print \"-- Currently Selected Mailbox: \" + currentFolder print", "\"7\": create_dir() elif choice == \"8\": delete_dir() elif choice == \"9\": copy_mail() elif", "print(\"Login information:\") username = \"<EMAIL>\" password = \"password\" print(\"Attempting to login.\\n\") sslSocket.send('A001 LOGIN", "0 again = 1 while again == 1: again = 1 start =", "data else: time.sleep(0.1)#give a slight pause before trying to read again except: pass", "#drafts elif choice == \"3\": cmd = 'DRAFT' #text elif choice == \"4\":", "0 while index < len(mailbox_list): print str(index) + \":\" + mailbox_list[index] + \"", "recv = recv_all() return recv #Create def imap_create(x): sslSocket.send('A401 CREATE \"' + x", "string to the list return mail_info_list #Return a string of the numbers returned", "which folder: ') try: if len(mail_nums)+2 > int(choice) and int(choice) > 0: print", "cmd = name except: cmd = \"\" print \"Checking: \" + cmd if", "boxes\" print \"2: Examine a mail box\" print \"3: Search selected mail box\"", "a mail box\" print \"8: Delete a mail box\" print \"9: Copy email", "cmd = 'OLD' #drafts elif choice == \"3\": cmd = 'DRAFT' #text elif", "last element is an empty string, so it isn't needed mail_list = []#Will", "+ x + '\"\\r\\n') recv = sslSocket.recv(1024) print recv return recv #UID Copy", "+ '\\r\\n') recv = sslSocket.recv(1024) if recv.find(\"completed\") != -1: print \"Successfully logged in", "imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) def examine_mailbox(): global currentFolder", "\"Email UID: \" + msg_uid pos = recv_header.find(\"Date: \") pos2 = recv_header.find('OK Success\\r\\n')-11", "last = len(recv)-1 if recv.find('}') != -1:#Find the first } first = recv.find('}')", "str(current_page+1) + '/' + str(max_pages) print_mail_list_with_subject(mail_nums, mailboxes_info, start, end) print \"\\nTo view more", "\"\\nNot a valid mail box.\" def get_mail_boxnum(): get_mail(0) def get_mail_uid(): get_mail(1) def get_mail(mail_type):#0", "mail_type == 0: recv_body = imap_fetch(str(ch) + \" BODY[1]\") recv_header = imap_fetch(str(ch) +", "filter_list_of_subjects(l): li = [] if l.find('\\nSubject: ') != -1: tmp = l.find('\\nSubject: ')", "data from the server try: data = sslSocket.recv(1024) if data: #if there is", "printing in the list wasn't specified in the params, set it to the", "if int(choice) < len(mail_list): currentFolder = mail_list[int(choice)] print \"\\nSelected \" + currentFolder else:", "+ 1 print \"------------------------------\" choice = raw_input(\"Choice: \") cmd = \"\" #all if", "!= s: return True return False def delete_all_children_with_child(strg, mailbox_list): for s in mailbox_list:", "\"6: Get mail from selected mail box using unique id\" print \"7: Create", "in mail_list: recv = imap_examine(x) tmp = recv.split(\" \") amtExist = 'N/A' amtRecent", "\"Text\", \"Date\"] print \"\\n------------------------------\" print \"Search by:\" inc = 0 while inc <", "= imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) max_pages = int(len(mail_nums)/email_list_length) if", "the substring of the line containing the mailbox name return mail_list #Print the", "recv = sslSocket.recv(1024) if recv.find(\"completed\") != -1: print \"Successfully logged in to: \"", "def format_email_body(recv): first = 0 last = len(recv)-1 if recv.find('}') != -1:#Find the", "#The main loop while choice != \"0\": print \"\\n\" print \"---------------------------------------------\" print \"--", "all mail folder pos = x.find('/\" \"')+4 mail_list.append(x[pos:-1]) #Store the substring of the", "str(inc) + \":\" + options[inc] inc = inc + 1 print \"------------------------------\" choice", "mail from selected mail box\" print \"6: Get mail from selected mail box", "recv.find(\"OK Success\") != -1: print \"Created \" + name + \"!\" else: print", "Currently Selected Mailbox: \" + currentFolder print \"---------------------------------------------\" print \"What would you like", "= imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print recv imap_expunge() except: print \"Email not", "recv = imap_search(str(ch) + ' SEEN') else: recv = imap_uid_search(str(ch) + ' SEEN')", "x + '\\r\\n') recv = recv_all() return recv #Create def imap_create(x): sslSocket.send('A401 CREATE", "string_list = string_list[:-1] subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list)", "print \"1: View all mail boxes\" print \"2: Examine a mail box\" print", "> timeout: break #If no data has been retrieved and it has passed", "using a timeout def recv_all(timeout = 2):#can either pass a different timeout or", "#The parameter is the string returned from the imap_list command def get_mailbox_list_array(mailbox_string): temp_list", "subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") else: subject_list = imap_uid_fetch(string_list + \"", "cmd if cmd == \"\": print \"\\nNo Box chosen\" if cmd == \"all\":", "return mail_list #Print the mailbox names in a list def print_mailboxes_list(mailbox_list): print \"\"", "end = -1):#nums = the numbers of the emails, subs = the subjects", "contains def get_mailboxes_info_array(mail_list): mail_info_list = [] #Holds the list of info for the", "= raw_input(\"\\nName of new mailbox to create:\") recv = imap_create(name) if recv.find(\"OK Success\")", "= 0 again = 1 while again == 1: again = 1 start", "= get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) choice = raw_input(\"Which mail box do you want to", "[] #Holds the list of info for the emails for x in mail_list:", "False def delete_all_children_with_child(strg, mailbox_list): for s in mailbox_list: if s.find(strg) != -1: imap_delete(s)", "def view_mailboxes(): mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info)", "-1: print \"Deleted \" + name + \"!\" else: print \"Failed to delete.\"", "\"None\" #Stores the currently selected mail box ################################# #imap Methods ################################# def imap_login():#login", "search #1 == UID search imap_examine(currentFolder) options = [\"All\", \"Unread\", \"Old\", \"Drafts\", \"Text\",", "the lists print str(nums[start-1]) + \": \" + str(subs[start-1]) start += 1 #Get", "global currentFolder mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info)", "to quit.)\" print \"1: View all mail boxes\" print \"2: Examine a mail", "x + '\\r\\n') recv = sslSocket.recv(1024) print recv return recv #UID Search def", "x + '\"\\r\\n') recv = sslSocket.recv(1024) print recv return recv #UID Copy def", "len(mailbox_list): print str(index) + \":\" + mailbox_list[index] + \" \" + info[index] index", "mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) def examine_mailbox():", "= recv.find('\\r') r = recv[pos1:pos2] tmp = r.split(' ') temp_list = [] for", "an empty string, so it isn't needed mail_list = []#Will hold the list", "email subject def print_mail_list_with_subject(nums, subs, start = 1, end = -1):#nums = the", "recv = imap_create(name) if recv.find(\"OK Success\") != -1: print \"Created \" + name", "if has_children(name, mail_list): decision = raw_input(\"Are you sure you want to delete \"", "amtRecent + ')')#Add the formated string to the list return mail_info_list #Return a", "\"2\": #delete recv = imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print recv imap_expunge() except:", "print \"---------------------------------------------\" print \"-- Currently Selected Mailbox: \" + currentFolder print \"---------------------------------------------\" print", "print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box is empty.\" choice = raw_input('\\nWhich email do", "valid email.\" except: print \"Invalid input.\" def testing(): imap_expunge() #Done running def close_mail():", "return mail_info_list #Return a string of the numbers returned from the search command", "int(len(mail_nums)/email_list_length) if (len(mail_nums)%email_list_length) > 0: max_pages += 1 current_page = 0 again =", "= get_mail_numbers_from_search(recv) if len(mail_nums) > 0: string_list = '' for x in range(len(mail_nums)):", "valid mail box.\" def get_mail_boxnum(): get_mail(0) def get_mail_uid(): get_mail(1) def get_mail(mail_type):#0 == search", "imap_search('ALL') else: recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) string_list = '' for x", "or use the default set in the parameter global sslSocket #set the socket", "store that data data_str += data begin=time.time()#reset the begin time so that it", "\" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid = imap_fetch(str(ch) + \" (UID)\") else:", "-1:#The line has a mail box (AND) doesn't contain the /Noselect flag (And)", "unread = 1, Delete = 2, Leave as is = 3\" choice =", "start #sslSocket = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), #ssl_version = ssl.PROTOCOL_SSLv23) sslSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sslSocket.connect(mailserver)", "end:#Print the specified elements of the lists print str(nums[start-1]) + \": \" +", "choice = raw_input(\"Choice: \") cmd = \"\" #all if choice == \"0\": cmd", "timeout def recv_all(timeout = 2):#can either pass a different timeout or use the", "til it find the A if recv[index] == 'A': last = index -", "box using unique id\" print \"7: Create a mail box\" print \"8: Delete", "base64, sys, time, math print \"Connecting..\" username = \"\" password = \"\" #", "1, Delete = 2, Leave as is = 3\" choice = raw_input(\"Choice: \")", "SEEN') else: recv = imap_uid_search(str(ch) + ' SEEN') pos1 = recv.find('SEARCH')+7 pos2 =", "number): Subject: This is the email subject def print_mail_list_with_subject(nums, subs, start = 1,", "imap_uid_copy(x): sslSocket.send('A300 COPY \"' + x + '\"\\r\\n') recv = recv_all() return recv", "recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails:' string_list", "print \"------------------------------\" choice = raw_input(\"Choice: \") cmd = \"\" #all if choice ==", "'next': again = 1 if current_page < max_pages-1: current_page+=1 elif choice == 'PREV'", "'\\r\\n') recv = recv_all() return recv #UID Store def imap_uid_store(x): print 'A003 UID", "== \"None\": print \"\\nNo mail box selected.\" else: get_mail_uid() elif choice == \"7\":", "== -1:#The line has a mail box (AND) doesn't contain the /Noselect flag", "= [] if l.find('\\nSubject: ') != -1: tmp = l.find('\\nSubject: ') l =", "if when_ch == \"1\": date_opt = \"BEFORE\" elif when_ch == \"2\": date_opt =", "ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), #ssl_version = ssl.PROTOCOL_SSLv23) sslSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sslSocket.connect(mailserver) recv = sslSocket.recv(1024)", "Page: ' + str(current_page+1) + '/' + str(max_pages) print_mail_list_with_subject(mail_nums, mailboxes_info, start, end) print", "print format_email_body(recv_body) print \"===============================================================================\\n\" email_read = email_is_read(mail_type, ch)#0 == norm #1 == UID", "no data has been retrieved and it has passed the timeout by 2,", "time.sleep(0.1)#give a slight pause before trying to read again except: pass #just let", "of new mailbox to create:\") recv = imap_create(name) if recv.find(\"OK Success\") != -1:", "imap_search(x): sslSocket.send('A201 SEARCH ' + x + '\\r\\n') recv = recv_all() return recv", "= 2):#can either pass a different timeout or use the default set in", "choice == 'NEXT' or choice == 'next': again = 1 if current_page <", "to: \" + username + \"\\n\" return 1 else: print \"Login failed!\\n\" return", "inc = inc + 1 print \"------------------------------\" choice = raw_input(\"Choice: \") cmd =", "start <= len(nums) and start <= end:#Print the specified elements of the lists", "specified elements of the lists print str(nums[start-1]) + \": \" + str(subs[start-1]) start", "a list containing the mailbox names #The parameter is the string returned from", "= recv_all() return recv #Create def imap_create(x): sslSocket.send('A401 CREATE \"' + x +", "') try: if len(mail_nums)+2 > int(choice) and int(choice) > 0: print imap_uid_copy(choice +", "read = 1, Delete = 2, Leave as is = 3\" choice =", "1 current_page = 0 again = 1 while again == 1: again =", "BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box is empty.\"", "else: imap_delete(cmd) if recv.find(\"OK Success\") != -1: print \"Deleted \" + name +", "return recv #UID Copy def imap_uid_copy(x): sslSocket.send('A300 COPY \"' + x + '\"\\r\\n')", "that it doesn't timeout while still getting data else: time.sleep(0.1)#give a slight pause", "filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box is empty.\" choice = raw_input('\\nWhich email", "+= 1 current_page = 0 again = 1 while again == 1: again", "again = 0 if len(mail_nums) > 0: try: ch = int(choice) if mail_type", "' ' + date_ch if search_type == 0: recv = imap_search(cmd) else: recv", "print email_read if email_read: print \"\\nMark as unread = 1, Delete = 2,", "def recv_all(timeout = 2):#can either pass a different timeout or use the default", "x + '\"\\r\\n') recv = recv_all() return recv #UID Fetch def imap_uid_fetch(x): sslSocket.send('A999", "== \"3\": date_opt = \"SINCE\" cmd = date_opt + ' ' + date_ch", "recv_uid[pos:pos2] print \"Email UID: \" + msg_uid pos = recv_header.find(\"Date: \") pos2 =", "mail box\" print \"6: Get mail from selected mail box using unique id\"", "== -1: close_mail() return 0 choice = \"\" #The main loop while choice", "get_mail(mail_type):#0 == search #1 == UID search imap_select(currentFolder) email_list_length = 10 if mail_type", "elif choice == \"5\": if currentFolder == \"None\": print \"\\nNo mail box selected.\"", "UID: \" + msg_uid pos = recv_header.find(\"Date: \") pos2 = recv_header.find('OK Success\\r\\n')-11 print", "def main(): log_success = imap_login() if log_success == -1: close_mail() return 0 choice", "+FLAGS (\\deleted)') print recv imap_expunge() else: print \"\\nMark as read = 1, Delete", "from selected mail box to another\" choice = raw_input(\"Choice: \") if choice ==", "Method def main(): log_success = imap_login() if log_success == -1: close_mail() return 0", "= 'OLD' #drafts elif choice == \"3\": cmd = 'DRAFT' #text elif choice", "return recv #Delete def imap_delete(x): print 'A501 DELETE \"' + x + '\"\\r\\n'", "0: string_list = '' for x in range(len(mail_nums)): string_list += str(mail_nums[x]) + ','", "the parameter global sslSocket #set the socket to non-blocking sslSocket.setblocking(0) #array of the", "amtExist = tmp[17] amtRecent = tmp[19] except: pass mail_info_list.append('(Emails: ' + amtExist +", "print \"Mail box is empty.\" again = 0 if len(mail_nums) > 0: try:", "+ \":\" + options[inc] inc = inc + 1 print \"------------------------------\" choice =", "FETCH ' + x + '\\r\\n') recv = recv_all() return recv #Create def", "print recv_header[pos:pos2] print \"--------------------------------------------------------------------\" print format_email_body(recv_body) print \"===============================================================================\\n\" email_read = email_is_read(mail_type, ch)#0 ==", "time, math print \"Connecting..\" username = \"\" password = \"\" # Choose a", "+ ')')#Add the formated string to the list return mail_info_list #Return a string", "log_success = imap_login() if log_success == -1: close_mail() return 0 choice = \"\"", "pass a different timeout or use the default set in the parameter global", "mail_list = get_mailbox_list_array(mailbox_string) print_mailboxes_list(mail_list) choice = raw_input(\"Enter the number for the box to", "non=blocking sslSocket.setblocking(1) return data_str #Returns a list containing the mailbox names #The parameter", "choice_dest = raw_input('To which folder: ') try: if len(mail_nums)+2 > int(choice) and int(choice)", "\"3\": cmd = 'DRAFT' #text elif choice == \"4\": search_text = raw_input(\"Search for", "empty string, so it isn't needed mail_list = []#Will hold the list of", "TO)]\") recv_uid = imap_uid_fetch(str(ch) + \" (UID)\") print \"\\n===============================================================================\" pos = recv_uid.find('(UID')+5 pos2", "= imap_search('ALL') else: recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) string_list = '' for", "cmd = \"No Box available\" else: name = mail_list[ch_num] if has_children(name, mail_list): decision", "\"2\": examine_mailbox() elif choice == \"3\": if currentFolder == \"None\": print \"\\nNo mail", "= recv.find('\\r') r = recv[pos1:pos2] if r != '': return True else: return", "has a mail box (AND) doesn't contain the /Noselect flag (And) isn't the", "msg_uid pos = recv_header.find(\"Date: \") pos2 = recv_header.find('OK Success\\r\\n')-11 print recv_header[pos:pos2] print \"--------------------------------------------------------------------\"", "for x in range(len(mail_nums)): string_list += str(mail_nums[x]) + ',' if string_list: string_list =", "' -FLAGS (\\seen)') elif choice == \"2\": #delete recv = imap_uid_store(msg_uid + '", "requests from') != -1: print \"Connected.\\n\" else: print \"Problem connecting.\\n\" ################################# #Done connecting", "mail box (AND) doesn't contain the /Noselect flag (And) isn't the all mail", "to delete: \") try: ch_num = int(choice) if ch_num > len(mail_list): cmd =", "mail_list[ch_num] if has_children(name, mail_list): decision = raw_input(\"Are you sure you want to delete", "it passed the timeout, then stop if data_str and time.time()-begin > timeout: break", "'UNSEEN' #old elif choice == \"2\": cmd = 'OLD' #drafts elif choice ==", "= 'N/A' amtRecent = 'N/A' try: amtExist = tmp[17] amtRecent = tmp[19] except:", "print recv return recv #UID Copy def imap_uid_copy(x): sslSocket.send('A300 COPY \"' + x", "= raw_input(\"Date(dd-mm-yyyy)(ex. 1-Sep-2013):\") date_opt = \"ON\" if when_ch == \"1\": date_opt = \"BEFORE\"", "in start #sslSocket = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), #ssl_version = ssl.PROTOCOL_SSLv23) sslSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)", "choice = raw_input(\"Choice: \") if choice == \"1\": view_mailboxes() elif choice == \"2\":", "recv = sslSocket.recv(1024) print recv return recv #UID Search def imap_uid_search(x): sslSocket.send('A999 UID", "recv #UID Search def imap_uid_search(x): sslSocket.send('A999 UID SEARCH ' + x + '\\r\\n')", "+= 1 #Get how many emails each mailbox contains def get_mailboxes_info_array(mail_list): mail_info_list =", "#ssl_version = ssl.PROTOCOL_SSLv23) sslSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sslSocket.connect(mailserver) recv = sslSocket.recv(1024) if recv.find('OK", "recv #Delete def imap_delete(x): print 'A501 DELETE \"' + x + '\"\\r\\n' sslSocket.send('A501", "if len(mail_nums)+2 > int(choice) and int(choice) > 0: print imap_uid_copy(choice + ' '", "#text elif choice == \"4\": search_text = raw_input(\"Search for text: \") cmd =", "= sslSocket.recv(1024) if recv.find(\"completed\") != -1: print \"Successfully logged in to: \" +", "\"' + search_text + '\"' #date elif choice == \"5\": when_ch = raw_input(\"(Before", "try/except to catch errors with getting data from the server try: data =", "',' if string_list: string_list = string_list[:-1] if mail_type == 0: subject_list = imap_fetch(string_list", "date = 1)(On date = 2)(Since date = 3):\") date_ch = raw_input(\"Date(dd-mm-yyyy)(ex. 1-Sep-2013):\")", "temp_list = [] for t in tmp: try: temp_list.append(int(t)) except: pass return temp_list", "raw_input(\"Are you sure you want to delete \" + name + \" and", "print \"Mail box is empty.\" def copy_mail(): imap_examine(currentFolder) recv = imap_uid_search('ALL') mail_nums =", "email_read if email_read: print \"\\nMark as unread = 1, Delete = 2, Leave", "imap_search(str(ch) + ' SEEN') else: recv = imap_uid_search(str(ch) + ' SEEN') pos1 =", "= get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) def examine_mailbox(): global currentFolder mailbox_string = imap_list() mail_list =", "#delete recv = imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print recv imap_expunge() except: print", "info for the emails for x in mail_list: recv = imap_examine(x) tmp =", "else: subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info)", "print_mailboxes_list_with_info(mailbox_list, info): print \"\" print \"---------------------------------\" print \"Mail Boxes:\" index = 0 while", "= [] #Holds the list of info for the emails for x in", "li = [] if l.find('\\nSubject: ') != -1: tmp = l.find('\\nSubject: ') l", "username = \"\" password = \"\" # Choose a mail server (e.g. Google", "0: try: ch = int(choice) if mail_type == 0: recv_body = imap_fetch(str(ch) +", "recv.find(\"completed\") != -1: print \"Successfully logged in to: \" + username + \"\\n\"", "False ################################# #Mail Client Methods ################################# def view_mailboxes(): mailbox_string = imap_list() mail_list =", "- 1 if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails~ Page: ' + str(current_page+1) +", "r = recv[pos1:pos2] tmp = r.split(' ') temp_list = [] for t in", "choice == \"1\": #mark as unread recv = imap_uid_store(msg_uid + ' -FLAGS (\\seen)')", "sslSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sslSocket.connect(mailserver) recv = sslSocket.recv(1024) if recv.find('OK Gimap ready for", "by 2, then there is probably nothing to get, so stop elif time.time()-begin", "box\" print \"8: Delete a mail box\" print \"9: Copy email from selected", "email_list_length - 1 if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails~ Page: ' + str(current_page+1)", "== UID recv = '' if mail_type == 0: recv = imap_search(str(ch) +", "= \"No Box available\" else: name = mail_list[ch_num] if has_children(name, mail_list): decision =", "t in tmp: try: temp_list.append(int(t)) except: pass return temp_list #Return the text of", "Choose a mail server (e.g. Google mail server) and call it mailserver mailserver", "+ \" (UID)\") print \"\\n===============================================================================\" pos = recv_uid.find('(UID')+5 pos2 = recv_uid.find(')') msg_uid =", "(e.g. Google mail server) and call it mailserver mailserver = ('imap.163.com', 143) #", "the begin time so that it doesn't timeout while still getting data else:", "recv = imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print recv imap_expunge() except: print \"Email", "3\" choice = raw_input(\"Choice: \") if choice == \"1\": #mark as unread recv", "sslSocket.send('A142 SELECT \"' + x + '\"\\r\\n') recv = recv_all() return recv #################################", "mailbox_list: if s.find(strg) != -1 and strg != s: return True return False", "print \"\\nNo mail box selected.\" else: get_mail_boxnum() elif choice == \"6\": if currentFolder", "list with additional information def print_mailboxes_list_with_info(mailbox_list, info): print \"\" print \"---------------------------------\" print \"Mail", "if choice == \"1\": view_mailboxes() elif choice == \"2\": examine_mailbox() elif choice ==", "emails each mailbox contains def get_mailboxes_info_array(mail_list): mail_info_list = [] #Holds the list of", "+ \"!\" else: print \"Failed to create.\" def delete_dir(): mailbox_string = imap_list(\"/\", \"*\")", "the box to delete: \") try: ch_num = int(choice) if ch_num > len(mail_list):", "x in range(len(mail_nums)): string_list += str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1]", "#imap Methods ################################# def imap_login():#login print(\"Login information:\") username = \"<EMAIL>\" password = \"password\"", "+ info[index] index = index + 1 print \"---------------------------------\" #Print the email list", "#Return a string of the numbers returned from the search command def get_mail_numbers_from_search(recv):", "choice == \"2\": cmd = 'OLD' #drafts elif choice == \"3\": cmd =", "to login.\\n\") sslSocket.send('A001 LOGIN ' + username + ' ' + password +", "string_list: string_list = string_list[:-1] subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info =", "and x.find('\\Noselect') == -1 and x.find('[Gmail]/All Mail') == -1:#The line has a mail", "len(options): print str(inc) + \":\" + options[inc] inc = inc + 1 print", "box.\" def get_mail_boxnum(): get_mail(0) def get_mail_uid(): get_mail(1) def get_mail(mail_type):#0 == search #1 ==", "\"\\n------------------------------\" print \"Search by:\" inc = 0 while inc < len(options): print str(inc)", "0 while inc < len(options): print str(inc) + \":\" + options[inc] inc =", "choice = raw_input(\"Enter the number for the box to delete: \") try: ch_num", "= 1)(On date = 2)(Since date = 3):\") date_ch = raw_input(\"Date(dd-mm-yyyy)(ex. 1-Sep-2013):\") date_opt", "else: time.sleep(0.1)#give a slight pause before trying to read again except: pass #just", "= raw_input('To which folder: ') try: if len(mail_nums)+2 > int(choice) and int(choice) >", "\"\" # Choose a mail server (e.g. Google mail server) and call it", "= ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), #ssl_version = ssl.PROTOCOL_SSLv23) sslSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sslSocket.connect(mailserver) recv =", "choice == \"3\": cmd = 'DRAFT' #text elif choice == \"4\": search_text =", "\" and all children.(1=yes, 2=no)\") if decision == \"1\": delete_all_children_with_child(name, mail_list) cmd =", "in range(len(mail_nums)): string_list += str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] subject_list", "imap_examine(x) tmp = recv.split(\" \") amtExist = 'N/A' amtRecent = 'N/A' try: amtExist", "recv_all() return recv #Create def imap_create(x): sslSocket.send('A401 CREATE \"' + x + '\"\\r\\n')", "call it mailserver mailserver = ('imap.163.com', 143) # Create socket called clientSocket and", "sslSocket.recv(1024) return recv #Delete def imap_delete(x): print 'A501 DELETE \"' + x +", "\"\\nNo Box chosen\" if cmd == \"all\": print \"Deleted\" else: imap_delete(cmd) if recv.find(\"OK", "+ amtRecent + ')')#Add the formated string to the list return mail_info_list #Return", "\"\\n===============================================================================\" pos = recv_uid.find('(UID')+5 pos2 = recv_uid.find(')') msg_uid = recv_uid[pos:pos2] print \"Email UID:", "this method started begin = time.time() #loop till the timeout has passed while", "pause before trying to read again except: pass #just let it reloop if", "def get_mail_numbers_from_search(recv): pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2] tmp =", "(SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) max_pages = int(len(mail_nums)/email_list_length) if (len(mail_nums)%email_list_length) > 0: max_pages +=", "return 1 else: print \"Login failed!\\n\" return -1 #List def imap_list(dir = \"\",", "\"Login failed!\\n\" return -1 #List def imap_list(dir = \"\", type = \"*\"):#return list", "names in a list with additional information def print_mailboxes_list_with_info(mailbox_list, info): print \"\" print", "using unique id\" print \"7: Create a mail box\" print \"8: Delete a", "raw_input(\"\\nName of new mailbox to create:\") recv = imap_create(name) if recv.find(\"OK Success\") !=", "mailbox names to be returned for x in temp_list: if x.find('/\" \"') !=", "################################# def view_mailboxes(): mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list,", "< len(options): print str(inc) + \":\" + options[inc] inc = inc + 1", "imap_uid_fetch(str(ch) + \" BODY[1]\") recv_header = imap_uid_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM", "len(mail_nums) > 0: print '\\n-------------------------------\\nEmails:' string_list = '' for x in range(len(mail_nums)): string_list", "def get_mailbox_list_array(mailbox_string): temp_list = mailbox_string.split('\\r\\n')#Split the returned string by the new line indicators", "different timeout or use the default set in the parameter global sslSocket #set", "' Recent: ' + amtRecent + ')')#Add the formated string to the list", "raw_input(\"Choice: \") if choice == \"1\": #mark as unread recv = imap_uid_store(msg_uid +", "= index + 1 print \"---------------------------------\" #Print the mailbox names in a list", "BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid = imap_uid_fetch(str(ch) + \" (UID)\") print \"\\n===============================================================================\"", "get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) choice = raw_input(\"Which mail box do you want to open:", "sslSocket.recv(1024) if recv.find('OK Gimap ready for requests from') != -1: print \"Connected.\\n\" else:", "choice == 'next': again = 1 if current_page < max_pages-1: current_page+=1 elif choice", "else: search_mail_uid_search() elif choice == \"5\": if currentFolder == \"None\": print \"\\nNo mail", "Mailbox: \" + currentFolder print \"---------------------------------------------\" print \"What would you like to do?", "parameters to change what is listed sslSocket.send('A101 List ' + \"\\\"\\\"\" +' '+", "recv = recv_all() return recv ################################# #Extra Methods ################################# #Receive using a timeout", "let it reloop if there was an error thrown #set the socket back", "ch = int(choice) if mail_type == 0: recv_body = imap_fetch(str(ch) + \" BODY[1]\")", "imap_uid_store(msg_uid + ' -FLAGS (\\seen)') elif choice == \"2\": #delete recv = imap_uid_store(msg_uid", "\"*\") mail_list = get_mailbox_list_array(mailbox_string) print_mailboxes_list(mail_list) choice = raw_input(\"Enter the number for the box", "delete_all_children_with_child(name, mail_list) cmd = \"all\" else: cmd = \"\" else: cmd = name", "selected mail box to another\" choice = raw_input(\"Choice: \") if choice == \"1\":", "!= -1: tmp = l.find('\\nSubject: ') l = l[tmp:] while l.find('\\nSubject: ') !=", "== 0: recv = imap_search(cmd) else: recv = imap_uid_search(cmd) mail_nums = get_mail_numbers_from_search(recv) if", "is some data that was received then store that data data_str += data", "+ '\"\\r\\n') recv = sslSocket.recv(1024) print recv return recv #UID Copy def imap_uid_copy(x):", "\"\\nNo mail box selected.\" else: get_mail_uid() elif choice == \"7\": create_dir() elif choice", "elif choice == \"6\": if currentFolder == \"None\": print \"\\nNo mail box selected.\"", "only this method is designed for non=blocking sslSocket.setblocking(1) return data_str #Returns a list", "trying to read again except: pass #just let it reloop if there was", "'N/A' amtRecent = 'N/A' try: amtExist = tmp[17] amtRecent = tmp[19] except: pass", "recv = imap_uid_store(msg_uid + ' +FLAGS (\\seen)') elif choice == \"2\": #delete recv", "x in temp_list: if x.find('/\" \"') != -1 and x.find('\\Noselect') == -1 and", "box to delete: \") try: ch_num = int(choice) if ch_num > len(mail_list): cmd", "elif choice == \"7\": create_dir() elif choice == \"8\": delete_dir() elif choice ==", "to non-blocking sslSocket.setblocking(0) #array of the data received data_str = '' #time this", "else: name = mail_list[ch_num] if has_children(name, mail_list): decision = raw_input(\"Are you sure you", "and it has passed the timeout by 2, then there is probably nothing", "1 end = start + email_list_length - 1 if len(mail_nums) > 0: print", "= 3\" choice = raw_input(\"Choice: \") if choice == \"1\": #mark as read", "you want to open: \") try: if int(choice) < len(mail_list): currentFolder = mail_list[int(choice)]", "= x.find('/\" \"')+4 mail_list.append(x[pos:-1]) #Store the substring of the line containing the mailbox", "imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") else: subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\")", "#Fill in start #sslSocket = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), #ssl_version = ssl.PROTOCOL_SSLv23) sslSocket = socket.socket(socket.AF_INET,", "x.find('[Gmail]/All Mail') == -1:#The line has a mail box (AND) doesn't contain the", "recv[first:last] #Return true if the mail box has child boxes def has_children(strg, mailbox_list):", "'TEXT \"' + search_text + '\"' #date elif choice == \"5\": when_ch =", "Methods ################################# def imap_login():#login print(\"Login information:\") username = \"<EMAIL>\" password = \"password\" print(\"Attempting", "recv = recv_all() return recv #Search def imap_search(x): sslSocket.send('A201 SEARCH ' + x", "recv = sslSocket.recv(1024) if recv.find('OK Gimap ready for requests from') != -1: print", "CREATE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) return recv #Delete def", "available.\" def create_dir(): name = raw_input(\"\\nName of new mailbox to create:\") recv =", "choice == \"4\": search_text = raw_input(\"Search for text: \") cmd = 'TEXT \"'", "imap_uid_store(msg_uid + ' +FLAGS (\\seen)') elif choice == \"2\": #delete recv = imap_uid_store(msg_uid", "recv = sslSocket.recv(1024) print recv #Select def imap_select(x): sslSocket.send('A142 SELECT \"' + x", "+ ',' if string_list: string_list = string_list[:-1] if mail_type == 0: subject_list =", "\"!\" else: print \"Failed to create.\" def delete_dir(): mailbox_string = imap_list(\"/\", \"*\") mail_list", "imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) choice = raw_input(\"Which mail", "want to open: \") try: if int(choice) < len(mail_list): currentFolder = mail_list[int(choice)] print", "to the list return mail_info_list #Return a string of the numbers returned from", "stop if data_str and time.time()-begin > timeout: break #If no data has been", "not available.\" def create_dir(): name = raw_input(\"\\nName of new mailbox to create:\") recv", "clientSocket and establish a TCP connection with mailserver #Fill in start #sslSocket =", "(\\deleted)') print recv imap_expunge() else: print \"\\nMark as read = 1, Delete =", "print_mailboxes_list(mailbox_list): print \"\" print \"---------------------------------\" print \"Mail Boxes:\" index = 0 while index", "decision == \"1\": delete_all_children_with_child(name, mail_list) cmd = \"all\" else: cmd = \"\" else:", "#Print the mailbox names in a list def print_mailboxes_list(mailbox_list): print \"\" print \"---------------------------------\"", "int(choice) < len(mail_list): currentFolder = mail_list[int(choice)] print \"\\nSelected \" + currentFolder else: print", "box selected.\" else: get_mail_uid() elif choice == \"7\": create_dir() elif choice == \"8\":", "len(mail_nums) > 0: print '\\n-------------------------------\\nEmails~ Page: ' + str(current_page+1) + '/' + str(max_pages)", "' + date_ch if search_type == 0: recv = imap_search(cmd) else: recv =", "imap_expunge() #Done running def close_mail(): sslSocket.close() #close the socket print \"Done.\" #Main Method", "and call it mailserver mailserver = ('imap.163.com', 143) # Create socket called clientSocket", "\") cmd = 'TEXT \"' + search_text + '\"' #date elif choice ==", "#1 == UID search imap_select(currentFolder) email_list_length = 10 if mail_type == 0: recv", "== -1:#If the point to stop printing in the list wasn't specified in", "#delete recv = imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print recv imap_expunge() else: print", "str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] subject_list = imap_uid_fetch(string_list + \"", "> int(choice) and int(choice) > 0: print imap_uid_copy(choice + ' ' + choice_dest)", "containing the mailbox names #The parameter is the string returned from the imap_list", "wasn't specified in the params, set it to the end of the list", "try: ch = int(choice) if mail_type == 0: recv_body = imap_fetch(str(ch) + \"", "what is listed sslSocket.send('A101 List ' + \"\\\"\\\"\" +' '+ type + '\\r\\n')", "\"' + x + '\"\\r\\n') recv = recv_all() return recv #UID Fetch def", "\"!\" else: print \"Failed to delete.\" def search_mail_search(): search_mail(0) def search_mail_uid_search(): search_mail(1) def", "get_mail_numbers_from_search(recv) string_list = '' for x in range(len(mail_nums)): string_list += str(mail_nums[x]) + ','", "+ ' +FLAGS (\\deleted)') print recv imap_expunge() else: print \"\\nMark as read =", "string_list += str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] if search_type ==", "\"2: Examine a mail box\" print \"3: Search selected mail box\" print \"4:", "sslSocket.setblocking(0) #array of the data received data_str = '' #time this method started", "was received then store that data data_str += data begin=time.time()#reset the begin time", "info[index] index = index + 1 print \"---------------------------------\" #Print the email list in", "= 3):\") date_ch = raw_input(\"Date(dd-mm-yyyy)(ex. 1-Sep-2013):\") date_opt = \"ON\" if when_ch == \"1\":", "= email_is_read(mail_type, ch)#0 == norm #1 == UID #false = unread true =", "username = \"<EMAIL>\" password = \"password\" print(\"Attempting to login.\\n\") sslSocket.send('A001 LOGIN ' +", "Selected Mailbox: \" + currentFolder print \"---------------------------------------------\" print \"What would you like to", "in range(len(mail_nums)): string_list += str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] if", "change what is listed sslSocket.send('A101 List ' + \"\\\"\\\"\" +' '+ type +", "elif choice == \"9\": copy_mail() elif choice == \"10\": testing() if choice ==", "establish a TCP connection with mailserver #Fill in start #sslSocket = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM),", "string_list = string_list[:-1] if mail_type == 0: subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS", "error thrown #set the socket back to blocking since only this method is", "the emails for x in mail_list: recv = imap_examine(x) tmp = recv.split(\" \")", "= mail_list[ch_num] if has_children(name, mail_list): decision = raw_input(\"Are you sure you want to", "imap_create(x): sslSocket.send('A401 CREATE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) return recv", "else: subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) max_pages =", "imap_create(name) if recv.find(\"OK Success\") != -1: print \"Created \" + name + \"!\"", "you sure you want to delete \" + name + \" and all", "mail server (e.g. Google mail server) and call it mailserver mailserver = ('imap.163.com',", "= raw_input(\"Choice: \") if choice == \"1\": #mark as unread recv = imap_uid_store(msg_uid", "#close the socket print \"Done.\" #Main Method def main(): log_success = imap_login() if", "imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print recv imap_expunge() else: print \"\\nMark as read", "= sslSocket.recv(1024) print recv #Select def imap_select(x): sslSocket.send('A142 SELECT \"' + x +", "recv imap_expunge() except: print \"Email not available.\" def create_dir(): name = raw_input(\"\\nName of", "\" (UID)\") print \"\\n===============================================================================\" pos = recv_uid.find('(UID')+5 pos2 = recv_uid.find(')') msg_uid = recv_uid[pos:pos2]", "emails for x in mail_list: recv = imap_examine(x) tmp = recv.split(\" \") amtExist", "recv_header = imap_uid_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid = imap_uid_fetch(str(ch)", "\"------------------------------\" choice = raw_input(\"Choice: \") cmd = \"\" #all if choice == \"0\":", "#Get how many emails each mailbox contains def get_mailboxes_info_array(mail_list): mail_info_list = [] #Holds", "+ currentFolder else: print \"\\nNot a valid mail box.\" except: print \"\\nNot a", "\"3\": if currentFolder == \"None\": print \"\\nNo mail box selected.\" else: search_mail_search() elif", "' ' + choice_dest) else: print \"Not a valid email.\" except: print \"Invalid", "print imap_uid_copy(choice + ' ' + choice_dest) else: print \"Not a valid email.\"", "+ password + '\\r\\n') recv = sslSocket.recv(1024) if recv.find(\"completed\") != -1: print \"Successfully", "date_opt = \"ON\" elif when_ch == \"3\": date_opt = \"SINCE\" cmd = date_opt", "\" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) max_pages = int(len(mail_nums)/email_list_length) if (len(mail_nums)%email_list_length) > 0:", "to get, so stop elif time.time()-begin > timeout*2: break #try and get the", "+ \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid = imap_uid_fetch(str(ch) + \" (UID)\")", "print \"Done.\" #Main Method def main(): log_success = imap_login() if log_success == -1:", "\" + username + \"\\n\" return 1 else: print \"Login failed!\\n\" return -1", "currentFolder print \"---------------------------------------------\" print \"What would you like to do? (0 to quit.)\"", "start + email_list_length - 1 if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails~ Page: '", "0 else: print \"Mail box is empty.\" again = 0 if len(mail_nums) >", "#List def imap_list(dir = \"\", type = \"*\"):#return list of mailboxes with optional", "containing the mailbox name return mail_list #Print the mailbox names in a list", "emails if end == -1:#If the point to stop printing in the list", "This is the email subject def print_mail_list_with_subject(nums, subs, start = 1, end =", "1 start = current_page * email_list_length + 1 end = start + email_list_length", "#1 == UID search imap_examine(currentFolder) options = [\"All\", \"Unread\", \"Old\", \"Drafts\", \"Text\", \"Date\"]", "box to another\" choice = raw_input(\"Choice: \") if choice == \"1\": view_mailboxes() elif", "== UID search imap_examine(currentFolder) options = [\"All\", \"Unread\", \"Old\", \"Drafts\", \"Text\", \"Date\"] print", "is listed sslSocket.send('A101 List ' + \"\\\"\\\"\" +' '+ type + '\\r\\n') recv", "name = mail_list[ch_num] if has_children(name, mail_list): decision = raw_input(\"Are you sure you want", "since only this method is designed for non=blocking sslSocket.setblocking(1) return data_str #Returns a", "0 while index < len(mailbox_list): print str(index) + \":\" + mailbox_list[index] index =", "the email body def format_email_body(recv): first = 0 last = len(recv)-1 if recv.find('}')", "is = 3\" choice = raw_input(\"Choice: \") if choice == \"1\": #mark as", "!= '': li.append(new) l = l[pos2+1:] return li def email_is_read(mail_type, ch):#0 == norm", "ch)#0 == norm #1 == UID #false = unread true = read print", "!= -1: pos1 = l.find('\\nSubject: ')+1 pos2 = l.find('\\r') new = l[pos1:pos2] if", "\"===============================================================================\\n\" email_read = email_is_read(mail_type, ch)#0 == norm #1 == UID #false = unread", "')')#Add the formated string to the list return mail_info_list #Return a string of", "+ ' +FLAGS (\\deleted)') print recv imap_expunge() except: print \"Email not available.\" def", "len(nums) and start <= end:#Print the specified elements of the lists print str(nums[start-1])", "\"8\": delete_dir() elif choice == \"9\": copy_mail() elif choice == \"10\": testing() if", "raw_input(\"Choice: \") cmd = \"\" #all if choice == \"0\": cmd = 'ALL'", "elif choice == 'PREV' or choice == 'prev': again = 1 if current_page", "errors with getting data from the server try: data = sslSocket.recv(1024) if data:", "formated string to the list return mail_info_list #Return a string of the numbers", "\"') != -1 and x.find('\\Noselect') == -1 and x.find('[Gmail]/All Mail') == -1:#The line", "string by the new line indicators del temp_list[len(temp_list)-1]#The last element is an empty", "return False ################################# #Mail Client Methods ################################# def view_mailboxes(): mailbox_string = imap_list() mail_list", "mail_list = []#Will hold the list of mailbox names to be returned for", "msg_uid = recv_uid[pos:pos2] print \"Email UID: \" + msg_uid pos = recv_header.find(\"Date: \")", "imap_login():#login print(\"Login information:\") username = \"<EMAIL>\" password = \"password\" print(\"Attempting to login.\\n\") sslSocket.send('A001", "= \"\" password = \"\" # Choose a mail server (e.g. Google mail", "+ x + '\"\\r\\n') recv = recv_all() return recv ################################# #Extra Methods #################################", "(DATE SUBJECT FROM TO)]\") recv_uid = imap_uid_fetch(str(ch) + \" (UID)\") print \"\\n===============================================================================\" pos", "command def get_mailbox_list_array(mailbox_string): temp_list = mailbox_string.split('\\r\\n')#Split the returned string by the new line", "open: \") try: if int(choice) < len(mail_list): currentFolder = mail_list[int(choice)] print \"\\nSelected \"", "mail box using unique id\" print \"7: Create a mail box\" print \"8:", "options = [\"All\", \"Unread\", \"Old\", \"Drafts\", \"Text\", \"Date\"] print \"\\n------------------------------\" print \"Search by:\"", "= raw_input(\"Choice: \") if choice == \"1\": view_mailboxes() elif choice == \"2\": examine_mailbox()", "mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) def examine_mailbox(): global currentFolder mailbox_string = imap_list() mail_list", "+ '\\r\\n') recv = recv_all() return recv #Create def imap_create(x): sslSocket.send('A401 CREATE \"'", "Methods ################################# def view_mailboxes(): mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list)", "== \"3\": cmd = 'DRAFT' #text elif choice == \"4\": search_text = raw_input(\"Search", "valid mail box.\" except: print \"\\nNot a valid mail box.\" def get_mail_boxnum(): get_mail(0)", "== UID #false = unread true = read print email_read if email_read: print", "'\"' #date elif choice == \"5\": when_ch = raw_input(\"(Before date = 1)(On date", "print \"Mail box is empty.\" choice = raw_input('\\nWhich email do you want to", "= '' for x in range(len(mail_nums)): string_list += str(mail_nums[x]) + ',' if string_list:", "del temp_list[len(temp_list)-1]#The last element is an empty string, so it isn't needed mail_list", "in reversed(range(len(recv))): #Loop from the end til it find the A if recv[index]", "as read = 1, Delete = 2, Leave as is = 3\" choice", "search_text = raw_input(\"Search for text: \") cmd = 'TEXT \"' + search_text +", "recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2] tmp = r.split(' ') temp_list =", "= imap_fetch(str(ch) + \" BODY[1]\") recv_header = imap_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT", "Fetch def imap_uid_fetch(x): sslSocket.send('A999 UID FETCH ' + x + '\\r\\n') recv =", "recv.find('}') + 3 for index in reversed(range(len(recv))): #Loop from the end til it", "in the format (box number or uid number): Subject: This is the email", "recv_uid = imap_fetch(str(ch) + \" (UID)\") else: recv_body = imap_uid_fetch(str(ch) + \" BODY[1]\")", "!= \"0\": print \"\\n\" print \"---------------------------------------------\" print \"-- Currently Selected Mailbox: \" +", "mail box\" print \"3: Search selected mail box\" print \"4: Search using message", "mailserver #Fill in start #sslSocket = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), #ssl_version = ssl.PROTOCOL_SSLv23) sslSocket =", "= 'TEXT \"' + search_text + '\"' #date elif choice == \"5\": when_ch", "#Holds the list of info for the emails for x in mail_list: recv", "a TCP connection with mailserver #Fill in start #sslSocket = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), #ssl_version", "\"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) return recv #Delete def imap_delete(x):", "empty.\" choice = raw_input('\\nWhich email do you want to copy: ') choice_dest =", "start = 1, end = -1):#nums = the numbers of the emails, subs", "+ '\"\\r\\n' sslSocket.send('A501 DELETE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) print", "the data received data_str = '' #time this method started begin = time.time()", "create:\") recv = imap_create(name) if recv.find(\"OK Success\") != -1: print \"Created \" +", "+ mailbox_list[index] + \" \" + info[index] index = index + 1 print", "recv = recv_all() return recv #Expunge def imap_expunge(): sslSocket.send('A202 EXPUNGE\\r\\n') recv = sslSocket.recv(1024)", "0 if len(mail_nums) > 0: try: ch = int(choice) if mail_type == 0:", "password = \"password\" print(\"Attempting to login.\\n\") sslSocket.send('A001 LOGIN ' + username + '", "the socket to non-blocking sslSocket.setblocking(0) #array of the data received data_str = ''", "' ' + password + '\\r\\n') recv = sslSocket.recv(1024) if recv.find(\"completed\") != -1:", "index < len(mailbox_list): print str(index) + \":\" + mailbox_list[index] + \" \" +", "if mail_type == 0: subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") else: subject_list", "#Return true if the mail box has child boxes def has_children(strg, mailbox_list): for", "################################# #Mail Client Methods ################################# def view_mailboxes(): mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string)", "\"Mail box is empty.\" choice = raw_input('\\nWhich email do you want to copy:", "== \"1\": cmd = 'UNSEEN' #old elif choice == \"2\": cmd = 'OLD'", "body def format_email_body(recv): first = 0 last = len(recv)-1 if recv.find('}') != -1:#Find", "the server try: data = sslSocket.recv(1024) if data: #if there is some data", "main(): log_success = imap_login() if log_success == -1: close_mail() return 0 choice =", "imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) string_list = '' for x in range(len(mail_nums)): string_list +=", "the line containing the mailbox name return mail_list #Print the mailbox names in", "0: max_pages += 1 current_page = 0 again = 1 while again ==", "'' for x in range(len(mail_nums)): string_list += str(mail_nums[x]) + ',' if string_list: string_list", "recv #Examine def imap_examine(x): sslSocket.send('A900 EXAMINE \"' + x + '\"\\r\\n') recv =", "a valid mail box.\" def get_mail_boxnum(): get_mail(0) def get_mail_uid(): get_mail(1) def get_mail(mail_type):#0 ==", "(SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box is empty.\" def", "+ \" (UID)\") else: recv_body = imap_uid_fetch(str(ch) + \" BODY[1]\") recv_header = imap_uid_fetch(str(ch)", "imap_search(cmd) else: recv = imap_uid_search(cmd) mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0: string_list", "data data_str += data begin=time.time()#reset the begin time so that it doesn't timeout", "temp_list #Return the text of the email body def format_email_body(recv): first = 0", "sslSocket.recv(1024) print recv return recv #UID Search def imap_uid_search(x): sslSocket.send('A999 UID SEARCH '", "\" + msg_uid pos = recv_header.find(\"Date: \") pos2 = recv_header.find('OK Success\\r\\n')-11 print recv_header[pos:pos2]", "\"None\": print \"\\nNo mail box selected.\" else: search_mail_uid_search() elif choice == \"5\": if", "def delete_dir(): mailbox_string = imap_list(\"/\", \"*\") mail_list = get_mailbox_list_array(mailbox_string) print_mailboxes_list(mail_list) choice = raw_input(\"Enter", "+ ' +FLAGS (\\seen)') elif choice == \"2\": #delete recv = imap_uid_store(msg_uid +", "recv_header[pos:pos2] print \"--------------------------------------------------------------------\" print format_email_body(recv_body) print \"===============================================================================\\n\" email_read = email_is_read(mail_type, ch)#0 == norm", "= imap_uid_search(str(ch) + ' SEEN') pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r =", "choice == 'PREV' or choice == 'prev': again = 1 if current_page >", "= 1, end = -1):#nums = the numbers of the emails, subs =", "Copy email from selected mail box to another\" choice = raw_input(\"Choice: \") if", "passed the timeout, then stop if data_str and time.time()-begin > timeout: break #If", "print \"\\nNo mail box selected.\" else: search_mail_search() elif choice == \"4\": if currentFolder", "imap_select(x): sslSocket.send('A142 SELECT \"' + x + '\"\\r\\n') recv = recv_all() return recv", "== 'A': last = index - 5 break return recv[first:last] #Return true if", "the search command def get_mail_numbers_from_search(recv): pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r =", "Methods ################################# #Receive using a timeout def recv_all(timeout = 2):#can either pass a", "a mail box\" print \"9: Copy email from selected mail box to another\"", "+ '\"\\r\\n') recv = recv_all() return recv #UID Fetch def imap_uid_fetch(x): sslSocket.send('A999 UID", "\"ON\" elif when_ch == \"3\": date_opt = \"SINCE\" cmd = date_opt + '", "+ \"!\" else: print \"Failed to delete.\" def search_mail_search(): search_mail(0) def search_mail_uid_search(): search_mail(1)", "temp_list.append(int(t)) except: pass return temp_list #Return the text of the email body def", "UID #false = unread true = read print email_read if email_read: print \"\\nMark", "if end == -1:#If the point to stop printing in the list wasn't", "it mailserver mailserver = ('imap.163.com', 143) # Create socket called clientSocket and establish", "'\"\\r\\n') recv = sslSocket.recv(1024) return recv #Fetch def imap_fetch(x): sslSocket.send('A301 FETCH ' +", "\"Search by:\" inc = 0 while inc < len(options): print str(inc) + \":\"", "mailserver = ('imap.163.com', 143) # Create socket called clientSocket and establish a TCP", "choice == \"0\": cmd = 'ALL' #unread elif choice == \"1\": cmd =", "\") try: ch_num = int(choice) if ch_num > len(mail_list): cmd = \"No Box", "\"\\nNo mail box selected.\" else: search_mail_search() elif choice == \"4\": if currentFolder ==", "box has child boxes def has_children(strg, mailbox_list): for s in mailbox_list: if s.find(strg)", "has passed while True: #If some data was receive and it passed the", "box is empty.\" again = 0 if len(mail_nums) > 0: try: ch =", "len(recv)-1 if recv.find('}') != -1:#Find the first } first = recv.find('}') + 3", "= \"None\" #Stores the currently selected mail box ################################# #imap Methods ################################# def", "> timeout*2: break #try and get the data using a try/except to catch", "= imap_uid_store(msg_uid + ' +FLAGS (\\seen)') elif choice == \"2\": #delete recv =", "= int(len(mail_nums)/email_list_length) if (len(mail_nums)%email_list_length) > 0: max_pages += 1 current_page = 0 again", "return recv #UID Search def imap_uid_search(x): sslSocket.send('A999 UID SEARCH ' + x +", "print \"Checking: \" + cmd if cmd == \"\": print \"\\nNo Box chosen\"", "as read recv = imap_uid_store(msg_uid + ' +FLAGS (\\seen)') elif choice == \"2\":", "back to blocking since only this method is designed for non=blocking sslSocket.setblocking(1) return", "stop printing in the list wasn't specified in the params, set it to", "login.\\n\") sslSocket.send('A001 LOGIN ' + username + ' ' + password + '\\r\\n')", "specified in the params, set it to the end of the list end", "print \"\\nMark as unread = 1, Delete = 2, Leave as is =", "mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) choice = raw_input(\"Which mail box", "cmd = \"\" print \"Checking: \" + cmd if cmd == \"\": print", "= recv_all() return recv #UID Fetch def imap_uid_fetch(x): sslSocket.send('A999 UID FETCH ' +", "Client Methods ################################# def view_mailboxes(): mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info =", "return recv #Search def imap_search(x): sslSocket.send('A201 SEARCH ' + x + '\\r\\n') recv", "+ ' ' + password + '\\r\\n') recv = sslSocket.recv(1024) if recv.find(\"completed\") !=", "recv = '' if mail_type == 0: recv = imap_search(str(ch) + ' SEEN')", "UID search imap_select(currentFolder) email_list_length = 10 if mail_type == 0: recv = imap_search('ALL')", "if len(mail_nums) > 0: try: ch = int(choice) if mail_type == 0: recv_body", "#Print the mailbox names in a list with additional information def print_mailboxes_list_with_info(mailbox_list, info):", "there is probably nothing to get, so stop elif time.time()-begin > timeout*2: break", "choice == \"2\": #delete recv = imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print recv", "< len(mailbox_list): print str(index) + \":\" + mailbox_list[index] index = index + 1", "#If some data was receive and it passed the timeout, then stop if", "examine_mailbox(): global currentFolder mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list,", "mailbox_string.split('\\r\\n')#Split the returned string by the new line indicators del temp_list[len(temp_list)-1]#The last element", "set in the parameter global sslSocket #set the socket to non-blocking sslSocket.setblocking(0) #array", "get_mail_numbers_from_search(recv): pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2] tmp = r.split('", "to read again except: pass #just let it reloop if there was an", "\"1\": #mark as unread recv = imap_uid_store(msg_uid + ' -FLAGS (\\seen)') elif choice", "if cmd == \"\": print \"\\nNo Box chosen\" if cmd == \"all\": print", "+ x + '\\r\\n') recv = recv_all() return recv #Create def imap_create(x): sslSocket.send('A401", "x.find('/\" \"')+4 mail_list.append(x[pos:-1]) #Store the substring of the line containing the mailbox name", "else: recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) string_list = '' for x in", "= raw_input(\"Choice: \") if choice == \"1\": #mark as read recv = imap_uid_store(msg_uid", "type + '\\r\\n') recv = recv_all() return recv #Search def imap_search(x): sslSocket.send('A201 SEARCH", "timeout*2: break #try and get the data using a try/except to catch errors", "begin=time.time()#reset the begin time so that it doesn't timeout while still getting data", "the mailbox names #The parameter is the string returned from the imap_list command", "children.(1=yes, 2=no)\") if decision == \"1\": delete_all_children_with_child(name, mail_list) cmd = \"all\" else: cmd", "name except: cmd = \"\" print \"Checking: \" + cmd if cmd ==", "all mail boxes\" print \"2: Examine a mail box\" print \"3: Search selected", "the all mail folder pos = x.find('/\" \"')+4 mail_list.append(x[pos:-1]) #Store the substring of", "def imap_expunge(): sslSocket.send('A202 EXPUNGE\\r\\n') recv = sslSocket.recv(1024) print recv #Select def imap_select(x): sslSocket.send('A142", "mail_info_list = [] #Holds the list of info for the emails for x", "\"1: View all mail boxes\" print \"2: Examine a mail box\" print \"3:", "== 0: recv = imap_search('ALL') else: recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) string_list", "= raw_input(\"Which email do you want to open? \") if choice == 'NEXT'", "\"1\": date_opt = \"BEFORE\" elif when_ch == \"2\": date_opt = \"ON\" elif when_ch", "lists print str(nums[start-1]) + \": \" + str(subs[start-1]) start += 1 #Get how", "1 print \"---------------------------------\" #Print the mailbox names in a list with additional information", "\"---------------------------------------------\" print \"What would you like to do? (0 to quit.)\" print \"1:", "+FLAGS (\\seen)') elif choice == \"2\": #delete recv = imap_uid_store(msg_uid + ' +FLAGS", "################################# #imap Methods ################################# def imap_login():#login print(\"Login information:\") username = \"<EMAIL>\" password =", "1 print \"---------------------------------\" #Print the email list in the format (box number or", "recv #UID Fetch def imap_uid_fetch(x): sslSocket.send('A999 UID FETCH ' + x + '\\r\\n')", "sslSocket.send('A401 CREATE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) return recv #Delete", "\" + str(subs[start-1]) start += 1 #Get how many emails each mailbox contains", "len(mail_nums) > 0: string_list = '' for x in range(len(mail_nums)): string_list += str(mail_nums[x])", "mail_nums = get_mail_numbers_from_search(recv) string_list = '' for x in range(len(mail_nums)): string_list += str(mail_nums[x])", "end til it find the A if recv[index] == 'A': last = index", "the list wasn't specified in the params, set it to the end of", "try: ch_num = int(choice) if ch_num > len(mail_list): cmd = \"No Box available\"", "= string_list[:-1] if mail_type == 0: subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\")", "\" BODY[1]\") recv_header = imap_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid", "\" + name + \" and all children.(1=yes, 2=no)\") if decision == \"1\":", "(UID)\") else: recv_body = imap_uid_fetch(str(ch) + \" BODY[1]\") recv_header = imap_uid_fetch(str(ch) + \"", "read again except: pass #just let it reloop if there was an error", "mail box.\" def get_mail_boxnum(): get_mail(0) def get_mail_uid(): get_mail(1) def get_mail(mail_type):#0 == search #1", "of mailbox names to be returned for x in temp_list: if x.find('/\" \"')", "+ ',' if string_list: string_list = string_list[:-1] subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS", "if choice == \"0\": cmd = 'ALL' #unread elif choice == \"1\": cmd", "= time.time() #loop till the timeout has passed while True: #If some data", "print \"5: Get mail from selected mail box\" print \"6: Get mail from", "math print \"Connecting..\" username = \"\" password = \"\" # Choose a mail", "email_read: print \"\\nMark as unread = 1, Delete = 2, Leave as is", "\"7: Create a mail box\" print \"8: Delete a mail box\" print \"9:", "' +FLAGS (\\seen)') elif choice == \"2\": #delete recv = imap_uid_store(msg_uid + '", "2)(Since date = 3):\") date_ch = raw_input(\"Date(dd-mm-yyyy)(ex. 1-Sep-2013):\") date_opt = \"ON\" if when_ch", "\"1\": #mark as read recv = imap_uid_store(msg_uid + ' +FLAGS (\\seen)') elif choice", "#set the socket to non-blocking sslSocket.setblocking(0) #array of the data received data_str =", "the mailbox names in a list def print_mailboxes_list(mailbox_list): print \"\" print \"---------------------------------\" print", "while index < len(mailbox_list): print str(index) + \":\" + mailbox_list[index] index = index", "doesn't timeout while still getting data else: time.sleep(0.1)#give a slight pause before trying", "currentFolder == \"None\": print \"\\nNo mail box selected.\" else: search_mail_uid_search() elif choice ==", "copy: ') choice_dest = raw_input('To which folder: ') try: if len(mail_nums)+2 > int(choice)", "mailbox_list[index] + \" \" + info[index] index = index + 1 print \"---------------------------------\"", "+ 1 end = start + email_list_length - 1 if len(mail_nums) > 0:", "connection with mailserver #Fill in start #sslSocket = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), #ssl_version = ssl.PROTOCOL_SSLv23)", "to stop printing in the list wasn't specified in the params, set it", "tmp[19] except: pass mail_info_list.append('(Emails: ' + amtExist + ' Recent: ' + amtRecent", "\"-- Currently Selected Mailbox: \" + currentFolder print \"---------------------------------------------\" print \"What would you", "when_ch == \"2\": date_opt = \"ON\" elif when_ch == \"3\": date_opt = \"SINCE\"", "COPY \"' + x + '\"\\r\\n') recv = recv_all() return recv #UID Fetch", "- 5 break return recv[first:last] #Return true if the mail box has child", "print \"---------------------------------\" #Print the mailbox names in a list with additional information def", "\" + cmd if cmd == \"\": print \"\\nNo Box chosen\" if cmd", "to open? \") if choice == 'NEXT' or choice == 'next': again =", "(SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box is empty.\" choice", "data was receive and it passed the timeout, then stop if data_str and", "box\" print \"3: Search selected mail box\" print \"4: Search using message unique", "= raw_input(\"Search for text: \") cmd = 'TEXT \"' + search_text + '\"'", "as unread recv = imap_uid_store(msg_uid + ' -FLAGS (\\seen)') elif choice == \"2\":", "== \"1\": view_mailboxes() elif choice == \"2\": examine_mailbox() elif choice == \"3\": if", "elif time.time()-begin > timeout*2: break #try and get the data using a try/except", "options[inc] inc = inc + 1 print \"------------------------------\" choice = raw_input(\"Choice: \") cmd", "choice = raw_input(\"Choice: \") if choice == \"1\": #mark as read recv =", "if recv.find(\"OK Success\") != -1: print \"Deleted \" + name + \"!\" else:", "len(mail_nums) > 0: try: ch = int(choice) if mail_type == 0: recv_body =", "= imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") else: subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS", "-1: print \"Connected.\\n\" else: print \"Problem connecting.\\n\" ################################# #Done connecting ################################# ################################# #Global", "either pass a different timeout or use the default set in the parameter", "if email_read: print \"\\nMark as unread = 1, Delete = 2, Leave as", "def get_mailboxes_info_array(mail_list): mail_info_list = [] #Holds the list of info for the emails", "\"Drafts\", \"Text\", \"Date\"] print \"\\n------------------------------\" print \"Search by:\" inc = 0 while inc", "str(nums[start-1]) + \": \" + str(subs[start-1]) start += 1 #Get how many emails", "def imap_uid_fetch(x): sslSocket.send('A999 UID FETCH ' + x + '\\r\\n') recv = recv_all()", "if search_type == 0: recv = imap_search(cmd) else: recv = imap_uid_search(cmd) mail_nums =", "recv_header.find(\"Date: \") pos2 = recv_header.find('OK Success\\r\\n')-11 print recv_header[pos:pos2] print \"--------------------------------------------------------------------\" print format_email_body(recv_body) print", "socket.socket(socket.AF_INET, socket.SOCK_STREAM) sslSocket.connect(mailserver) recv = sslSocket.recv(1024) if recv.find('OK Gimap ready for requests from')", "the timeout by 2, then there is probably nothing to get, so stop", "mail_list.append(x[pos:-1]) #Store the substring of the line containing the mailbox name return mail_list", "\"\" print \"---------------------------------\" print \"Mail Boxes:\" index = 0 while index < len(mailbox_list):", "amtRecent = 'N/A' try: amtExist = tmp[17] amtRecent = tmp[19] except: pass mail_info_list.append('(Emails:", "get, so stop elif time.time()-begin > timeout*2: break #try and get the data", "print 'A003 UID STORE ' + x + '\\r\\n' sslSocket.send('A003 UID STORE '", "date_opt + ' ' + date_ch if search_type == 0: recv = imap_search(cmd)", "')+1 pos2 = l.find('\\r') new = l[pos1:pos2] if new != '': li.append(new) l", "= recv_uid[pos:pos2] print \"Email UID: \" + msg_uid pos = recv_header.find(\"Date: \") pos2", "timeout has passed while True: #If some data was receive and it passed", "\"No Box available\" else: name = mail_list[ch_num] if has_children(name, mail_list): decision = raw_input(\"Are", "Success\") != -1: print \"Created \" + name + \"!\" else: print \"Failed", "recv = imap_uid_search(cmd) mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0: string_list = ''", "\":\" + options[inc] inc = inc + 1 print \"------------------------------\" choice = raw_input(\"Choice:", "\"\" print \"Checking: \" + cmd if cmd == \"\": print \"\\nNo Box", "still getting data else: time.sleep(0.1)#give a slight pause before trying to read again", "x + '\\r\\n' sslSocket.send('A003 UID STORE ' + x + '\\r\\n') recv =", "= sslSocket.recv(1024) return recv #Delete def imap_delete(x): print 'A501 DELETE \"' + x", "or choice == 'next': again = 1 if current_page < max_pages-1: current_page+=1 elif", "== \"2\": cmd = 'OLD' #drafts elif choice == \"3\": cmd = 'DRAFT'", "print \"8: Delete a mail box\" print \"9: Copy email from selected mail", "return temp_list #Return the text of the email body def format_email_body(recv): first =", "imap_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid = imap_fetch(str(ch) + \"", "mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box is empty.\" def copy_mail():", "TO)]\") recv_uid = imap_fetch(str(ch) + \" (UID)\") else: recv_body = imap_uid_fetch(str(ch) + \"", "= raw_input(\"Which mail box do you want to open: \") try: if int(choice)", "the /Noselect flag (And) isn't the all mail folder pos = x.find('/\" \"')+4", "choice == \"9\": copy_mail() elif choice == \"10\": testing() if choice == \"0\":", "if log_success == -1: close_mail() return 0 choice = \"\" #The main loop", "#all if choice == \"0\": cmd = 'ALL' #unread elif choice == \"1\":", "+ 1 print \"---------------------------------\" #Print the mailbox names in a list with additional", "= string_list[:-1] if search_type == 0: subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\")", "= get_mail_numbers_from_search(recv) if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails:' string_list = '' for x", "#Main Method def main(): log_success = imap_login() if log_success == -1: close_mail() return", "\"Deleted\" else: imap_delete(cmd) if recv.find(\"OK Success\") != -1: print \"Deleted \" + name", "want to open? \") if choice == 'NEXT' or choice == 'next': again", "== \"4\": if currentFolder == \"None\": print \"\\nNo mail box selected.\" else: search_mail_uid_search()", "elif choice == \"2\": cmd = 'OLD' #drafts elif choice == \"3\": cmd", "elif choice == \"1\": cmd = 'UNSEEN' #old elif choice == \"2\": cmd", "email do you want to copy: ') choice_dest = raw_input('To which folder: ')", "= 2, Leave as is = 3\" choice = raw_input(\"Choice: \") if choice", "subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else:", "imap_list command def get_mailbox_list_array(mailbox_string): temp_list = mailbox_string.split('\\r\\n')#Split the returned string by the new", "-1: imap_delete(s) def filter_list_of_subjects(l): li = [] if l.find('\\nSubject: ') != -1: tmp", "recv #Search def imap_search(x): sslSocket.send('A201 SEARCH ' + x + '\\r\\n') recv =", "params, set it to the end of the list end = len(subs) while", "the list return mail_info_list #Return a string of the numbers returned from the", "first = recv.find('}') + 3 for index in reversed(range(len(recv))): #Loop from the end", "\"BEFORE\" elif when_ch == \"2\": date_opt = \"ON\" elif when_ch == \"3\": date_opt", "raw_input(\"Date(dd-mm-yyyy)(ex. 1-Sep-2013):\") date_opt = \"ON\" if when_ch == \"1\": date_opt = \"BEFORE\" elif", "string, so it isn't needed mail_list = []#Will hold the list of mailbox", "= raw_input('\\nWhich email do you want to copy: ') choice_dest = raw_input('To which", "mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box is empty.\" choice =", "mailboxes_info, start, end) print \"\\nTo view more mail type, NEXT or PREV\" choice", "for the box to delete: \") try: ch_num = int(choice) if ch_num >", "names to be returned for x in temp_list: if x.find('/\" \"') != -1", "sslSocket.recv(1024) if recv.find(\"completed\") != -1: print \"Successfully logged in to: \" + username", "current_page < max_pages-1: current_page+=1 elif choice == 'PREV' or choice == 'prev': again", "' + x + '\\r\\n') recv = sslSocket.recv(1024) print recv return recv #UID", "true = read print email_read if email_read: print \"\\nMark as unread = 1,", "selected mail box\" print \"4: Search using message unique id\" print \"5: Get", "3 for index in reversed(range(len(recv))): #Loop from the end til it find the", "Store def imap_uid_store(x): print 'A003 UID STORE ' + x + '\\r\\n' sslSocket.send('A003", "SUBJECT FROM TO)]\") recv_uid = imap_fetch(str(ch) + \" (UID)\") else: recv_body = imap_uid_fetch(str(ch)", "to open: \") try: if int(choice) < len(mail_list): currentFolder = mail_list[int(choice)] print \"\\nSelected", "string_list[:-1] if mail_type == 0: subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") else:", "except: pass return temp_list #Return the text of the email body def format_email_body(recv):", "(SUBJECT)]\") else: subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) max_pages", "= []#Will hold the list of mailbox names to be returned for x", "\"*\"):#return list of mailboxes with optional parameters to change what is listed sslSocket.send('A101", "thrown #set the socket back to blocking since only this method is designed", "== \"1\": delete_all_children_with_child(name, mail_list) cmd = \"all\" else: cmd = \"\" else: cmd", "currentFolder == \"None\": print \"\\nNo mail box selected.\" else: search_mail_search() elif choice ==", "mail_list) cmd = \"all\" else: cmd = \"\" else: cmd = name except:", "#Stores the currently selected mail box ################################# #imap Methods ################################# def imap_login():#login print(\"Login", "numbers of the emails, subs = the subjects of the emails if end", "currentFolder else: print \"\\nNot a valid mail box.\" except: print \"\\nNot a valid", "== \"7\": create_dir() elif choice == \"8\": delete_dir() elif choice == \"9\": copy_mail()", "if len(mail_nums) > 0: string_list = '' for x in range(len(mail_nums)): string_list +=", "= \"<EMAIL>\" password = \"password\" print(\"Attempting to login.\\n\") sslSocket.send('A001 LOGIN ' + username", "Success\") != -1: print \"Deleted \" + name + \"!\" else: print \"Failed", "names #The parameter is the string returned from the imap_list command def get_mailbox_list_array(mailbox_string):", "with getting data from the server try: data = sslSocket.recv(1024) if data: #if", "with optional parameters to change what is listed sslSocket.send('A101 List ' + \"\\\"\\\"\"", "and get the data using a try/except to catch errors with getting data", "box\" print \"4: Search using message unique id\" print \"5: Get mail from", "3\" choice = raw_input(\"Choice: \") if choice == \"1\": #mark as read recv", "def imap_uid_search(x): sslSocket.send('A999 UID SEARCH ' + x + '\\r\\n') recv = recv_all()", "else: get_mail_boxnum() elif choice == \"6\": if currentFolder == \"None\": print \"\\nNo mail", "= imap_uid_fetch(str(ch) + \" BODY[1]\") recv_header = imap_uid_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT", "string_list[:-1] subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info)", "while l.find('\\nSubject: ') != -1: pos1 = l.find('\\nSubject: ')+1 pos2 = l.find('\\r') new", "list of mailboxes with optional parameters to change what is listed sslSocket.send('A101 List", "-1 and x.find('[Gmail]/All Mail') == -1:#The line has a mail box (AND) doesn't", "= 0 while index < len(mailbox_list): print str(index) + \":\" + mailbox_list[index] index", "choice == \"7\": create_dir() elif choice == \"8\": delete_dir() elif choice == \"9\":", "email_list_length = 10 if mail_type == 0: recv = imap_search('ALL') else: recv =", "#array of the data received data_str = '' #time this method started begin", "(UID)\") print \"\\n===============================================================================\" pos = recv_uid.find('(UID')+5 pos2 = recv_uid.find(')') msg_uid = recv_uid[pos:pos2] print", "socket to non-blocking sslSocket.setblocking(0) #array of the data received data_str = '' #time", "+ x + '\"\\r\\n' sslSocket.send('A501 DELETE \"' + x + '\"\\r\\n') recv =", "subjects of the emails if end == -1:#If the point to stop printing", "\"None\": print \"\\nNo mail box selected.\" else: get_mail_uid() elif choice == \"7\": create_dir()", "raw_input('\\nWhich email do you want to copy: ') choice_dest = raw_input('To which folder:", "== \"1\": #mark as read recv = imap_uid_store(msg_uid + ' +FLAGS (\\seen)') elif", "start = current_page * email_list_length + 1 end = start + email_list_length -", "= 10 if mail_type == 0: recv = imap_search('ALL') else: recv = imap_uid_search('ALL')", "if current_page < max_pages-1: current_page+=1 elif choice == 'PREV' or choice == 'prev':", "date_opt = \"ON\" if when_ch == \"1\": date_opt = \"BEFORE\" elif when_ch ==", "= recv[pos1:pos2] tmp = r.split(' ') temp_list = [] for t in tmp:", "def imap_search(x): sslSocket.send('A201 SEARCH ' + x + '\\r\\n') recv = recv_all() return", "imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) max_pages = int(len(mail_nums)/email_list_length) if (len(mail_nums)%email_list_length)", "\"1\": delete_all_children_with_child(name, mail_list) cmd = \"all\" else: cmd = \"\" else: cmd =", "contain the /Noselect flag (And) isn't the all mail folder pos = x.find('/\"", "== \"4\": search_text = raw_input(\"Search for text: \") cmd = 'TEXT \"' +", "box\" print \"6: Get mail from selected mail box using unique id\" print", "index = index + 1 print \"---------------------------------\" #Print the mailbox names in a", "of the emails if end == -1:#If the point to stop printing in", "cmd = \"\" else: cmd = name except: cmd = \"\" print \"Checking:", "in temp_list: if x.find('/\" \"') != -1 and x.find('\\Noselect') == -1 and x.find('[Gmail]/All", "= 0 while inc < len(options): print str(inc) + \":\" + options[inc] inc", "Create a mail box\" print \"8: Delete a mail box\" print \"9: Copy", "STORE ' + x + '\\r\\n' sslSocket.send('A003 UID STORE ' + x +", "!= -1 and x.find('\\Noselect') == -1 and x.find('[Gmail]/All Mail') == -1:#The line has", "in a list with additional information def print_mailboxes_list_with_info(mailbox_list, info): print \"\" print \"---------------------------------\"", "mailboxes with optional parameters to change what is listed sslSocket.send('A101 List ' +", "end = start + email_list_length - 1 if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails~", "else: print \"\\nMark as read = 1, Delete = 2, Leave as is", "recv #UID Store def imap_uid_store(x): print 'A003 UID STORE ' + x +", "elif choice == \"8\": delete_dir() elif choice == \"9\": copy_mail() elif choice ==", "receive and it passed the timeout, then stop if data_str and time.time()-begin >", "('imap.163.com', 143) # Create socket called clientSocket and establish a TCP connection with", "from the server try: data = sslSocket.recv(1024) if data: #if there is some", "amtExist = 'N/A' amtRecent = 'N/A' try: amtExist = tmp[17] amtRecent = tmp[19]", "imap_list(dir = \"\", type = \"*\"):#return list of mailboxes with optional parameters to", "sslSocket #set the socket to non-blocking sslSocket.setblocking(0) #array of the data received data_str", "name return mail_list #Print the mailbox names in a list def print_mailboxes_list(mailbox_list): print", "'\\r\\n') recv = recv_all() return recv #Expunge def imap_expunge(): sslSocket.send('A202 EXPUNGE\\r\\n') recv =", "stop elif time.time()-begin > timeout*2: break #try and get the data using a", "\"\\nNo mail box selected.\" else: get_mail_boxnum() elif choice == \"6\": if currentFolder ==", "== search #1 == UID search imap_select(currentFolder) email_list_length = 10 if mail_type ==", "') choice_dest = raw_input('To which folder: ') try: if len(mail_nums)+2 > int(choice) and", "+ x + '\\r\\n') recv = recv_all() return recv #Examine def imap_examine(x): sslSocket.send('A900", "last = index - 5 break return recv[first:last] #Return true if the mail", "= mailbox_string.split('\\r\\n')#Split the returned string by the new line indicators del temp_list[len(temp_list)-1]#The last", "index - 5 break return recv[first:last] #Return true if the mail box has", "+ \" \" + info[index] index = index + 1 print \"---------------------------------\" #Print", "is an empty string, so it isn't needed mail_list = []#Will hold the", "designed for non=blocking sslSocket.setblocking(1) return data_str #Returns a list containing the mailbox names", "== -1 and x.find('[Gmail]/All Mail') == -1:#The line has a mail box (AND)", "or uid number): Subject: This is the email subject def print_mail_list_with_subject(nums, subs, start", "PREV\" choice = raw_input(\"Which email do you want to open? \") if choice", "imap_examine(currentFolder) options = [\"All\", \"Unread\", \"Old\", \"Drafts\", \"Text\", \"Date\"] print \"\\n------------------------------\" print \"Search", "= imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails:' string_list =", "email_read = email_is_read(mail_type, ch)#0 == norm #1 == UID #false = unread true", "socket called clientSocket and establish a TCP connection with mailserver #Fill in start", "time.time()-begin > timeout*2: break #try and get the data using a try/except to", "filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box is empty.\" def copy_mail(): imap_examine(currentFolder) recv", "+ \": \" + str(subs[start-1]) start += 1 #Get how many emails each", "print \"Connected.\\n\" else: print \"Problem connecting.\\n\" ################################# #Done connecting ################################# ################################# #Global Variables", "print \"Deleted\" else: imap_delete(cmd) if recv.find(\"OK Success\") != -1: print \"Deleted \" +", "server) and call it mailserver mailserver = ('imap.163.com', 143) # Create socket called", "search_mail_uid_search() elif choice == \"5\": if currentFolder == \"None\": print \"\\nNo mail box", "if s.find(strg) != -1 and strg != s: return True return False def", "view_mailboxes() elif choice == \"2\": examine_mailbox() elif choice == \"3\": if currentFolder ==", "\"0\": cmd = 'ALL' #unread elif choice == \"1\": cmd = 'UNSEEN' #old", "the string returned from the imap_list command def get_mailbox_list_array(mailbox_string): temp_list = mailbox_string.split('\\r\\n')#Split the", "data using a try/except to catch errors with getting data from the server", "recv.find(\"OK Success\") != -1: print \"Deleted \" + name + \"!\" else: print", "'' #time this method started begin = time.time() #loop till the timeout has", "date = 2)(Since date = 3):\") date_ch = raw_input(\"Date(dd-mm-yyyy)(ex. 1-Sep-2013):\") date_opt = \"ON\"", "recv = imap_uid_search(str(ch) + ' SEEN') pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r", "#loop till the timeout has passed while True: #If some data was receive", "+ name + \"!\" else: print \"Failed to create.\" def delete_dir(): mailbox_string =", "of the list end = len(subs) while start <= len(nums) and start <=", "################################# def imap_login():#login print(\"Login information:\") username = \"<EMAIL>\" password = \"password\" print(\"Attempting to", "\"ON\" if when_ch == \"1\": date_opt = \"BEFORE\" elif when_ch == \"2\": date_opt", "\"Mail box is empty.\" def copy_mail(): imap_examine(currentFolder) recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv)", "= get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) choice = raw_input(\"Which mail box do", "BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid = imap_fetch(str(ch) + \" (UID)\") else: recv_body", "return recv #Fetch def imap_fetch(x): sslSocket.send('A301 FETCH ' + x + '\\r\\n') recv", "then there is probably nothing to get, so stop elif time.time()-begin > timeout*2:", "= 0 else: print \"Mail box is empty.\" again = 0 if len(mail_nums)", "recv_header = imap_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid = imap_fetch(str(ch)", "+ cmd if cmd == \"\": print \"\\nNo Box chosen\" if cmd ==", "choice == \"10\": testing() if choice == \"0\": close_mail() if __name__ == '__main__':", "def print_mailboxes_list(mailbox_list): print \"\" print \"---------------------------------\" print \"Mail Boxes:\" index = 0 while", "close_mail() return 0 choice = \"\" #The main loop while choice != \"0\":", "return 0 choice = \"\" #The main loop while choice != \"0\": print", "parameter is the string returned from the imap_list command def get_mailbox_list_array(mailbox_string): temp_list =", "and all children.(1=yes, 2=no)\") if decision == \"1\": delete_all_children_with_child(name, mail_list) cmd = \"all\"", "def search_mail_search(): search_mail(0) def search_mail_uid_search(): search_mail(1) def search_mail(search_type):#0 == search #1 == UID", "\"\", type = \"*\"):#return list of mailboxes with optional parameters to change what", "recv_all() return recv ################################# #Extra Methods ################################# #Receive using a timeout def recv_all(timeout", "\" + currentFolder else: print \"\\nNot a valid mail box.\" except: print \"\\nNot", "> 0: current_page-=1 else: again = 0 else: print \"Mail box is empty.\"", "def imap_list(dir = \"\", type = \"*\"):#return list of mailboxes with optional parameters", "recv #Expunge def imap_expunge(): sslSocket.send('A202 EXPUNGE\\r\\n') recv = sslSocket.recv(1024) print recv #Select def", "x + '\"\\r\\n') recv = sslSocket.recv(1024) return recv #Delete def imap_delete(x): print 'A501", "is empty.\" again = 0 if len(mail_nums) > 0: try: ch = int(choice)", "raw_input(\"(Before date = 1)(On date = 2)(Since date = 3):\") date_ch = raw_input(\"Date(dd-mm-yyyy)(ex.", "failed!\\n\" return -1 #List def imap_list(dir = \"\", type = \"*\"):#return list of", "imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail", "str(index) + \":\" + mailbox_list[index] index = index + 1 print \"---------------------------------\" #Print", "+ '\"\\r\\n') recv = sslSocket.recv(1024) return recv #Delete def imap_delete(x): print 'A501 DELETE", "for non=blocking sslSocket.setblocking(1) return data_str #Returns a list containing the mailbox names #The", "= string_list[:-1] subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums,", "\"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) return recv #Fetch def imap_fetch(x):", "mail_info_list #Return a string of the numbers returned from the search command def", "if ch_num > len(mail_list): cmd = \"No Box available\" else: name = mail_list[ch_num]", "print \"\\nNot a valid mail box.\" except: print \"\\nNot a valid mail box.\"", "UID FETCH ' + x + '\\r\\n') recv = recv_all() return recv #UID", "if l.find('\\nSubject: ') != -1: tmp = l.find('\\nSubject: ') l = l[tmp:] while", "\"2\": #delete recv = imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print recv imap_expunge() else:", "from the end til it find the A if recv[index] == 'A': last", "else: print \"Failed to create.\" def delete_dir(): mailbox_string = imap_list(\"/\", \"*\") mail_list =", "\"---------------------------------\" print \"Mail Boxes:\" index = 0 while index < len(mailbox_list): print str(index)", "mail box selected.\" else: search_mail_uid_search() elif choice == \"5\": if currentFolder == \"None\":", "current_page-=1 else: again = 0 else: print \"Mail box is empty.\" again =", "Search using message unique id\" print \"5: Get mail from selected mail box\"", "x.find('\\Noselect') == -1 and x.find('[Gmail]/All Mail') == -1:#The line has a mail box", "= recv_all() return recv ################################# #Extra Methods ################################# #Receive using a timeout def", "(\\deleted)') print recv imap_expunge() except: print \"Email not available.\" def create_dir(): name =", "-1: close_mail() return 0 choice = \"\" #The main loop while choice !=", "selected.\" else: search_mail_search() elif choice == \"4\": if currentFolder == \"None\": print \"\\nNo", "elif choice == \"4\": search_text = raw_input(\"Search for text: \") cmd = 'TEXT", "mailbox names in a list def print_mailboxes_list(mailbox_list): print \"\" print \"---------------------------------\" print \"Mail", "mail box selected.\" else: get_mail_uid() elif choice == \"7\": create_dir() elif choice ==", "(box number or uid number): Subject: This is the email subject def print_mail_list_with_subject(nums,", "retrieved and it has passed the timeout by 2, then there is probably", "\"Failed to delete.\" def search_mail_search(): search_mail(0) def search_mail_uid_search(): search_mail(1) def search_mail(search_type):#0 == search", "been retrieved and it has passed the timeout by 2, then there is", "again = 0 else: print \"Mail box is empty.\" again = 0 if", "+ '\"' #date elif choice == \"5\": when_ch = raw_input(\"(Before date = 1)(On", "else: print \"Failed to delete.\" def search_mail_search(): search_mail(0) def search_mail_uid_search(): search_mail(1) def search_mail(search_type):#0", "x + '\"\\r\\n') recv = recv_all() return recv ################################# #Extra Methods ################################# #Receive", "tmp = r.split(' ') temp_list = [] for t in tmp: try: temp_list.append(int(t))", "Box available\" else: name = mail_list[ch_num] if has_children(name, mail_list): decision = raw_input(\"Are you", "else: print \"Mail box is empty.\" again = 0 if len(mail_nums) > 0:", "imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails:' string_list = ''", "#time this method started begin = time.time() #loop till the timeout has passed", "+ ',' if string_list: string_list = string_list[:-1] if search_type == 0: subject_list =", "so stop elif time.time()-begin > timeout*2: break #try and get the data using", "\" BODY[HEADER.FIELDS (SUBJECT)]\") else: subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info =", "def delete_all_children_with_child(strg, mailbox_list): for s in mailbox_list: if s.find(strg) != -1: imap_delete(s) def", "+ x + '\\r\\n' sslSocket.send('A003 UID STORE ' + x + '\\r\\n') recv", "= read print email_read if email_read: print \"\\nMark as unread = 1, Delete", "= socket.socket(socket.AF_INET, socket.SOCK_STREAM) sslSocket.connect(mailserver) recv = sslSocket.recv(1024) if recv.find('OK Gimap ready for requests", "if currentFolder == \"None\": print \"\\nNo mail box selected.\" else: search_mail_uid_search() elif choice", "print \"===============================================================================\\n\" email_read = email_is_read(mail_type, ch)#0 == norm #1 == UID #false =", "mailbox to create:\") recv = imap_create(name) if recv.find(\"OK Success\") != -1: print \"Created", "#Examine def imap_examine(x): sslSocket.send('A900 EXAMINE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024)", "+ options[inc] inc = inc + 1 print \"------------------------------\" choice = raw_input(\"Choice: \")", "################################# #Extra Methods ################################# #Receive using a timeout def recv_all(timeout = 2):#can either", "else: cmd = name except: cmd = \"\" print \"Checking: \" + cmd", "True else: return False ################################# #Mail Client Methods ################################# def view_mailboxes(): mailbox_string =", "def imap_uid_copy(x): sslSocket.send('A300 COPY \"' + x + '\"\\r\\n') recv = recv_all() return", "len(mailbox_list): print str(index) + \":\" + mailbox_list[index] index = index + 1 print", "string of the numbers returned from the search command def get_mail_numbers_from_search(recv): pos1 =", "= recv_uid.find(')') msg_uid = recv_uid[pos:pos2] print \"Email UID: \" + msg_uid pos =", "recv.split(\" \") amtExist = 'N/A' amtRecent = 'N/A' try: amtExist = tmp[17] amtRecent", "\" BODY[1]\") recv_header = imap_uid_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid", "passed the timeout by 2, then there is probably nothing to get, so", "be returned for x in temp_list: if x.find('/\" \"') != -1 and x.find('\\Noselect')", "sslSocket.send('A300 COPY \"' + x + '\"\\r\\n') recv = recv_all() return recv #UID", "print \"7: Create a mail box\" print \"8: Delete a mail box\" print", "again = 1 while again == 1: again = 1 start = current_page", "!= -1:#Find the first } first = recv.find('}') + 3 for index in", "range(len(mail_nums)): string_list += str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] if search_type", "\"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) print recv return recv #UID", "'DRAFT' #text elif choice == \"4\": search_text = raw_input(\"Search for text: \") cmd", "break #try and get the data using a try/except to catch errors with", "== \"1\": date_opt = \"BEFORE\" elif when_ch == \"2\": date_opt = \"ON\" elif", "subs, start = 1, end = -1):#nums = the numbers of the emails,", "choice == \"1\": #mark as read recv = imap_uid_store(msg_uid + ' +FLAGS (\\seen)')", "#mark as read recv = imap_uid_store(msg_uid + ' +FLAGS (\\seen)') elif choice ==", "the default set in the parameter global sslSocket #set the socket to non-blocking", "l.find('\\nSubject: ')+1 pos2 = l.find('\\r') new = l[pos1:pos2] if new != '': li.append(new)", "recv_all() return recv #Expunge def imap_expunge(): sslSocket.send('A202 EXPUNGE\\r\\n') recv = sslSocket.recv(1024) print recv", "you want to open? \") if choice == 'NEXT' or choice == 'next':", "string_list += str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] if mail_type ==", "raw_input(\"Enter the number for the box to delete: \") try: ch_num = int(choice)", "print '\\n-------------------------------\\nEmails~ Page: ' + str(current_page+1) + '/' + str(max_pages) print_mail_list_with_subject(mail_nums, mailboxes_info, start,", "search_text + '\"' #date elif choice == \"5\": when_ch = raw_input(\"(Before date =", "then store that data data_str += data begin=time.time()#reset the begin time so that", "email_is_read(mail_type, ch)#0 == norm #1 == UID #false = unread true = read", "== \"5\": when_ch = raw_input(\"(Before date = 1)(On date = 2)(Since date =", "\") try: if int(choice) < len(mail_list): currentFolder = mail_list[int(choice)] print \"\\nSelected \" +", "\"---------------------------------\" #Print the mailbox names in a list with additional information def print_mailboxes_list_with_info(mailbox_list,", "#sslSocket = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), #ssl_version = ssl.PROTOCOL_SSLv23) sslSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sslSocket.connect(mailserver) recv", "sslSocket.send('A501 DELETE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) print recv return", "= unread true = read print email_read if email_read: print \"\\nMark as unread", "mail box do you want to open: \") try: if int(choice) < len(mail_list):", "if cmd == \"all\": print \"Deleted\" else: imap_delete(cmd) if recv.find(\"OK Success\") != -1:", "new = l[pos1:pos2] if new != '': li.append(new) l = l[pos2+1:] return li", "if choice == \"1\": #mark as unread recv = imap_uid_store(msg_uid + ' -FLAGS", "#Receive using a timeout def recv_all(timeout = 2):#can either pass a different timeout", "subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) max_pages = int(len(mail_nums)/email_list_length)", "\"\\nMark as unread = 1, Delete = 2, Leave as is = 3\"", "currentFolder mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) choice", "mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) def examine_mailbox(): global currentFolder mailbox_string", "\"\\\"\\\"\" +' '+ type + '\\r\\n') recv = recv_all() return recv #Search def", "' + x + '\\r\\n') recv = recv_all() return recv #UID Store def", "Search selected mail box\" print \"4: Search using message unique id\" print \"5:", "view more mail type, NEXT or PREV\" choice = raw_input(\"Which email do you", "imap_uid_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid = imap_uid_fetch(str(ch) + \"", "= index + 1 print \"---------------------------------\" #Print the email list in the format", "do you want to copy: ') choice_dest = raw_input('To which folder: ') try:", "\"8: Delete a mail box\" print \"9: Copy email from selected mail box", "get_mail_numbers_from_search(recv) if len(mail_nums) > 0: string_list = '' for x in range(len(mail_nums)): string_list", "'ALL' #unread elif choice == \"1\": cmd = 'UNSEEN' #old elif choice ==", "+ choice_dest) else: print \"Not a valid email.\" except: print \"Invalid input.\" def", "#Global Variables ################################# currentFolder = \"None\" #Stores the currently selected mail box #################################", "s.find(strg) != -1: imap_delete(s) def filter_list_of_subjects(l): li = [] if l.find('\\nSubject: ') !=", "selected.\" else: get_mail_boxnum() elif choice == \"6\": if currentFolder == \"None\": print \"\\nNo", "pass #just let it reloop if there was an error thrown #set the", "\"Checking: \" + cmd if cmd == \"\": print \"\\nNo Box chosen\" if", "get_mailbox_list_array(mailbox_string) print_mailboxes_list(mail_list) choice = raw_input(\"Enter the number for the box to delete: \")", "choice = raw_input(\"Which email do you want to open? \") if choice ==", "\" + info[index] index = index + 1 print \"---------------------------------\" #Print the email", "+ x + '\\r\\n') recv = recv_all() return recv #UID Store def imap_uid_store(x):", "print \"Login failed!\\n\" return -1 #List def imap_list(dir = \"\", type = \"*\"):#return", "listed sslSocket.send('A101 List ' + \"\\\"\\\"\" +' '+ type + '\\r\\n') recv =", "first } first = recv.find('}') + 3 for index in reversed(range(len(recv))): #Loop from", "= '' if mail_type == 0: recv = imap_search(str(ch) + ' SEEN') else:", "inc < len(options): print str(inc) + \":\" + options[inc] inc = inc +", "\" + name + \"!\" else: print \"Failed to create.\" def delete_dir(): mailbox_string", "elif choice == \"5\": when_ch = raw_input(\"(Before date = 1)(On date = 2)(Since", "the numbers of the emails, subs = the subjects of the emails if", "elements of the lists print str(nums[start-1]) + \": \" + str(subs[start-1]) start +=", "else: print \"Mail box is empty.\" def copy_mail(): imap_examine(currentFolder) recv = imap_uid_search('ALL') mail_nums", "timeout while still getting data else: time.sleep(0.1)#give a slight pause before trying to", "mailbox_list): for s in mailbox_list: if s.find(strg) != -1: imap_delete(s) def filter_list_of_subjects(l): li", "recv_all() return recv #Search def imap_search(x): sslSocket.send('A201 SEARCH ' + x + '\\r\\n')", "== norm #1 == UID #false = unread true = read print email_read", "in to: \" + username + \"\\n\" return 1 else: print \"Login failed!\\n\"", "uid number): Subject: This is the email subject def print_mail_list_with_subject(nums, subs, start =", "if mail_type == 0: recv = imap_search('ALL') else: recv = imap_uid_search('ALL') mail_nums =", "'': li.append(new) l = l[pos2+1:] return li def email_is_read(mail_type, ch):#0 == norm #1", "= imap_search(str(ch) + ' SEEN') else: recv = imap_uid_search(str(ch) + ' SEEN') pos1", "the list of mailbox names to be returned for x in temp_list: if", "return True else: return False ################################# #Mail Client Methods ################################# def view_mailboxes(): mailbox_string", "search_mail(0) def search_mail_uid_search(): search_mail(1) def search_mail(search_type):#0 == search #1 == UID search imap_examine(currentFolder)", "0: recv_body = imap_fetch(str(ch) + \" BODY[1]\") recv_header = imap_fetch(str(ch) + \" BODY[HEADER.FIELDS", "socket.SOCK_STREAM), #ssl_version = ssl.PROTOCOL_SSLv23) sslSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sslSocket.connect(mailserver) recv = sslSocket.recv(1024) if", "' + password + '\\r\\n') recv = sslSocket.recv(1024) if recv.find(\"completed\") != -1: print", "mail_type == 0: recv = imap_search('ALL') else: recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv)", "another\" choice = raw_input(\"Choice: \") if choice == \"1\": view_mailboxes() elif choice ==", "imap_uid_search(str(ch) + ' SEEN') pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2]", "except: pass mail_info_list.append('(Emails: ' + amtExist + ' Recent: ' + amtRecent +", "#Print the email list in the format (box number or uid number): Subject:", "it find the A if recv[index] == 'A': last = index - 5", "def has_children(strg, mailbox_list): for s in mailbox_list: if s.find(strg) != -1 and strg", "= filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box is empty.\" choice = raw_input('\\nWhich", "0: recv = imap_search('ALL') else: recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) string_list =", "ch_num = int(choice) if ch_num > len(mail_list): cmd = \"No Box available\" else:", "== \"2\": #delete recv = imap_uid_store(msg_uid + ' +FLAGS (\\deleted)') print recv imap_expunge()", "socket back to blocking since only this method is designed for non=blocking sslSocket.setblocking(1)", "type, NEXT or PREV\" choice = raw_input(\"Which email do you want to open?", "imap_examine(currentFolder) recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails:'", "sslSocket.close() #close the socket print \"Done.\" #Main Method def main(): log_success = imap_login()", "recv.find('OK Gimap ready for requests from') != -1: print \"Connected.\\n\" else: print \"Problem", "\"password\" print(\"Attempting to login.\\n\") sslSocket.send('A001 LOGIN ' + username + ' ' +", "if recv[index] == 'A': last = index - 5 break return recv[first:last] #Return", "mailbox_list): for s in mailbox_list: if s.find(strg) != -1 and strg != s:", "True: #If some data was receive and it passed the timeout, then stop", "Leave as is = 3\" choice = raw_input(\"Choice: \") if choice == \"1\":", "def imap_fetch(x): sslSocket.send('A301 FETCH ' + x + '\\r\\n') recv = recv_all() return", "delete: \") try: ch_num = int(choice) if ch_num > len(mail_list): cmd = \"No", "= 'UNSEEN' #old elif choice == \"2\": cmd = 'OLD' #drafts elif choice", "recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) string_list = '' for x in range(len(mail_nums)):", "create.\" def delete_dir(): mailbox_string = imap_list(\"/\", \"*\") mail_list = get_mailbox_list_array(mailbox_string) print_mailboxes_list(mail_list) choice =", "= imap_search(cmd) else: recv = imap_uid_search(cmd) mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0:", "the formated string to the list return mail_info_list #Return a string of the", "\") if choice == \"1\": #mark as read recv = imap_uid_store(msg_uid + '", "mail box ################################# #imap Methods ################################# def imap_login():#login print(\"Login information:\") username = \"<EMAIL>\"", "FROM TO)]\") recv_uid = imap_fetch(str(ch) + \" (UID)\") else: recv_body = imap_uid_fetch(str(ch) +", "LOGIN ' + username + ' ' + password + '\\r\\n') recv =", "that was received then store that data data_str += data begin=time.time()#reset the begin", "timeout by 2, then there is probably nothing to get, so stop elif", "inc = 0 while inc < len(options): print str(inc) + \":\" + options[inc]", "print \"3: Search selected mail box\" print \"4: Search using message unique id\"", "then stop if data_str and time.time()-begin > timeout: break #If no data has", "#set the socket back to blocking since only this method is designed for", "and start <= end:#Print the specified elements of the lists print str(nums[start-1]) +", "available\" else: name = mail_list[ch_num] if has_children(name, mail_list): decision = raw_input(\"Are you sure", "Subject: This is the email subject def print_mail_list_with_subject(nums, subs, start = 1, end", "elif choice == \"3\": cmd = 'DRAFT' #text elif choice == \"4\": search_text", "email body def format_email_body(recv): first = 0 last = len(recv)-1 if recv.find('}') !=", "recv imap_expunge() else: print \"\\nMark as read = 1, Delete = 2, Leave", "pos = recv_uid.find('(UID')+5 pos2 = recv_uid.find(')') msg_uid = recv_uid[pos:pos2] print \"Email UID: \"", "of the emails, subs = the subjects of the emails if end ==", "empty.\" again = 0 if len(mail_nums) > 0: try: ch = int(choice) if", "get_mail(1) def get_mail(mail_type):#0 == search #1 == UID search imap_select(currentFolder) email_list_length = 10", "#UID Store def imap_uid_store(x): print 'A003 UID STORE ' + x + '\\r\\n'", "imap_uid_fetch(x): sslSocket.send('A999 UID FETCH ' + x + '\\r\\n') recv = recv_all() return", "= sslSocket.recv(1024) return recv #Fetch def imap_fetch(x): sslSocket.send('A301 FETCH ' + x +", "+ ' ' + choice_dest) else: print \"Not a valid email.\" except: print", "= 3\" choice = raw_input(\"Choice: \") if choice == \"1\": #mark as unread", "0: current_page-=1 else: again = 0 else: print \"Mail box is empty.\" again", "UID STORE ' + x + '\\r\\n' sslSocket.send('A003 UID STORE ' + x", "\"\\nSelected \" + currentFolder else: print \"\\nNot a valid mail box.\" except: print", "has_children(name, mail_list): decision = raw_input(\"Are you sure you want to delete \" +", "\"3: Search selected mail box\" print \"4: Search using message unique id\" print", "def close_mail(): sslSocket.close() #close the socket print \"Done.\" #Main Method def main(): log_success", "return recv #Expunge def imap_expunge(): sslSocket.send('A202 EXPUNGE\\r\\n') recv = sslSocket.recv(1024) print recv #Select", "mail box has child boxes def has_children(strg, mailbox_list): for s in mailbox_list: if", "to delete \" + name + \" and all children.(1=yes, 2=no)\") if decision", "this method is designed for non=blocking sslSocket.setblocking(1) return data_str #Returns a list containing", "+= str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] if search_type == 0:", "while inc < len(options): print str(inc) + \":\" + options[inc] inc = inc", "email.\" except: print \"Invalid input.\" def testing(): imap_expunge() #Done running def close_mail(): sslSocket.close()", "returned from the search command def get_mail_numbers_from_search(recv): pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r')", "\"4\": search_text = raw_input(\"Search for text: \") cmd = 'TEXT \"' + search_text", "return recv #Examine def imap_examine(x): sslSocket.send('A900 EXAMINE \"' + x + '\"\\r\\n') recv", "tmp: try: temp_list.append(int(t)) except: pass return temp_list #Return the text of the email", "= \"\", type = \"*\"):#return list of mailboxes with optional parameters to change", "Recent: ' + amtRecent + ')')#Add the formated string to the list return", "l.find('\\nSubject: ') != -1: tmp = l.find('\\nSubject: ') l = l[tmp:] while l.find('\\nSubject:", "\"Date\"] print \"\\n------------------------------\" print \"Search by:\" inc = 0 while inc < len(options):", "> 0: print '\\n-------------------------------\\nEmails~ Page: ' + str(current_page+1) + '/' + str(max_pages) print_mail_list_with_subject(mail_nums,", "recv #Select def imap_select(x): sslSocket.send('A142 SELECT \"' + x + '\"\\r\\n') recv =", "mailboxes_info) else: print \"Mail box is empty.\" def copy_mail(): imap_examine(currentFolder) recv = imap_uid_search('ALL')", "else: print \"Mail box is empty.\" choice = raw_input('\\nWhich email do you want", "== 'prev': again = 1 if current_page > 0: current_page-=1 else: again =", "email_is_read(mail_type, ch):#0 == norm #1 == UID recv = '' if mail_type ==", "x + '\"\\r\\n' sslSocket.send('A501 DELETE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024)", "if string_list: string_list = string_list[:-1] if mail_type == 0: subject_list = imap_fetch(string_list +", "mail_list[int(choice)] print \"\\nSelected \" + currentFolder else: print \"\\nNot a valid mail box.\"", "#Search def imap_search(x): sslSocket.send('A201 SEARCH ' + x + '\\r\\n') recv = recv_all()", "if current_page > 0: current_page-=1 else: again = 0 else: print \"Mail box", "== 0: subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") else: subject_list = imap_uid_fetch(string_list", "print \"\\nSelected \" + currentFolder else: print \"\\nNot a valid mail box.\" except:", "format_email_body(recv_body) print \"===============================================================================\\n\" email_read = email_is_read(mail_type, ch)#0 == norm #1 == UID #false", "print str(index) + \":\" + mailbox_list[index] + \" \" + info[index] index =", "= recv_header.find('OK Success\\r\\n')-11 print recv_header[pos:pos2] print \"--------------------------------------------------------------------\" print format_email_body(recv_body) print \"===============================================================================\\n\" email_read =", "cmd = date_opt + ' ' + date_ch if search_type == 0: recv", "> 0: print imap_uid_copy(choice + ' ' + choice_dest) else: print \"Not a", "get_mail_uid(): get_mail(1) def get_mail(mail_type):#0 == search #1 == UID search imap_select(currentFolder) email_list_length =", "if there was an error thrown #set the socket back to blocking since", "string_list = '' for x in range(len(mail_nums)): string_list += str(mail_nums[x]) + ',' if", "1 if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails~ Page: ' + str(current_page+1) + '/'", "Google mail server) and call it mailserver mailserver = ('imap.163.com', 143) # Create", "'\\r\\n') recv = recv_all() return recv #Create def imap_create(x): sslSocket.send('A401 CREATE \"' +", "delete.\" def search_mail_search(): search_mail(0) def search_mail_uid_search(): search_mail(1) def search_mail(search_type):#0 == search #1 ==", "copy_mail(): imap_examine(currentFolder) recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0: print", "range(len(mail_nums)): string_list += str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] if mail_type", "#Expunge def imap_expunge(): sslSocket.send('A202 EXPUNGE\\r\\n') recv = sslSocket.recv(1024) print recv #Select def imap_select(x):", "while True: #If some data was receive and it passed the timeout, then", "the email subject def print_mail_list_with_subject(nums, subs, start = 1, end = -1):#nums =", "sys, time, math print \"Connecting..\" username = \"\" password = \"\" # Choose", "selected mail box\" print \"6: Get mail from selected mail box using unique", "-1):#nums = the numbers of the emails, subs = the subjects of the", "list def print_mailboxes_list(mailbox_list): print \"\" print \"---------------------------------\" print \"Mail Boxes:\" index = 0", "data_str = '' #time this method started begin = time.time() #loop till the", "List ' + \"\\\"\\\"\" +' '+ type + '\\r\\n') recv = recv_all() return", "def print_mail_list_with_subject(nums, subs, start = 1, end = -1):#nums = the numbers of", "#Return the text of the email body def format_email_body(recv): first = 0 last", "of info for the emails for x in mail_list: recv = imap_examine(x) tmp", "chosen\" if cmd == \"all\": print \"Deleted\" else: imap_delete(cmd) if recv.find(\"OK Success\") !=", "received then store that data data_str += data begin=time.time()#reset the begin time so", "mail from selected mail box using unique id\" print \"7: Create a mail", "def copy_mail(): imap_examine(currentFolder) recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0:", "-1 and strg != s: return True return False def delete_all_children_with_child(strg, mailbox_list): for", "################################# ################################# #Global Variables ################################# currentFolder = \"None\" #Stores the currently selected mail", "input.\" def testing(): imap_expunge() #Done running def close_mail(): sslSocket.close() #close the socket print", "Gimap ready for requests from') != -1: print \"Connected.\\n\" else: print \"Problem connecting.\\n\"", "= \"BEFORE\" elif when_ch == \"2\": date_opt = \"ON\" elif when_ch == \"3\":", "l = l[pos2+1:] return li def email_is_read(mail_type, ch):#0 == norm #1 == UID", "= 'DRAFT' #text elif choice == \"4\": search_text = raw_input(\"Search for text: \")", "sslSocket.send('A001 LOGIN ' + username + ' ' + password + '\\r\\n') recv", "choice == \"3\": if currentFolder == \"None\": print \"\\nNo mail box selected.\" else:", "def get_mail(mail_type):#0 == search #1 == UID search imap_select(currentFolder) email_list_length = 10 if", "-1:#If the point to stop printing in the list wasn't specified in the", "selected.\" else: search_mail_uid_search() elif choice == \"5\": if currentFolder == \"None\": print \"\\nNo", "0: recv = imap_search(cmd) else: recv = imap_uid_search(cmd) mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums)", "if data_str and time.time()-begin > timeout: break #If no data has been retrieved", "was an error thrown #set the socket back to blocking since only this", "\"\\nTo view more mail type, NEXT or PREV\" choice = raw_input(\"Which email do", "= int(choice) if ch_num > len(mail_list): cmd = \"No Box available\" else: name", "index + 1 print \"---------------------------------\" #Print the mailbox names in a list with", "'\\r\\n' sslSocket.send('A003 UID STORE ' + x + '\\r\\n') recv = sslSocket.recv(1024) print", "\") amtExist = 'N/A' amtRecent = 'N/A' try: amtExist = tmp[17] amtRecent =", "x.find('/\" \"') != -1 and x.find('\\Noselect') == -1 and x.find('[Gmail]/All Mail') == -1:#The", "and time.time()-begin > timeout: break #If no data has been retrieved and it", "a try/except to catch errors with getting data from the server try: data", "= 1 start = current_page * email_list_length + 1 end = start +", "substring of the line containing the mailbox name return mail_list #Print the mailbox", "timeout or use the default set in the parameter global sslSocket #set the", "UID STORE ' + x + '\\r\\n') recv = sslSocket.recv(1024) print recv return", "data has been retrieved and it has passed the timeout by 2, then", "print \"Email not available.\" def create_dir(): name = raw_input(\"\\nName of new mailbox to", "'prev': again = 1 if current_page > 0: current_page-=1 else: again = 0", "selected mail box using unique id\" print \"7: Create a mail box\" print", "logged in to: \" + username + \"\\n\" return 1 else: print \"Login", "if currentFolder == \"None\": print \"\\nNo mail box selected.\" else: search_mail_search() elif choice", "== \"8\": delete_dir() elif choice == \"9\": copy_mail() elif choice == \"10\": testing()", "the point to stop printing in the list wasn't specified in the params,", "by the new line indicators del temp_list[len(temp_list)-1]#The last element is an empty string,", "search command def get_mail_numbers_from_search(recv): pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2]", "= imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) def examine_mailbox(): global", "#UID Fetch def imap_uid_fetch(x): sslSocket.send('A999 UID FETCH ' + x + '\\r\\n') recv", "SEEN') pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2] if r !=", "sslSocket.send('A201 SEARCH ' + x + '\\r\\n') recv = recv_all() return recv #Examine", "till the timeout has passed while True: #If some data was receive and", "1: again = 1 start = current_page * email_list_length + 1 end =", "the imap_list command def get_mailbox_list_array(mailbox_string): temp_list = mailbox_string.split('\\r\\n')#Split the returned string by the", "break return recv[first:last] #Return true if the mail box has child boxes def", "main loop while choice != \"0\": print \"\\n\" print \"---------------------------------------------\" print \"-- Currently", "socket, ssl, base64, sys, time, math print \"Connecting..\" username = \"\" password =", "has_children(strg, mailbox_list): for s in mailbox_list: if s.find(strg) != -1 and strg !=", "quit.)\" print \"1: View all mail boxes\" print \"2: Examine a mail box\"", "== 'next': again = 1 if current_page < max_pages-1: current_page+=1 elif choice ==", "there is some data that was received then store that data data_str +=", "current_page > 0: current_page-=1 else: again = 0 else: print \"Mail box is", "#Store the substring of the line containing the mailbox name return mail_list #Print", "for x in mail_list: recv = imap_examine(x) tmp = recv.split(\" \") amtExist =", "int(choice) and int(choice) > 0: print imap_uid_copy(choice + ' ' + choice_dest) else:", "recv_all() return recv #Examine def imap_examine(x): sslSocket.send('A900 EXAMINE \"' + x + '\"\\r\\n')", "BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) max_pages = int(len(mail_nums)/email_list_length) if (len(mail_nums)%email_list_length) > 0: max_pages", "= raw_input(\"Choice: \") cmd = \"\" #all if choice == \"0\": cmd =", "from the imap_list command def get_mailbox_list_array(mailbox_string): temp_list = mailbox_string.split('\\r\\n')#Split the returned string by", "while start <= len(nums) and start <= end:#Print the specified elements of the", "+ '\\r\\n' sslSocket.send('A003 UID STORE ' + x + '\\r\\n') recv = sslSocket.recv(1024)", "data begin=time.time()#reset the begin time so that it doesn't timeout while still getting", "def imap_delete(x): print 'A501 DELETE \"' + x + '\"\\r\\n' sslSocket.send('A501 DELETE \"'", "return recv ################################# #Extra Methods ################################# #Receive using a timeout def recv_all(timeout =", "more mail type, NEXT or PREV\" choice = raw_input(\"Which email do you want", "mail box to another\" choice = raw_input(\"Choice: \") if choice == \"1\": view_mailboxes()", "#Done running def close_mail(): sslSocket.close() #close the socket print \"Done.\" #Main Method def", "the timeout has passed while True: #If some data was receive and it", "flag (And) isn't the all mail folder pos = x.find('/\" \"')+4 mail_list.append(x[pos:-1]) #Store", "true if the mail box has child boxes def has_children(strg, mailbox_list): for s", "Copy def imap_uid_copy(x): sslSocket.send('A300 COPY \"' + x + '\"\\r\\n') recv = recv_all()", "+ \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) max_pages = int(len(mail_nums)/email_list_length) if (len(mail_nums)%email_list_length) >", "def email_is_read(mail_type, ch):#0 == norm #1 == UID recv = '' if mail_type", "print \"\\n------------------------------\" print \"Search by:\" inc = 0 while inc < len(options): print", "1-Sep-2013):\") date_opt = \"ON\" if when_ch == \"1\": date_opt = \"BEFORE\" elif when_ch", "imap_uid_search(cmd) mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0: string_list = '' for x", "+ username + \"\\n\" return 1 else: print \"Login failed!\\n\" return -1 #List", "} first = recv.find('}') + 3 for index in reversed(range(len(recv))): #Loop from the", "subs = the subjects of the emails if end == -1:#If the point", "return recv[first:last] #Return true if the mail box has child boxes def has_children(strg,", "\"' + x + '\"\\r\\n') recv = recv_all() return recv ################################# #Extra Methods", "want to copy: ') choice_dest = raw_input('To which folder: ') try: if len(mail_nums)+2", "child boxes def has_children(strg, mailbox_list): for s in mailbox_list: if s.find(strg) != -1", "0 last = len(recv)-1 if recv.find('}') != -1:#Find the first } first =", "= 1 if current_page < max_pages-1: current_page+=1 elif choice == 'PREV' or choice", "print str(inc) + \":\" + options[inc] inc = inc + 1 print \"------------------------------\"", "get_mail(0) def get_mail_uid(): get_mail(1) def get_mail(mail_type):#0 == search #1 == UID search imap_select(currentFolder)", "folder: ') try: if len(mail_nums)+2 > int(choice) and int(choice) > 0: print imap_uid_copy(choice", "else: print \"Problem connecting.\\n\" ################################# #Done connecting ################################# ################################# #Global Variables ################################# currentFolder", "print \"---------------------------------------------\" print \"What would you like to do? (0 to quit.)\" print", "\"\" password = \"\" # Choose a mail server (e.g. Google mail server)", "= the numbers of the emails, subs = the subjects of the emails", "for requests from') != -1: print \"Connected.\\n\" else: print \"Problem connecting.\\n\" ################################# #Done", "recv.find('\\r') r = recv[pos1:pos2] tmp = r.split(' ') temp_list = [] for t", "it reloop if there was an error thrown #set the socket back to", "#Fetch def imap_fetch(x): sslSocket.send('A301 FETCH ' + x + '\\r\\n') recv = recv_all()", "imap_examine(x): sslSocket.send('A900 EXAMINE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) return recv", "the text of the email body def format_email_body(recv): first = 0 last =", "except: print \"\\nNot a valid mail box.\" def get_mail_boxnum(): get_mail(0) def get_mail_uid(): get_mail(1)", "returned from the imap_list command def get_mailbox_list_array(mailbox_string): temp_list = mailbox_string.split('\\r\\n')#Split the returned string", "recv[pos1:pos2] if r != '': return True else: return False ################################# #Mail Client", "print \"\\nTo view more mail type, NEXT or PREV\" choice = raw_input(\"Which email", "an error thrown #set the socket back to blocking since only this method", "again = 1 if current_page < max_pages-1: current_page+=1 elif choice == 'PREV' or", "get the data using a try/except to catch errors with getting data from", "imap_fetch(x): sslSocket.send('A301 FETCH ' + x + '\\r\\n') recv = recv_all() return recv", "box selected.\" else: search_mail_uid_search() elif choice == \"5\": if currentFolder == \"None\": print", "+= data begin=time.time()#reset the begin time so that it doesn't timeout while still", "\"SINCE\" cmd = date_opt + ' ' + date_ch if search_type == 0:", "print_mail_list_with_subject(nums, subs, start = 1, end = -1):#nums = the numbers of the", "1)(On date = 2)(Since date = 3):\") date_ch = raw_input(\"Date(dd-mm-yyyy)(ex. 1-Sep-2013):\") date_opt =", "mail box\" print \"8: Delete a mail box\" print \"9: Copy email from", "a valid mail box.\" except: print \"\\nNot a valid mail box.\" def get_mail_boxnum():", "mail_info_list.append('(Emails: ' + amtExist + ' Recent: ' + amtRecent + ')')#Add the", "Search def imap_uid_search(x): sslSocket.send('A999 UID SEARCH ' + x + '\\r\\n') recv =", "+ 1 print \"---------------------------------\" #Print the email list in the format (box number", "'N/A' try: amtExist = tmp[17] amtRecent = tmp[19] except: pass mail_info_list.append('(Emails: ' +", "currentFolder = mail_list[int(choice)] print \"\\nSelected \" + currentFolder else: print \"\\nNot a valid", "= tmp[19] except: pass mail_info_list.append('(Emails: ' + amtExist + ' Recent: ' +", "#UID Copy def imap_uid_copy(x): sslSocket.send('A300 COPY \"' + x + '\"\\r\\n') recv =", "import socket, ssl, base64, sys, time, math print \"Connecting..\" username = \"\" password", "#if there is some data that was received then store that data data_str", "= recv_all() return recv #Search def imap_search(x): sslSocket.send('A201 SEARCH ' + x +", "= filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box is empty.\" def copy_mail(): imap_examine(currentFolder)", "'PREV' or choice == 'prev': again = 1 if current_page > 0: current_page-=1", "and establish a TCP connection with mailserver #Fill in start #sslSocket = ssl.wrap_socket(socket.socket(socket.AF_INET,", "is empty.\" def copy_mail(): imap_examine(currentFolder) recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums)", "'\\r\\n') recv = recv_all() return recv #Examine def imap_examine(x): sslSocket.send('A900 EXAMINE \"' +", "################################# #Global Variables ################################# currentFolder = \"None\" #Stores the currently selected mail box", "box selected.\" else: search_mail_search() elif choice == \"4\": if currentFolder == \"None\": print", "list containing the mailbox names #The parameter is the string returned from the", "list of info for the emails for x in mail_list: recv = imap_examine(x)", "sslSocket.send('A999 UID FETCH ' + x + '\\r\\n') recv = recv_all() return recv", "+ search_text + '\"' #date elif choice == \"5\": when_ch = raw_input(\"(Before date", "except: print \"Invalid input.\" def testing(): imap_expunge() #Done running def close_mail(): sslSocket.close() #close", "else: search_mail_search() elif choice == \"4\": if currentFolder == \"None\": print \"\\nNo mail", "str(index) + \":\" + mailbox_list[index] + \" \" + info[index] index = index", "data_str #Returns a list containing the mailbox names #The parameter is the string", "Get mail from selected mail box using unique id\" print \"7: Create a", "' +FLAGS (\\deleted)') print recv imap_expunge() else: print \"\\nMark as read = 1,", "mail folder pos = x.find('/\" \"')+4 mail_list.append(x[pos:-1]) #Store the substring of the line", "\"' + x + '\"\\r\\n' sslSocket.send('A501 DELETE \"' + x + '\"\\r\\n') recv", "\"all\": print \"Deleted\" else: imap_delete(cmd) if recv.find(\"OK Success\") != -1: print \"Deleted \"", "when_ch == \"1\": date_opt = \"BEFORE\" elif when_ch == \"2\": date_opt = \"ON\"", "time.time()-begin > timeout: break #If no data has been retrieved and it has", "to be returned for x in temp_list: if x.find('/\" \"') != -1 and", "+ mailbox_list[index] index = index + 1 print \"---------------------------------\" #Print the mailbox names", "= imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list) print_mailboxes_list_with_info(mail_list, mailboxes_info) choice = raw_input(\"Which", "in mailbox_list: if s.find(strg) != -1: imap_delete(s) def filter_list_of_subjects(l): li = [] if", "recv_uid.find('(UID')+5 pos2 = recv_uid.find(')') msg_uid = recv_uid[pos:pos2] print \"Email UID: \" + msg_uid", "norm #1 == UID #false = unread true = read print email_read if", "= 0 last = len(recv)-1 if recv.find('}') != -1:#Find the first } first", "cmd = \"\" #all if choice == \"0\": cmd = 'ALL' #unread elif", "create_dir() elif choice == \"8\": delete_dir() elif choice == \"9\": copy_mail() elif choice", "l[tmp:] while l.find('\\nSubject: ') != -1: pos1 = l.find('\\nSubject: ')+1 pos2 = l.find('\\r')", "choice = raw_input(\"Choice: \") if choice == \"1\": #mark as unread recv =", "0 choice = \"\" #The main loop while choice != \"0\": print \"\\n\"", "mail box\" print \"4: Search using message unique id\" print \"5: Get mail", "get_mail_uid() elif choice == \"7\": create_dir() elif choice == \"8\": delete_dir() elif choice", "+= str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] if mail_type == 0:", "doesn't contain the /Noselect flag (And) isn't the all mail folder pos =", "norm #1 == UID recv = '' if mail_type == 0: recv =", "getting data from the server try: data = sslSocket.recv(1024) if data: #if there", "') != -1: tmp = l.find('\\nSubject: ') l = l[tmp:] while l.find('\\nSubject: ')", "10 if mail_type == 0: recv = imap_search('ALL') else: recv = imap_uid_search('ALL') mail_nums", "+ ' SEEN') pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2] if", "string_list: string_list = string_list[:-1] if mail_type == 0: subject_list = imap_fetch(string_list + \"", "return li def email_is_read(mail_type, ch):#0 == norm #1 == UID recv = ''", "+ \" BODY[1]\") recv_header = imap_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\")", "(SUBJECT)]\") else: subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums,", "(And) isn't the all mail folder pos = x.find('/\" \"')+4 mail_list.append(x[pos:-1]) #Store the", "how many emails each mailbox contains def get_mailboxes_info_array(mail_list): mail_info_list = [] #Holds the", "DELETE \"' + x + '\"\\r\\n') recv = sslSocket.recv(1024) print recv return recv", "print \"\\nNo mail box selected.\" else: search_mail_uid_search() elif choice == \"5\": if currentFolder", "the mailbox name return mail_list #Print the mailbox names in a list def", "l.find('\\r') new = l[pos1:pos2] if new != '': li.append(new) l = l[pos2+1:] return", "0: print imap_uid_copy(choice + ' ' + choice_dest) else: print \"Not a valid", "\"\" #all if choice == \"0\": cmd = 'ALL' #unread elif choice ==", "except: print \"Email not available.\" def create_dir(): name = raw_input(\"\\nName of new mailbox", "print_mailboxes_list_with_info(mail_list, mailboxes_info) choice = raw_input(\"Which mail box do you want to open: \")", "blocking since only this method is designed for non=blocking sslSocket.setblocking(1) return data_str #Returns", "needed mail_list = []#Will hold the list of mailbox names to be returned", "as unread = 1, Delete = 2, Leave as is = 3\" choice", "def imap_login():#login print(\"Login information:\") username = \"<EMAIL>\" password = \"password\" print(\"Attempting to login.\\n\")", "'\\r\\n') recv = sslSocket.recv(1024) if recv.find(\"completed\") != -1: print \"Successfully logged in to:", "want to delete \" + name + \" and all children.(1=yes, 2=no)\") if", "+ x + '\\r\\n') recv = recv_all() return recv #Expunge def imap_expunge(): sslSocket.send('A202", "\":\" + mailbox_list[index] + \" \" + info[index] index = index + 1", "end == -1:#If the point to stop printing in the list wasn't specified", "the new line indicators del temp_list[len(temp_list)-1]#The last element is an empty string, so", "imap_uid_copy(choice + ' ' + choice_dest) else: print \"Not a valid email.\" except:", "the format (box number or uid number): Subject: This is the email subject", "return data_str #Returns a list containing the mailbox names #The parameter is the", "= recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2] tmp = r.split(' ') temp_list", "mailboxes_info) else: print \"Mail box is empty.\" choice = raw_input('\\nWhich email do you", "started begin = time.time() #loop till the timeout has passed while True: #If", "= recv_all() return recv #Examine def imap_examine(x): sslSocket.send('A900 EXAMINE \"' + x +", "' SEEN') pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r') r = recv[pos1:pos2] if r", "print \"Email UID: \" + msg_uid pos = recv_header.find(\"Date: \") pos2 = recv_header.find('OK", "= 1, Delete = 2, Leave as is = 3\" choice = raw_input(\"Choice:", "ch_num > len(mail_list): cmd = \"No Box available\" else: name = mail_list[ch_num] if", "len(mail_list): cmd = \"No Box available\" else: name = mail_list[ch_num] if has_children(name, mail_list):", "mailbox names in a list with additional information def print_mailboxes_list_with_info(mailbox_list, info): print \"\"", "\"9: Copy email from selected mail box to another\" choice = raw_input(\"Choice: \")", "sslSocket.recv(1024) if data: #if there is some data that was received then store", "elif when_ch == \"3\": date_opt = \"SINCE\" cmd = date_opt + ' '", "' + x + '\\r\\n') recv = recv_all() return recv #Expunge def imap_expunge():", "using a try/except to catch errors with getting data from the server try:", "def testing(): imap_expunge() #Done running def close_mail(): sslSocket.close() #close the socket print \"Done.\"", "= sslSocket.recv(1024) print recv return recv #UID Search def imap_uid_search(x): sslSocket.send('A999 UID SEARCH", "examine_mailbox() elif choice == \"3\": if currentFolder == \"None\": print \"\\nNo mail box", "= start + email_list_length - 1 if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails~ Page:", "method started begin = time.time() #loop till the timeout has passed while True:", "the socket back to blocking since only this method is designed for non=blocking", "for the emails for x in mail_list: recv = imap_examine(x) tmp = recv.split(\"", "= -1):#nums = the numbers of the emails, subs = the subjects of", "list wasn't specified in the params, set it to the end of the", "mail_nums = get_mail_numbers_from_search(recv) if len(mail_nums) > 0: print '\\n-------------------------------\\nEmails:' string_list = '' for", "get_mail_boxnum(): get_mail(0) def get_mail_uid(): get_mail(1) def get_mail(mail_type):#0 == search #1 == UID search", "begin time so that it doesn't timeout while still getting data else: time.sleep(0.1)#give", "to do? (0 to quit.)\" print \"1: View all mail boxes\" print \"2:", "= recv[pos1:pos2] if r != '': return True else: return False ################################# #Mail", "print \"Problem connecting.\\n\" ################################# #Done connecting ################################# ################################# #Global Variables ################################# currentFolder =", "== \"None\": print \"\\nNo mail box selected.\" else: get_mail_boxnum() elif choice == \"6\":", "mail type, NEXT or PREV\" choice = raw_input(\"Which email do you want to", "by:\" inc = 0 while inc < len(options): print str(inc) + \":\" +", "\"Connected.\\n\" else: print \"Problem connecting.\\n\" ################################# #Done connecting ################################# ################################# #Global Variables #################################", "choice == 'prev': again = 1 if current_page > 0: current_page-=1 else: again", "= recv.find('}') + 3 for index in reversed(range(len(recv))): #Loop from the end til", "box do you want to open: \") try: if int(choice) < len(mail_list): currentFolder", "== 'PREV' or choice == 'prev': again = 1 if current_page > 0:", "the mailbox names in a list with additional information def print_mailboxes_list_with_info(mailbox_list, info): print", "with mailserver #Fill in start #sslSocket = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), #ssl_version = ssl.PROTOCOL_SSLv23) sslSocket", "x + '\\r\\n') recv = recv_all() return recv #Expunge def imap_expunge(): sslSocket.send('A202 EXPUNGE\\r\\n')", "index = index + 1 print \"---------------------------------\" #Print the email list in the", "= recv_header.find(\"Date: \") pos2 = recv_header.find('OK Success\\r\\n')-11 print recv_header[pos:pos2] print \"--------------------------------------------------------------------\" print format_email_body(recv_body)", "#1 == UID #false = unread true = read print email_read if email_read:", "mail box.\" except: print \"\\nNot a valid mail box.\" def get_mail_boxnum(): get_mail(0) def", "< max_pages-1: current_page+=1 elif choice == 'PREV' or choice == 'prev': again =", "+ '\\r\\n') recv = sslSocket.recv(1024) print recv return recv #UID Search def imap_uid_search(x):", "= get_mailbox_list_array(mailbox_string) print_mailboxes_list(mail_list) choice = raw_input(\"Enter the number for the box to delete:", "/Noselect flag (And) isn't the all mail folder pos = x.find('/\" \"')+4 mail_list.append(x[pos:-1])", "search_mail(1) def search_mail(search_type):#0 == search #1 == UID search imap_examine(currentFolder) options = [\"All\",", "the socket print \"Done.\" #Main Method def main(): log_success = imap_login() if log_success", "emails, subs = the subjects of the emails if end == -1:#If the", "BODY[HEADER.FIELDS (SUBJECT)]\") else: subject_list = imap_uid_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list)", "print \"Deleted \" + name + \"!\" else: print \"Failed to delete.\" def", "indicators del temp_list[len(temp_list)-1]#The last element is an empty string, so it isn't needed", "called clientSocket and establish a TCP connection with mailserver #Fill in start #sslSocket", "a different timeout or use the default set in the parameter global sslSocket", "the data using a try/except to catch errors with getting data from the", "recv = imap_search('ALL') else: recv = imap_uid_search('ALL') mail_nums = get_mail_numbers_from_search(recv) string_list = ''", "+ ' ' + date_ch if search_type == 0: recv = imap_search(cmd) else:", "len(mail_nums)+2 > int(choice) and int(choice) > 0: print imap_uid_copy(choice + ' ' +", "start, end) print \"\\nTo view more mail type, NEXT or PREV\" choice =", "' + x + '\\r\\n') recv = recv_all() return recv #Create def imap_create(x):", "Variables ################################# currentFolder = \"None\" #Stores the currently selected mail box ################################# #imap", "= 'ALL' #unread elif choice == \"1\": cmd = 'UNSEEN' #old elif choice", "like to do? (0 to quit.)\" print \"1: View all mail boxes\" print", "1 else: print \"Login failed!\\n\" return -1 #List def imap_list(dir = \"\", type", "\"Invalid input.\" def testing(): imap_expunge() #Done running def close_mail(): sslSocket.close() #close the socket", "each mailbox contains def get_mailboxes_info_array(mail_list): mail_info_list = [] #Holds the list of info", "+ x + '\"\\r\\n') recv = recv_all() return recv #UID Fetch def imap_uid_fetch(x):", "\"\": print \"\\nNo Box chosen\" if cmd == \"all\": print \"Deleted\" else: imap_delete(cmd)", "recv = recv_all() return recv #UID Fetch def imap_uid_fetch(x): sslSocket.send('A999 UID FETCH '", "\") pos2 = recv_header.find('OK Success\\r\\n')-11 print recv_header[pos:pos2] print \"--------------------------------------------------------------------\" print format_email_body(recv_body) print \"===============================================================================\\n\"", "index < len(mailbox_list): print str(index) + \":\" + mailbox_list[index] index = index +", "recv return recv #UID Copy def imap_uid_copy(x): sslSocket.send('A300 COPY \"' + x +", "Examine a mail box\" print \"3: Search selected mail box\" print \"4: Search", "!= -1: print \"Created \" + name + \"!\" else: print \"Failed to", "int(choice) if ch_num > len(mail_list): cmd = \"No Box available\" else: name =", "+ '\\r\\n') recv = recv_all() return recv #Expunge def imap_expunge(): sslSocket.send('A202 EXPUNGE\\r\\n') recv", "box.\" except: print \"\\nNot a valid mail box.\" def get_mail_boxnum(): get_mail(0) def get_mail_uid():", "get_mailbox_list_array(mailbox_string): temp_list = mailbox_string.split('\\r\\n')#Split the returned string by the new line indicators del", "= l[pos2+1:] return li def email_is_read(mail_type, ch):#0 == norm #1 == UID recv", "if search_type == 0: subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") else: subject_list", "string_list += str(mail_nums[x]) + ',' if string_list: string_list = string_list[:-1] subject_list = imap_uid_fetch(string_list", "cmd = 'UNSEEN' #old elif choice == \"2\": cmd = 'OLD' #drafts elif", "choice == \"4\": if currentFolder == \"None\": print \"\\nNo mail box selected.\" else:", "#If no data has been retrieved and it has passed the timeout by", "imap_delete(cmd) if recv.find(\"OK Success\") != -1: print \"Deleted \" + name + \"!\"", "+ \" BODY[HEADER.FIELDS (SUBJECT)]\") mailboxes_info = filter_list_of_subjects(subject_list) print_mail_list_with_subject(mail_nums, mailboxes_info) else: print \"Mail box", "nothing to get, so stop elif time.time()-begin > timeout*2: break #try and get", "isn't needed mail_list = []#Will hold the list of mailbox names to be", "the emails if end == -1:#If the point to stop printing in the", "received data_str = '' #time this method started begin = time.time() #loop till", "def examine_mailbox(): global currentFolder mailbox_string = imap_list() mail_list = get_mailbox_list_array(mailbox_string) mailboxes_info = get_mailboxes_info_array(mail_list)", "elif choice == \"10\": testing() if choice == \"0\": close_mail() if __name__ ==", "= imap_list(\"/\", \"*\") mail_list = get_mailbox_list_array(mailbox_string) print_mailboxes_list(mail_list) choice = raw_input(\"Enter the number for", "of the lists print str(nums[start-1]) + \": \" + str(subs[start-1]) start += 1", "raw_input(\"Choice: \") if choice == \"1\": #mark as read recv = imap_uid_store(msg_uid +", "#date elif choice == \"5\": when_ch = raw_input(\"(Before date = 1)(On date =", "+ x + '\\r\\n') recv = sslSocket.recv(1024) print recv return recv #UID Search", "print recv imap_expunge() except: print \"Email not available.\" def create_dir(): name = raw_input(\"\\nName", "try: temp_list.append(int(t)) except: pass return temp_list #Return the text of the email body", "== \"None\": print \"\\nNo mail box selected.\" else: search_mail_search() elif choice == \"4\":", "') != -1: pos1 = l.find('\\nSubject: ')+1 pos2 = l.find('\\r') new = l[pos1:pos2]", "while index < len(mailbox_list): print str(index) + \":\" + mailbox_list[index] + \" \"", "print \"Invalid input.\" def testing(): imap_expunge() #Done running def close_mail(): sslSocket.close() #close the", "'NEXT' or choice == 'next': again = 1 if current_page < max_pages-1: current_page+=1", "and strg != s: return True return False def delete_all_children_with_child(strg, mailbox_list): for s", "def print_mailboxes_list_with_info(mailbox_list, info): print \"\" print \"---------------------------------\" print \"Mail Boxes:\" index = 0", "the timeout, then stop if data_str and time.time()-begin > timeout: break #If no", "0: print '\\n-------------------------------\\nEmails:' string_list = '' for x in range(len(mail_nums)): string_list += str(mail_nums[x])", "\" + currentFolder print \"---------------------------------------------\" print \"What would you like to do? (0", "143) # Create socket called clientSocket and establish a TCP connection with mailserver", "end of the list end = len(subs) while start <= len(nums) and start", "testing(): imap_expunge() #Done running def close_mail(): sslSocket.close() #close the socket print \"Done.\" #Main", "== \"2\": date_opt = \"ON\" elif when_ch == \"3\": date_opt = \"SINCE\" cmd", "print str(nums[start-1]) + \": \" + str(subs[start-1]) start += 1 #Get how many", "'\\r\\n') recv = sslSocket.recv(1024) print recv return recv #UID Search def imap_uid_search(x): sslSocket.send('A999", "else: get_mail_uid() elif choice == \"7\": create_dir() elif choice == \"8\": delete_dir() elif", "print \"Connecting..\" username = \"\" password = \"\" # Choose a mail server", "!= -1 and strg != s: return True return False def delete_all_children_with_child(strg, mailbox_list):", "= 0 if len(mail_nums) > 0: try: ch = int(choice) if mail_type ==", "while choice != \"0\": print \"\\n\" print \"---------------------------------------------\" print \"-- Currently Selected Mailbox:", "mailbox_list: if s.find(strg) != -1: imap_delete(s) def filter_list_of_subjects(l): li = [] if l.find('\\nSubject:", "def get_mail_uid(): get_mail(1) def get_mail(mail_type):#0 == search #1 == UID search imap_select(currentFolder) email_list_length", "\"5\": when_ch = raw_input(\"(Before date = 1)(On date = 2)(Since date = 3):\")", "else: recv = imap_uid_search(str(ch) + ' SEEN') pos1 = recv.find('SEARCH')+7 pos2 = recv.find('\\r')", "if string_list: string_list = string_list[:-1] if search_type == 0: subject_list = imap_fetch(string_list +", "start += 1 #Get how many emails each mailbox contains def get_mailboxes_info_array(mail_list): mail_info_list", "\"Created \" + name + \"!\" else: print \"Failed to create.\" def delete_dir():", "to blocking since only this method is designed for non=blocking sslSocket.setblocking(1) return data_str", "recv = recv_all() return recv #Examine def imap_examine(x): sslSocket.send('A900 EXAMINE \"' + x", "strg != s: return True return False def delete_all_children_with_child(strg, mailbox_list): for s in", "recv.find('}') != -1:#Find the first } first = recv.find('}') + 3 for index", "Boxes:\" index = 0 while index < len(mailbox_list): print str(index) + \":\" +", "') temp_list = [] for t in tmp: try: temp_list.append(int(t)) except: pass return", "> len(mail_list): cmd = \"No Box available\" else: name = mail_list[ch_num] if has_children(name,", "Mail') == -1:#The line has a mail box (AND) doesn't contain the /Noselect", "\"5\": if currentFolder == \"None\": print \"\\nNo mail box selected.\" else: get_mail_boxnum() elif", "choice == \"5\": if currentFolder == \"None\": print \"\\nNo mail box selected.\" else:", "imap_delete(x): print 'A501 DELETE \"' + x + '\"\\r\\n' sslSocket.send('A501 DELETE \"' +", "-FLAGS (\\seen)') elif choice == \"2\": #delete recv = imap_uid_store(msg_uid + ' +FLAGS", "currentFolder = \"None\" #Stores the currently selected mail box ################################# #imap Methods #################################", "< len(mail_list): currentFolder = mail_list[int(choice)] print \"\\nSelected \" + currentFolder else: print \"\\nNot", "hold the list of mailbox names to be returned for x in temp_list:", "password = \"\" # Choose a mail server (e.g. Google mail server) and", "return -1 #List def imap_list(dir = \"\", type = \"*\"):#return list of mailboxes", "imap_expunge() except: print \"Email not available.\" def create_dir(): name = raw_input(\"\\nName of new", "data that was received then store that data data_str += data begin=time.time()#reset the", "= filter_list_of_subjects(subject_list) max_pages = int(len(mail_nums)/email_list_length) if (len(mail_nums)%email_list_length) > 0: max_pages += 1 current_page", "'': return True else: return False ################################# #Mail Client Methods ################################# def view_mailboxes():", "search_type == 0: subject_list = imap_fetch(string_list + \" BODY[HEADER.FIELDS (SUBJECT)]\") else: subject_list =", "copy_mail() elif choice == \"10\": testing() if choice == \"0\": close_mail() if __name__", "print_mail_list_with_subject(mail_nums, mailboxes_info, start, end) print \"\\nTo view more mail type, NEXT or PREV\"", "except: cmd = \"\" print \"Checking: \" + cmd if cmd == \"\":", "find the A if recv[index] == 'A': last = index - 5 break", "return recv #Create def imap_create(x): sslSocket.send('A401 CREATE \"' + x + '\"\\r\\n') recv", "+ '\"\\r\\n') recv = recv_all() return recv ################################# #Extra Methods ################################# #Receive using", "= imap_fetch(str(ch) + \" BODY[HEADER.FIELDS (DATE SUBJECT FROM TO)]\") recv_uid = imap_fetch(str(ch) +", "imap_uid_fetch(str(ch) + \" (UID)\") print \"\\n===============================================================================\" pos = recv_uid.find('(UID')+5 pos2 = recv_uid.find(')') msg_uid", "inc + 1 print \"------------------------------\" choice = raw_input(\"Choice: \") cmd = \"\" #all", "'\\n-------------------------------\\nEmails:' string_list = '' for x in range(len(mail_nums)): string_list += str(mail_nums[x]) + ','", "recv_uid = imap_uid_fetch(str(ch) + \" (UID)\") print \"\\n===============================================================================\" pos = recv_uid.find('(UID')+5 pos2 =", "a mail box\" print \"3: Search selected mail box\" print \"4: Search using", "currentFolder == \"None\": print \"\\nNo mail box selected.\" else: get_mail_boxnum() elif choice ==", "\"2\": cmd = 'OLD' #drafts elif choice == \"3\": cmd = 'DRAFT' #text", "recv = recv_all() return recv #UID Store def imap_uid_store(x): print 'A003 UID STORE", "== UID search imap_select(currentFolder) email_list_length = 10 if mail_type == 0: recv =", "pos = recv_header.find(\"Date: \") pos2 = recv_header.find('OK Success\\r\\n')-11 print recv_header[pos:pos2] print \"--------------------------------------------------------------------\" print", "id\" print \"5: Get mail from selected mail box\" print \"6: Get mail" ]
[ "HTTPException, default_exceptions import connexion from utils.network import log_endpoints from utils.network.exc import HttpException from", "timedelta(days=1) jwt = JWTManager(app) CORS(app) @app.teardown_request def teardown_request(exception): if exception: database.Session.rollback() database.Session.remove() @app.errorhandler(HttpException)", "import timedelta from flask import jsonify from flask_cors import CORS from flask_jwt_extended import", "utils.network.exc import HttpException from config import config from database import database from logging_config", "= connexion.App(__name__, arguments={ 'server_host': config.get('server', 'host'), 'version': __version__ }) connexion_app.add_api('api_swagger.yml') app = connexion_app.app", "'status': e.code, 'detail': e.message }), e.code @app.errorhandler(Exception) def handle_error(e): code = 500 if", "}), e.code @app.errorhandler(Exception) def handle_error(e): code = 500 if isinstance(e, HTTPException): code =", "logging from datetime import timedelta from flask import jsonify from flask_cors import CORS", "= logging.getLogger(__name__) connexion_app = connexion.App(__name__, arguments={ 'server_host': config.get('server', 'host'), 'version': __version__ }) connexion_app.add_api('api_swagger.yml')", "'version': __version__ }) connexion_app.add_api('api_swagger.yml') app = connexion_app.app for blueprint in blueprints: app.register_blueprint(blueprint) app.config['JWT_SECRET_KEY']", "flask_cors import CORS from flask_jwt_extended import JWTManager from werkzeug.exceptions import HTTPException, default_exceptions import", "500 if isinstance(e, HTTPException): code = e.code return jsonify({ 'status': code, 'detail': str(e)", "'detail': str(e) }), code if __name__ == '__main__': logging_config() port = int(config.get('server', 'port'))", "return jsonify({ 'status': code, 'detail': str(e) }), code if __name__ == '__main__': logging_config()", "log.info(f'Running rl-loadout {__version__} on port {port}') log_endpoints(log, app) for ex in default_exceptions: app.register_error_handler(ex,", "JWTManager from werkzeug.exceptions import HTTPException, default_exceptions import connexion from utils.network import log_endpoints from", "def handle_error(e): code = 500 if isinstance(e, HTTPException): code = e.code return jsonify({", "database.Session.remove() @app.errorhandler(HttpException) def handle_http_exception(e: HttpException): return jsonify({ 'status': e.code, 'detail': e.message }), e.code", "connexion_app.app for blueprint in blueprints: app.register_blueprint(blueprint) app.config['JWT_SECRET_KEY'] = config.get('server', 'jwt_secret') app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1)", "import __version__ log = logging.getLogger(__name__) connexion_app = connexion.App(__name__, arguments={ 'server_host': config.get('server', 'host'), 'version':", "<reponame>Longi94/rl-loadout import logging from datetime import timedelta from flask import jsonify from flask_cors", "werkzeug.exceptions import HTTPException, default_exceptions import connexion from utils.network import log_endpoints from utils.network.exc import", "}) connexion_app.add_api('api_swagger.yml') app = connexion_app.app for blueprint in blueprints: app.register_blueprint(blueprint) app.config['JWT_SECRET_KEY'] = config.get('server',", "= connexion_app.app for blueprint in blueprints: app.register_blueprint(blueprint) app.config['JWT_SECRET_KEY'] = config.get('server', 'jwt_secret') app.config['JWT_ACCESS_TOKEN_EXPIRES'] =", "= config.get('server', 'jwt_secret') app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1) jwt = JWTManager(app) CORS(app) @app.teardown_request def teardown_request(exception):", "'jwt_secret') app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1) jwt = JWTManager(app) CORS(app) @app.teardown_request def teardown_request(exception): if exception:", "import jsonify from flask_cors import CORS from flask_jwt_extended import JWTManager from werkzeug.exceptions import", "import log_endpoints from utils.network.exc import HttpException from config import config from database import", "blueprints from _version import __version__ log = logging.getLogger(__name__) connexion_app = connexion.App(__name__, arguments={ 'server_host':", "e.code, 'detail': e.message }), e.code @app.errorhandler(Exception) def handle_error(e): code = 500 if isinstance(e,", "jwt = JWTManager(app) CORS(app) @app.teardown_request def teardown_request(exception): if exception: database.Session.rollback() database.Session.remove() @app.errorhandler(HttpException) def", "connexion from utils.network import log_endpoints from utils.network.exc import HttpException from config import config", "int(config.get('server', 'port')) log.info(f'Running rl-loadout {__version__} on port {port}') log_endpoints(log, app) for ex in", "return jsonify({ 'status': e.code, 'detail': e.message }), e.code @app.errorhandler(Exception) def handle_error(e): code =", "@app.errorhandler(Exception) def handle_error(e): code = 500 if isinstance(e, HTTPException): code = e.code return", "datetime import timedelta from flask import jsonify from flask_cors import CORS from flask_jwt_extended", "from utils.network.exc import HttpException from config import config from database import database from", "config from database import database from logging_config import logging_config from blueprints import blueprints", "database from logging_config import logging_config from blueprints import blueprints from _version import __version__", "'__main__': logging_config() port = int(config.get('server', 'port')) log.info(f'Running rl-loadout {__version__} on port {port}') log_endpoints(log,", "connexion_app = connexion.App(__name__, arguments={ 'server_host': config.get('server', 'host'), 'version': __version__ }) connexion_app.add_api('api_swagger.yml') app =", "= JWTManager(app) CORS(app) @app.teardown_request def teardown_request(exception): if exception: database.Session.rollback() database.Session.remove() @app.errorhandler(HttpException) def handle_http_exception(e:", "@app.teardown_request def teardown_request(exception): if exception: database.Session.rollback() database.Session.remove() @app.errorhandler(HttpException) def handle_http_exception(e: HttpException): return jsonify({", "'status': code, 'detail': str(e) }), code if __name__ == '__main__': logging_config() port =", "__version__ log = logging.getLogger(__name__) connexion_app = connexion.App(__name__, arguments={ 'server_host': config.get('server', 'host'), 'version': __version__", "logging_config import logging_config from blueprints import blueprints from _version import __version__ log =", "from flask_jwt_extended import JWTManager from werkzeug.exceptions import HTTPException, default_exceptions import connexion from utils.network", "rl-loadout {__version__} on port {port}') log_endpoints(log, app) for ex in default_exceptions: app.register_error_handler(ex, handle_error)", "arguments={ 'server_host': config.get('server', 'host'), 'version': __version__ }) connexion_app.add_api('api_swagger.yml') app = connexion_app.app for blueprint", "import HttpException from config import config from database import database from logging_config import", "= timedelta(days=1) jwt = JWTManager(app) CORS(app) @app.teardown_request def teardown_request(exception): if exception: database.Session.rollback() database.Session.remove()", "from flask_cors import CORS from flask_jwt_extended import JWTManager from werkzeug.exceptions import HTTPException, default_exceptions", "HTTPException): code = e.code return jsonify({ 'status': code, 'detail': str(e) }), code if", "e.code @app.errorhandler(Exception) def handle_error(e): code = 500 if isinstance(e, HTTPException): code = e.code", "'server_host': config.get('server', 'host'), 'version': __version__ }) connexion_app.add_api('api_swagger.yml') app = connexion_app.app for blueprint in", "CORS from flask_jwt_extended import JWTManager from werkzeug.exceptions import HTTPException, default_exceptions import connexion from", "from werkzeug.exceptions import HTTPException, default_exceptions import connexion from utils.network import log_endpoints from utils.network.exc", "__name__ == '__main__': logging_config() port = int(config.get('server', 'port')) log.info(f'Running rl-loadout {__version__} on port", "config import config from database import database from logging_config import logging_config from blueprints", "def teardown_request(exception): if exception: database.Session.rollback() database.Session.remove() @app.errorhandler(HttpException) def handle_http_exception(e: HttpException): return jsonify({ 'status':", "jsonify from flask_cors import CORS from flask_jwt_extended import JWTManager from werkzeug.exceptions import HTTPException,", "= int(config.get('server', 'port')) log.info(f'Running rl-loadout {__version__} on port {port}') log_endpoints(log, app) for ex", "from _version import __version__ log = logging.getLogger(__name__) connexion_app = connexion.App(__name__, arguments={ 'server_host': config.get('server',", "logging.getLogger(__name__) connexion_app = connexion.App(__name__, arguments={ 'server_host': config.get('server', 'host'), 'version': __version__ }) connexion_app.add_api('api_swagger.yml') app", "app.config['JWT_SECRET_KEY'] = config.get('server', 'jwt_secret') app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1) jwt = JWTManager(app) CORS(app) @app.teardown_request def", "connexion.App(__name__, arguments={ 'server_host': config.get('server', 'host'), 'version': __version__ }) connexion_app.add_api('api_swagger.yml') app = connexion_app.app for", "HttpException from config import config from database import database from logging_config import logging_config", "code = e.code return jsonify({ 'status': code, 'detail': str(e) }), code if __name__", "timedelta from flask import jsonify from flask_cors import CORS from flask_jwt_extended import JWTManager", "handle_error(e): code = 500 if isinstance(e, HTTPException): code = e.code return jsonify({ 'status':", "database import database from logging_config import logging_config from blueprints import blueprints from _version", "code, 'detail': str(e) }), code if __name__ == '__main__': logging_config() port = int(config.get('server',", "}), code if __name__ == '__main__': logging_config() port = int(config.get('server', 'port')) log.info(f'Running rl-loadout", "flask_jwt_extended import JWTManager from werkzeug.exceptions import HTTPException, default_exceptions import connexion from utils.network import", "in blueprints: app.register_blueprint(blueprint) app.config['JWT_SECRET_KEY'] = config.get('server', 'jwt_secret') app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1) jwt = JWTManager(app)", "config.get('server', 'jwt_secret') app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1) jwt = JWTManager(app) CORS(app) @app.teardown_request def teardown_request(exception): if", "'host'), 'version': __version__ }) connexion_app.add_api('api_swagger.yml') app = connexion_app.app for blueprint in blueprints: app.register_blueprint(blueprint)", "on port {port}') log_endpoints(log, app) for ex in default_exceptions: app.register_error_handler(ex, handle_error) connexion_app.run(host='0.0.0.0', port=port)", "jsonify({ 'status': code, 'detail': str(e) }), code if __name__ == '__main__': logging_config() port", "app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1) jwt = JWTManager(app) CORS(app) @app.teardown_request def teardown_request(exception): if exception: database.Session.rollback()", "import database from logging_config import logging_config from blueprints import blueprints from _version import", "flask import jsonify from flask_cors import CORS from flask_jwt_extended import JWTManager from werkzeug.exceptions", "blueprint in blueprints: app.register_blueprint(blueprint) app.config['JWT_SECRET_KEY'] = config.get('server', 'jwt_secret') app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1) jwt =", "_version import __version__ log = logging.getLogger(__name__) connexion_app = connexion.App(__name__, arguments={ 'server_host': config.get('server', 'host'),", "__version__ }) connexion_app.add_api('api_swagger.yml') app = connexion_app.app for blueprint in blueprints: app.register_blueprint(blueprint) app.config['JWT_SECRET_KEY'] =", "@app.errorhandler(HttpException) def handle_http_exception(e: HttpException): return jsonify({ 'status': e.code, 'detail': e.message }), e.code @app.errorhandler(Exception)", "from database import database from logging_config import logging_config from blueprints import blueprints from", "if __name__ == '__main__': logging_config() port = int(config.get('server', 'port')) log.info(f'Running rl-loadout {__version__} on", "jsonify({ 'status': e.code, 'detail': e.message }), e.code @app.errorhandler(Exception) def handle_error(e): code = 500", "import CORS from flask_jwt_extended import JWTManager from werkzeug.exceptions import HTTPException, default_exceptions import connexion", "code = 500 if isinstance(e, HTTPException): code = e.code return jsonify({ 'status': code,", "e.code return jsonify({ 'status': code, 'detail': str(e) }), code if __name__ == '__main__':", "== '__main__': logging_config() port = int(config.get('server', 'port')) log.info(f'Running rl-loadout {__version__} on port {port}')", "from utils.network import log_endpoints from utils.network.exc import HttpException from config import config from", "from datetime import timedelta from flask import jsonify from flask_cors import CORS from", "app = connexion_app.app for blueprint in blueprints: app.register_blueprint(blueprint) app.config['JWT_SECRET_KEY'] = config.get('server', 'jwt_secret') app.config['JWT_ACCESS_TOKEN_EXPIRES']", "from config import config from database import database from logging_config import logging_config from", "from flask import jsonify from flask_cors import CORS from flask_jwt_extended import JWTManager from", "if isinstance(e, HTTPException): code = e.code return jsonify({ 'status': code, 'detail': str(e) }),", "utils.network import log_endpoints from utils.network.exc import HttpException from config import config from database", "e.message }), e.code @app.errorhandler(Exception) def handle_error(e): code = 500 if isinstance(e, HTTPException): code", "port = int(config.get('server', 'port')) log.info(f'Running rl-loadout {__version__} on port {port}') log_endpoints(log, app) for", "import HTTPException, default_exceptions import connexion from utils.network import log_endpoints from utils.network.exc import HttpException", "for blueprint in blueprints: app.register_blueprint(blueprint) app.config['JWT_SECRET_KEY'] = config.get('server', 'jwt_secret') app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1) jwt", "blueprints: app.register_blueprint(blueprint) app.config['JWT_SECRET_KEY'] = config.get('server', 'jwt_secret') app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1) jwt = JWTManager(app) CORS(app)", "logging_config from blueprints import blueprints from _version import __version__ log = logging.getLogger(__name__) connexion_app", "log = logging.getLogger(__name__) connexion_app = connexion.App(__name__, arguments={ 'server_host': config.get('server', 'host'), 'version': __version__ })", "default_exceptions import connexion from utils.network import log_endpoints from utils.network.exc import HttpException from config", "{__version__} on port {port}') log_endpoints(log, app) for ex in default_exceptions: app.register_error_handler(ex, handle_error) connexion_app.run(host='0.0.0.0',", "HttpException): return jsonify({ 'status': e.code, 'detail': e.message }), e.code @app.errorhandler(Exception) def handle_error(e): code", "handle_http_exception(e: HttpException): return jsonify({ 'status': e.code, 'detail': e.message }), e.code @app.errorhandler(Exception) def handle_error(e):", "CORS(app) @app.teardown_request def teardown_request(exception): if exception: database.Session.rollback() database.Session.remove() @app.errorhandler(HttpException) def handle_http_exception(e: HttpException): return", "JWTManager(app) CORS(app) @app.teardown_request def teardown_request(exception): if exception: database.Session.rollback() database.Session.remove() @app.errorhandler(HttpException) def handle_http_exception(e: HttpException):", "def handle_http_exception(e: HttpException): return jsonify({ 'status': e.code, 'detail': e.message }), e.code @app.errorhandler(Exception) def", "code if __name__ == '__main__': logging_config() port = int(config.get('server', 'port')) log.info(f'Running rl-loadout {__version__}", "isinstance(e, HTTPException): code = e.code return jsonify({ 'status': code, 'detail': str(e) }), code", "import connexion from utils.network import log_endpoints from utils.network.exc import HttpException from config import", "exception: database.Session.rollback() database.Session.remove() @app.errorhandler(HttpException) def handle_http_exception(e: HttpException): return jsonify({ 'status': e.code, 'detail': e.message", "import JWTManager from werkzeug.exceptions import HTTPException, default_exceptions import connexion from utils.network import log_endpoints", "from logging_config import logging_config from blueprints import blueprints from _version import __version__ log", "import logging from datetime import timedelta from flask import jsonify from flask_cors import", "connexion_app.add_api('api_swagger.yml') app = connexion_app.app for blueprint in blueprints: app.register_blueprint(blueprint) app.config['JWT_SECRET_KEY'] = config.get('server', 'jwt_secret')", "log_endpoints from utils.network.exc import HttpException from config import config from database import database", "import logging_config from blueprints import blueprints from _version import __version__ log = logging.getLogger(__name__)", "if exception: database.Session.rollback() database.Session.remove() @app.errorhandler(HttpException) def handle_http_exception(e: HttpException): return jsonify({ 'status': e.code, 'detail':", "logging_config() port = int(config.get('server', 'port')) log.info(f'Running rl-loadout {__version__} on port {port}') log_endpoints(log, app)", "'port')) log.info(f'Running rl-loadout {__version__} on port {port}') log_endpoints(log, app) for ex in default_exceptions:", "= 500 if isinstance(e, HTTPException): code = e.code return jsonify({ 'status': code, 'detail':", "import blueprints from _version import __version__ log = logging.getLogger(__name__) connexion_app = connexion.App(__name__, arguments={", "from blueprints import blueprints from _version import __version__ log = logging.getLogger(__name__) connexion_app =", "= e.code return jsonify({ 'status': code, 'detail': str(e) }), code if __name__ ==", "str(e) }), code if __name__ == '__main__': logging_config() port = int(config.get('server', 'port')) log.info(f'Running", "config.get('server', 'host'), 'version': __version__ }) connexion_app.add_api('api_swagger.yml') app = connexion_app.app for blueprint in blueprints:", "teardown_request(exception): if exception: database.Session.rollback() database.Session.remove() @app.errorhandler(HttpException) def handle_http_exception(e: HttpException): return jsonify({ 'status': e.code,", "'detail': e.message }), e.code @app.errorhandler(Exception) def handle_error(e): code = 500 if isinstance(e, HTTPException):", "blueprints import blueprints from _version import __version__ log = logging.getLogger(__name__) connexion_app = connexion.App(__name__,", "database.Session.rollback() database.Session.remove() @app.errorhandler(HttpException) def handle_http_exception(e: HttpException): return jsonify({ 'status': e.code, 'detail': e.message }),", "app.register_blueprint(blueprint) app.config['JWT_SECRET_KEY'] = config.get('server', 'jwt_secret') app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1) jwt = JWTManager(app) CORS(app) @app.teardown_request", "import config from database import database from logging_config import logging_config from blueprints import" ]
[ "in range(2,len(augPattern)): s = links[k-1] stop = False while s>=1 and not stop:", "= False while s>=1 and not stop: if augPattern[s] == augPattern[k-1]: stop =", "augPattern = \"0\"+pattern links = {} links[1] = 0 for k in range(2,len(augPattern)):", "{} links[1] = 0 for k in range(2,len(augPattern)): s = links[k-1] stop =", "= \"0\"+pattern links = {} links[1] = 0 for k in range(2,len(augPattern)): s", "range(2,len(augPattern)): s = links[k-1] stop = False while s>=1 and not stop: if", "s>=1 and not stop: if augPattern[s] == augPattern[k-1]: stop = True else: s", "links[k-1] stop = False while s>=1 and not stop: if augPattern[s] == augPattern[k-1]:", "== augPattern[k-1]: stop = True else: s = links[s] links[k] = s+1 return", "augPattern[k-1]: stop = True else: s = links[s] links[k] = s+1 return links", "= 0 for k in range(2,len(augPattern)): s = links[k-1] stop = False while", "if augPattern[s] == augPattern[k-1]: stop = True else: s = links[s] links[k] =", "\"0\"+pattern links = {} links[1] = 0 for k in range(2,len(augPattern)): s =", "for k in range(2,len(augPattern)): s = links[k-1] stop = False while s>=1 and", "while s>=1 and not stop: if augPattern[s] == augPattern[k-1]: stop = True else:", "not stop: if augPattern[s] == augPattern[k-1]: stop = True else: s = links[s]", "0 for k in range(2,len(augPattern)): s = links[k-1] stop = False while s>=1", "augPattern[s] == augPattern[k-1]: stop = True else: s = links[s] links[k] = s+1", "k in range(2,len(augPattern)): s = links[k-1] stop = False while s>=1 and not", "stop: if augPattern[s] == augPattern[k-1]: stop = True else: s = links[s] links[k]", "def mismatchLinks(pattern): augPattern = \"0\"+pattern links = {} links[1] = 0 for k", "links[1] = 0 for k in range(2,len(augPattern)): s = links[k-1] stop = False", "stop = False while s>=1 and not stop: if augPattern[s] == augPattern[k-1]: stop", "= {} links[1] = 0 for k in range(2,len(augPattern)): s = links[k-1] stop", "and not stop: if augPattern[s] == augPattern[k-1]: stop = True else: s =", "= links[k-1] stop = False while s>=1 and not stop: if augPattern[s] ==", "mismatchLinks(pattern): augPattern = \"0\"+pattern links = {} links[1] = 0 for k in", "links = {} links[1] = 0 for k in range(2,len(augPattern)): s = links[k-1]", "s = links[k-1] stop = False while s>=1 and not stop: if augPattern[s]", "False while s>=1 and not stop: if augPattern[s] == augPattern[k-1]: stop = True" ]
[ "speaker in self.event.submitters: accepted_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.ACCEPTED ).exists() confirmed_talks = speaker.submissions.filter( event=self.event,", "speaker.submissions.filter( event=self.event, state=SubmissionStates.ACCEPTED ).exists() confirmed_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.CONFIRMED ).exists() if not accepted_talks", "not accepted_talks and not confirmed_talks: continue writer.writerow( { 'name': speaker.get_display_name(), 'email': speaker.email, 'confirmed':", "from pretalx.common.exporter import BaseExporter from pretalx.submission.models import SubmissionStates class CSVSpeakerExporter(BaseExporter): public = False", "self.event.submitters: accepted_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.ACCEPTED ).exists() confirmed_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.CONFIRMED ).exists()", "= False icon = 'fa-users' identifier = 'speakers.csv' verbose_name = _('Speaker CSV') def", "fieldnames=['name', 'email', 'confirmed']) writer.writeheader() for speaker in self.event.submitters: accepted_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.ACCEPTED", "'confirmed']) writer.writeheader() for speaker in self.event.submitters: accepted_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.ACCEPTED ).exists() confirmed_talks", "ugettext_lazy as _ from pretalx.common.exporter import BaseExporter from pretalx.submission.models import SubmissionStates class CSVSpeakerExporter(BaseExporter):", "= speaker.submissions.filter( event=self.event, state=SubmissionStates.CONFIRMED ).exists() if not accepted_talks and not confirmed_talks: continue writer.writerow(", "django.utils.translation import ugettext_lazy as _ from pretalx.common.exporter import BaseExporter from pretalx.submission.models import SubmissionStates", "writer.writeheader() for speaker in self.event.submitters: accepted_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.ACCEPTED ).exists() confirmed_talks =", "import SubmissionStates class CSVSpeakerExporter(BaseExporter): public = False icon = 'fa-users' identifier = 'speakers.csv'", "as _ from pretalx.common.exporter import BaseExporter from pretalx.submission.models import SubmissionStates class CSVSpeakerExporter(BaseExporter): public", "identifier = 'speakers.csv' verbose_name = _('Speaker CSV') def render(self, **kwargs): content = io.StringIO()", "and not confirmed_talks: continue writer.writerow( { 'name': speaker.get_display_name(), 'email': speaker.email, 'confirmed': str(bool(confirmed_talks)), }", "= _('Speaker CSV') def render(self, **kwargs): content = io.StringIO() writer = csv.DictWriter(content, fieldnames=['name',", "speaker.submissions.filter( event=self.event, state=SubmissionStates.CONFIRMED ).exists() if not accepted_talks and not confirmed_talks: continue writer.writerow( {", "io from django.utils.translation import ugettext_lazy as _ from pretalx.common.exporter import BaseExporter from pretalx.submission.models", "<reponame>MaxRink/pretalx import csv import io from django.utils.translation import ugettext_lazy as _ from pretalx.common.exporter", "accepted_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.ACCEPTED ).exists() confirmed_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.CONFIRMED ).exists() if", "writer.writerow( { 'name': speaker.get_display_name(), 'email': speaker.email, 'confirmed': str(bool(confirmed_talks)), } ) return (f'{self.event.slug}-speakers.csv', 'text/plain',", "SubmissionStates class CSVSpeakerExporter(BaseExporter): public = False icon = 'fa-users' identifier = 'speakers.csv' verbose_name", "accepted_talks and not confirmed_talks: continue writer.writerow( { 'name': speaker.get_display_name(), 'email': speaker.email, 'confirmed': str(bool(confirmed_talks)),", "from pretalx.submission.models import SubmissionStates class CSVSpeakerExporter(BaseExporter): public = False icon = 'fa-users' identifier", "import BaseExporter from pretalx.submission.models import SubmissionStates class CSVSpeakerExporter(BaseExporter): public = False icon =", "CSV') def render(self, **kwargs): content = io.StringIO() writer = csv.DictWriter(content, fieldnames=['name', 'email', 'confirmed'])", "content = io.StringIO() writer = csv.DictWriter(content, fieldnames=['name', 'email', 'confirmed']) writer.writeheader() for speaker in", "= 'speakers.csv' verbose_name = _('Speaker CSV') def render(self, **kwargs): content = io.StringIO() writer", "def render(self, **kwargs): content = io.StringIO() writer = csv.DictWriter(content, fieldnames=['name', 'email', 'confirmed']) writer.writeheader()", "= csv.DictWriter(content, fieldnames=['name', 'email', 'confirmed']) writer.writeheader() for speaker in self.event.submitters: accepted_talks = speaker.submissions.filter(", "csv.DictWriter(content, fieldnames=['name', 'email', 'confirmed']) writer.writeheader() for speaker in self.event.submitters: accepted_talks = speaker.submissions.filter( event=self.event,", "pretalx.common.exporter import BaseExporter from pretalx.submission.models import SubmissionStates class CSVSpeakerExporter(BaseExporter): public = False icon", "False icon = 'fa-users' identifier = 'speakers.csv' verbose_name = _('Speaker CSV') def render(self,", "verbose_name = _('Speaker CSV') def render(self, **kwargs): content = io.StringIO() writer = csv.DictWriter(content,", "confirmed_talks: continue writer.writerow( { 'name': speaker.get_display_name(), 'email': speaker.email, 'confirmed': str(bool(confirmed_talks)), } ) return", "**kwargs): content = io.StringIO() writer = csv.DictWriter(content, fieldnames=['name', 'email', 'confirmed']) writer.writeheader() for speaker", "public = False icon = 'fa-users' identifier = 'speakers.csv' verbose_name = _('Speaker CSV')", "= speaker.submissions.filter( event=self.event, state=SubmissionStates.ACCEPTED ).exists() confirmed_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.CONFIRMED ).exists() if not", "event=self.event, state=SubmissionStates.ACCEPTED ).exists() confirmed_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.CONFIRMED ).exists() if not accepted_talks and", "io.StringIO() writer = csv.DictWriter(content, fieldnames=['name', 'email', 'confirmed']) writer.writeheader() for speaker in self.event.submitters: accepted_talks", "class CSVSpeakerExporter(BaseExporter): public = False icon = 'fa-users' identifier = 'speakers.csv' verbose_name =", "event=self.event, state=SubmissionStates.CONFIRMED ).exists() if not accepted_talks and not confirmed_talks: continue writer.writerow( { 'name':", "continue writer.writerow( { 'name': speaker.get_display_name(), 'email': speaker.email, 'confirmed': str(bool(confirmed_talks)), } ) return (f'{self.event.slug}-speakers.csv',", "'email', 'confirmed']) writer.writeheader() for speaker in self.event.submitters: accepted_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.ACCEPTED ).exists()", ").exists() if not accepted_talks and not confirmed_talks: continue writer.writerow( { 'name': speaker.get_display_name(), 'email':", "_('Speaker CSV') def render(self, **kwargs): content = io.StringIO() writer = csv.DictWriter(content, fieldnames=['name', 'email',", "_ from pretalx.common.exporter import BaseExporter from pretalx.submission.models import SubmissionStates class CSVSpeakerExporter(BaseExporter): public =", "'fa-users' identifier = 'speakers.csv' verbose_name = _('Speaker CSV') def render(self, **kwargs): content =", "'speakers.csv' verbose_name = _('Speaker CSV') def render(self, **kwargs): content = io.StringIO() writer =", "= 'fa-users' identifier = 'speakers.csv' verbose_name = _('Speaker CSV') def render(self, **kwargs): content", "from django.utils.translation import ugettext_lazy as _ from pretalx.common.exporter import BaseExporter from pretalx.submission.models import", "render(self, **kwargs): content = io.StringIO() writer = csv.DictWriter(content, fieldnames=['name', 'email', 'confirmed']) writer.writeheader() for", "confirmed_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.CONFIRMED ).exists() if not accepted_talks and not confirmed_talks: continue", "state=SubmissionStates.CONFIRMED ).exists() if not accepted_talks and not confirmed_talks: continue writer.writerow( { 'name': speaker.get_display_name(),", "if not accepted_talks and not confirmed_talks: continue writer.writerow( { 'name': speaker.get_display_name(), 'email': speaker.email,", "not confirmed_talks: continue writer.writerow( { 'name': speaker.get_display_name(), 'email': speaker.email, 'confirmed': str(bool(confirmed_talks)), } )", "state=SubmissionStates.ACCEPTED ).exists() confirmed_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.CONFIRMED ).exists() if not accepted_talks and not", ").exists() confirmed_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.CONFIRMED ).exists() if not accepted_talks and not confirmed_talks:", "csv import io from django.utils.translation import ugettext_lazy as _ from pretalx.common.exporter import BaseExporter", "{ 'name': speaker.get_display_name(), 'email': speaker.email, 'confirmed': str(bool(confirmed_talks)), } ) return (f'{self.event.slug}-speakers.csv', 'text/plain', content.getvalue())", "CSVSpeakerExporter(BaseExporter): public = False icon = 'fa-users' identifier = 'speakers.csv' verbose_name = _('Speaker", "import csv import io from django.utils.translation import ugettext_lazy as _ from pretalx.common.exporter import", "in self.event.submitters: accepted_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.ACCEPTED ).exists() confirmed_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.CONFIRMED", "import ugettext_lazy as _ from pretalx.common.exporter import BaseExporter from pretalx.submission.models import SubmissionStates class", "BaseExporter from pretalx.submission.models import SubmissionStates class CSVSpeakerExporter(BaseExporter): public = False icon = 'fa-users'", "= io.StringIO() writer = csv.DictWriter(content, fieldnames=['name', 'email', 'confirmed']) writer.writeheader() for speaker in self.event.submitters:", "writer = csv.DictWriter(content, fieldnames=['name', 'email', 'confirmed']) writer.writeheader() for speaker in self.event.submitters: accepted_talks =", "icon = 'fa-users' identifier = 'speakers.csv' verbose_name = _('Speaker CSV') def render(self, **kwargs):", "pretalx.submission.models import SubmissionStates class CSVSpeakerExporter(BaseExporter): public = False icon = 'fa-users' identifier =", "import io from django.utils.translation import ugettext_lazy as _ from pretalx.common.exporter import BaseExporter from", "for speaker in self.event.submitters: accepted_talks = speaker.submissions.filter( event=self.event, state=SubmissionStates.ACCEPTED ).exists() confirmed_talks = speaker.submissions.filter(" ]
[ "immediately after generation. For example: dj generate command bar dj run manage.py bar", "name. The command can be run immediately after generation. For example: dj generate", "doc): \"\"\"Generate a command with given name. The command can be run immediately", "import inflection @click.command() @click.argument(\"name\") @click.option(\"--doc\") def get_context(name, doc): \"\"\"Generate a command with given", "manage.py bar \"\"\" name = inflection.underscore(name) return {\"name\": name, \"doc\": doc or name}", "with given name. The command can be run immediately after generation. For example:", "after generation. For example: dj generate command bar dj run manage.py bar \"\"\"", "command bar dj run manage.py bar \"\"\" name = inflection.underscore(name) return {\"name\": name,", "dj run manage.py bar \"\"\" name = inflection.underscore(name) return {\"name\": name, \"doc\": doc", "be run immediately after generation. For example: dj generate command bar dj run", "dj generate command bar dj run manage.py bar \"\"\" name = inflection.underscore(name) return", "inflection @click.command() @click.argument(\"name\") @click.option(\"--doc\") def get_context(name, doc): \"\"\"Generate a command with given name.", "@click.argument(\"name\") @click.option(\"--doc\") def get_context(name, doc): \"\"\"Generate a command with given name. The command", "generation. For example: dj generate command bar dj run manage.py bar \"\"\" name", "run manage.py bar \"\"\" name = inflection.underscore(name) return {\"name\": name, \"doc\": doc or", "click import inflection @click.command() @click.argument(\"name\") @click.option(\"--doc\") def get_context(name, doc): \"\"\"Generate a command with", "@click.option(\"--doc\") def get_context(name, doc): \"\"\"Generate a command with given name. The command can", "def get_context(name, doc): \"\"\"Generate a command with given name. The command can be", "The command can be run immediately after generation. For example: dj generate command", "command can be run immediately after generation. For example: dj generate command bar", "example: dj generate command bar dj run manage.py bar \"\"\" name = inflection.underscore(name)", "get_context(name, doc): \"\"\"Generate a command with given name. The command can be run", "@click.command() @click.argument(\"name\") @click.option(\"--doc\") def get_context(name, doc): \"\"\"Generate a command with given name. The", "given name. The command can be run immediately after generation. For example: dj", "import click import inflection @click.command() @click.argument(\"name\") @click.option(\"--doc\") def get_context(name, doc): \"\"\"Generate a command", "command with given name. The command can be run immediately after generation. For", "generate command bar dj run manage.py bar \"\"\" name = inflection.underscore(name) return {\"name\":", "\"\"\"Generate a command with given name. The command can be run immediately after", "a command with given name. The command can be run immediately after generation.", "bar dj run manage.py bar \"\"\" name = inflection.underscore(name) return {\"name\": name, \"doc\":", "run immediately after generation. For example: dj generate command bar dj run manage.py", "For example: dj generate command bar dj run manage.py bar \"\"\" name =", "can be run immediately after generation. For example: dj generate command bar dj" ]
[ "Institute for Snow' in doc.publisher[0] assert '2018' == doc.publication_year assert ['AVALANCHE ACCIDENT STATISTICS',", "(((45.81802, 10.49203), (45.81802, 47.80838), (5.95587, 47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial #", "doc.temporal_coverage_end_date def test_boundingbox(): point_file = os.path.join( TESTDATA_DIR, 'deims', 'raw', '8708dd68-f413-5414-80fb-da439a4224f9.xml') reader = ISO19139Reader()", "in doc.title[0] assert 'Avalanche Warning Service SLF' in doc.creator[0] assert 'WSL Institute for", "(5.95587, 47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa # assert '2018-12-31T00:00:00Z'", "= reader.read(point_file) # <gmd:westBoundLongitude> # <gco:Decimal>34.611499754704</gco:Decimal> # </gmd:westBoundLongitude> # <gmd:eastBoundLongitude> # <gco:Decimal>35.343095815055</gco:Decimal> #", "# <gmd:northBoundLatitude> # <gco:Decimal>30.968572510749</gco:Decimal> # </gmd:northBoundLatitude> assert '(34.611W, 29.491S, 35.343E, 30.969N)' == doc.spatial_coverage", "</gmd:northBoundLatitude> assert '(34.611W, 29.491S, 35.343E, 30.969N)' == doc.spatial_coverage @pytest.mark.xfail(reason='missing in reader') def test_iso19139_temporal_coverage():", "10.49203)),)}\" == doc.spatial # noqa assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_end_date", "for Snow' in doc.publisher[0] assert '2018' == doc.publication_year assert ['AVALANCHE ACCIDENT STATISTICS', 'AVALANCHE", "ISO19139Reader() doc = reader.read(point_file) # assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587 47.80838,", "mdingestion.reader import ISO19139Reader from tests.common import TESTDATA_DIR def test_envidat_iso19139(): point_file = os.path.join( TESTDATA_DIR,", "'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file) assert 'Number of avalanche", "os.path.join( TESTDATA_DIR, 'deims', 'raw', '8708dd68-f413-5414-80fb-da439a4224f9.xml') reader = ISO19139Reader() doc = reader.read(point_file) # <gmd:westBoundLongitude>", "35.343E, 30.969N)' == doc.spatial_coverage @pytest.mark.xfail(reason='missing in reader') def test_iso19139_temporal_coverage(): point_file = os.path.join( TESTDATA_DIR,", "TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file) # assert", "os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file) assert", "# <gco:Decimal>34.611499754704</gco:Decimal> # </gmd:westBoundLongitude> # <gmd:eastBoundLongitude> # <gco:Decimal>35.343095815055</gco:Decimal> # </gmd:eastBoundLongitude> # <gmd:southBoundLatitude> #", "# assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587 47.80838, 5.95587 10.49203, 45.81802 10.49203))\"", "noqa # assert \"{'type': 'Polygon', 'coordinates': (((45.81802, 10.49203), (45.81802, 47.80838), (5.95587, 47.80838), (5.95587,", "def test_boundingbox(): point_file = os.path.join( TESTDATA_DIR, 'deims', 'raw', '8708dd68-f413-5414-80fb-da439a4224f9.xml') reader = ISO19139Reader() doc", "\"{'type': 'Polygon', 'coordinates': (((45.81802, 10.49203), (45.81802, 47.80838), (5.95587, 47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\"", "<gco:Decimal>34.611499754704</gco:Decimal> # </gmd:westBoundLongitude> # <gmd:eastBoundLongitude> # <gco:Decimal>35.343095815055</gco:Decimal> # </gmd:eastBoundLongitude> # <gmd:southBoundLatitude> # <gco:Decimal>29.491402811787</gco:Decimal>", "# </gmd:southBoundLatitude> # <gmd:northBoundLatitude> # <gco:Decimal>30.968572510749</gco:Decimal> # </gmd:northBoundLatitude> assert '(34.611W, 29.491S, 35.343E, 30.969N)'", "'coordinates': (((45.81802, 10.49203), (45.81802, 47.80838), (5.95587, 47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial", "</gmd:eastBoundLongitude> # <gmd:southBoundLatitude> # <gco:Decimal>29.491402811787</gco:Decimal> # </gmd:southBoundLatitude> # <gmd:northBoundLatitude> # <gco:Decimal>30.968572510749</gco:Decimal> # </gmd:northBoundLatitude>", "def test_iso19139_temporal_coverage(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader()", "(45.81802, 10.49203)),)}\" == doc.spatial # noqa assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date assert '2018-12-31T00:00:00Z' ==", "10.49203))\" == doc.spatial_coverage # noqa # assert \"{'type': 'Polygon', 'coordinates': (((45.81802, 10.49203), (45.81802,", "SLF' in doc.creator[0] assert 'WSL Institute for Snow' in doc.publisher[0] assert '2018' ==", "assert 'Number of avalanche fatalities' in doc.title[0] assert 'Avalanche Warning Service SLF' in", "== doc.publication_year assert ['AVALANCHE ACCIDENT STATISTICS', 'AVALANCHE ACCIDENTS', 'AVALANCHE FATALITIES'] == doc.keywords #", "point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc =", "point_file = os.path.join( TESTDATA_DIR, 'deims', 'raw', '8708dd68-f413-5414-80fb-da439a4224f9.xml') reader = ISO19139Reader() doc = reader.read(point_file)", "29.491S, 35.343E, 30.969N)' == doc.spatial_coverage @pytest.mark.xfail(reason='missing in reader') def test_iso19139_temporal_coverage(): point_file = os.path.join(", "FATALITIES'] == doc.keywords # assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587 47.80838, 5.95587", "# assert \"{'type': 'Polygon', 'coordinates': (((45.81802, 10.49203), (45.81802, 47.80838), (5.95587, 47.80838), (5.95587, 10.49203),", "# </gmd:eastBoundLongitude> # <gmd:southBoundLatitude> # <gco:Decimal>29.491402811787</gco:Decimal> # </gmd:southBoundLatitude> # <gmd:northBoundLatitude> # <gco:Decimal>30.968572510749</gco:Decimal> #", "= ISO19139Reader() doc = reader.read(point_file) # <gmd:westBoundLongitude> # <gco:Decimal>34.611499754704</gco:Decimal> # </gmd:westBoundLongitude> # <gmd:eastBoundLongitude>", "((45.81802 10.49203, 45.81802 47.80838, 5.95587 47.80838, 5.95587 10.49203, 45.81802 10.49203))\" == doc.spatial_coverage #", "10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date assert '2018-12-31T00:00:00Z'", "'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file) # assert \"POLYGON", "= ISO19139Reader() doc = reader.read(point_file) # assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587", "ISO19139Reader() doc = reader.read(point_file) # <gmd:westBoundLongitude> # <gco:Decimal>34.611499754704</gco:Decimal> # </gmd:westBoundLongitude> # <gmd:eastBoundLongitude> #", "30.969N)' == doc.spatial_coverage @pytest.mark.xfail(reason='missing in reader') def test_iso19139_temporal_coverage(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139',", "== doc.spatial_coverage @pytest.mark.xfail(reason='missing in reader') def test_iso19139_temporal_coverage(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1',", "# <gmd:southBoundLatitude> # <gco:Decimal>29.491402811787</gco:Decimal> # </gmd:southBoundLatitude> # <gmd:northBoundLatitude> # <gco:Decimal>30.968572510749</gco:Decimal> # </gmd:northBoundLatitude> assert", "pytest from mdingestion.reader import ISO19139Reader from tests.common import TESTDATA_DIR def test_envidat_iso19139(): point_file =", "from mdingestion.reader import ISO19139Reader from tests.common import TESTDATA_DIR def test_envidat_iso19139(): point_file = os.path.join(", "reader = ISO19139Reader() doc = reader.read(point_file) # <gmd:westBoundLongitude> # <gco:Decimal>34.611499754704</gco:Decimal> # </gmd:westBoundLongitude> #", "'Avalanche Warning Service SLF' in doc.creator[0] assert 'WSL Institute for Snow' in doc.publisher[0]", "47.80838, 5.95587 47.80838, 5.95587 10.49203, 45.81802 10.49203))\" == doc.spatial_coverage # noqa # assert", "noqa # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_end_date def test_boundingbox():", "# <gco:Decimal>35.343095815055</gco:Decimal> # </gmd:eastBoundLongitude> # <gmd:southBoundLatitude> # <gco:Decimal>29.491402811787</gco:Decimal> # </gmd:southBoundLatitude> # <gmd:northBoundLatitude> #", "# noqa # assert \"{'type': 'Polygon', 'coordinates': (((45.81802, 10.49203), (45.81802, 47.80838), (5.95587, 47.80838),", "<gco:Decimal>30.968572510749</gco:Decimal> # </gmd:northBoundLatitude> assert '(34.611W, 29.491S, 35.343E, 30.969N)' == doc.spatial_coverage @pytest.mark.xfail(reason='missing in reader')", "import TESTDATA_DIR def test_envidat_iso19139(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader", "= os.path.join( TESTDATA_DIR, 'deims', 'raw', '8708dd68-f413-5414-80fb-da439a4224f9.xml') reader = ISO19139Reader() doc = reader.read(point_file) #", "test_iso19139_temporal_coverage(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc", "= reader.read(point_file) # assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587 47.80838, 5.95587 10.49203,", "'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file) assert 'Number of avalanche fatalities' in", "doc.spatial # noqa # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_end_date", "'AVALANCHE ACCIDENTS', 'AVALANCHE FATALITIES'] == doc.keywords # assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838,", "TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file) assert 'Number", "'2018-12-31T00:00:00Z' == doc.temporal_coverage_end_date def test_boundingbox(): point_file = os.path.join( TESTDATA_DIR, 'deims', 'raw', '8708dd68-f413-5414-80fb-da439a4224f9.xml') reader", "'raw', '8708dd68-f413-5414-80fb-da439a4224f9.xml') reader = ISO19139Reader() doc = reader.read(point_file) # <gmd:westBoundLongitude> # <gco:Decimal>34.611499754704</gco:Decimal> #", "'(34.611W, 29.491S, 35.343E, 30.969N)' == doc.spatial_coverage @pytest.mark.xfail(reason='missing in reader') def test_iso19139_temporal_coverage(): point_file =", "<gmd:eastBoundLongitude> # <gco:Decimal>35.343095815055</gco:Decimal> # </gmd:eastBoundLongitude> # <gmd:southBoundLatitude> # <gco:Decimal>29.491402811787</gco:Decimal> # </gmd:southBoundLatitude> # <gmd:northBoundLatitude>", "import pytest from mdingestion.reader import ISO19139Reader from tests.common import TESTDATA_DIR def test_envidat_iso19139(): point_file", "doc = reader.read(point_file) # assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587 47.80838, 5.95587", "Warning Service SLF' in doc.creator[0] assert 'WSL Institute for Snow' in doc.publisher[0] assert", "(45.81802, 47.80838), (5.95587, 47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa #", "assert 'WSL Institute for Snow' in doc.publisher[0] assert '2018' == doc.publication_year assert ['AVALANCHE", "'2018' == doc.publication_year assert ['AVALANCHE ACCIDENT STATISTICS', 'AVALANCHE ACCIDENTS', 'AVALANCHE FATALITIES'] == doc.keywords", "= ISO19139Reader() doc = reader.read(point_file) assert 'Number of avalanche fatalities' in doc.title[0] assert", "\"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587 47.80838, 5.95587 10.49203, 45.81802 10.49203))\" == doc.spatial_coverage", "from tests.common import TESTDATA_DIR def test_envidat_iso19139(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml',", "os import pytest from mdingestion.reader import ISO19139Reader from tests.common import TESTDATA_DIR def test_envidat_iso19139():", "STATISTICS', 'AVALANCHE ACCIDENTS', 'AVALANCHE FATALITIES'] == doc.keywords # assert \"POLYGON ((45.81802 10.49203, 45.81802", "# <gco:Decimal>30.968572510749</gco:Decimal> # </gmd:northBoundLatitude> assert '(34.611W, 29.491S, 35.343E, 30.969N)' == doc.spatial_coverage @pytest.mark.xfail(reason='missing in", "== doc.temporal_coverage_begin_date # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_end_date def test_boundingbox(): point_file = os.path.join( TESTDATA_DIR,", "assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_end_date def test_boundingbox(): point_file = os.path.join( TESTDATA_DIR, 'deims', 'raw', '8708dd68-f413-5414-80fb-da439a4224f9.xml')", "doc.spatial_coverage @pytest.mark.xfail(reason='missing in reader') def test_iso19139_temporal_coverage(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml',", "fatalities' in doc.title[0] assert 'Avalanche Warning Service SLF' in doc.creator[0] assert 'WSL Institute", "avalanche fatalities' in doc.title[0] assert 'Avalanche Warning Service SLF' in doc.creator[0] assert 'WSL", "reader.read(point_file) # assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587 47.80838, 5.95587 10.49203, 45.81802", "= reader.read(point_file) assert 'Number of avalanche fatalities' in doc.title[0] assert 'Avalanche Warning Service", "doc.spatial_coverage # noqa # assert \"{'type': 'Polygon', 'coordinates': (((45.81802, 10.49203), (45.81802, 47.80838), (5.95587,", "in reader') def test_iso19139_temporal_coverage(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader", "'8708dd68-f413-5414-80fb-da439a4224f9.xml') reader = ISO19139Reader() doc = reader.read(point_file) # <gmd:westBoundLongitude> # <gco:Decimal>34.611499754704</gco:Decimal> # </gmd:westBoundLongitude>", "10.49203)),)}\" == doc.spatial # noqa # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date # assert '2018-12-31T00:00:00Z'", "# <gco:Decimal>29.491402811787</gco:Decimal> # </gmd:southBoundLatitude> # <gmd:northBoundLatitude> # <gco:Decimal>30.968572510749</gco:Decimal> # </gmd:northBoundLatitude> assert '(34.611W, 29.491S,", "(45.81802, 10.49203)),)}\" == doc.spatial # noqa # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date # assert", "10.49203, 45.81802 10.49203))\" == doc.spatial_coverage # noqa # assert \"{'type': 'Polygon', 'coordinates': (((45.81802,", "doc.creator[0] assert 'WSL Institute for Snow' in doc.publisher[0] assert '2018' == doc.publication_year assert", "'2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_end_date def test_boundingbox(): point_file = os.path.join(", "== doc.spatial_coverage # noqa # assert \"{'type': 'Polygon', 'coordinates': (((45.81802, 10.49203), (45.81802, 47.80838),", "'Number of avalanche fatalities' in doc.title[0] assert 'Avalanche Warning Service SLF' in doc.creator[0]", "45.81802 47.80838, 5.95587 47.80838, 5.95587 10.49203, 45.81802 10.49203))\" == doc.spatial_coverage # noqa #", "'deims', 'raw', '8708dd68-f413-5414-80fb-da439a4224f9.xml') reader = ISO19139Reader() doc = reader.read(point_file) # <gmd:westBoundLongitude> # <gco:Decimal>34.611499754704</gco:Decimal>", "import os import pytest from mdingestion.reader import ISO19139Reader from tests.common import TESTDATA_DIR def", "TESTDATA_DIR def test_envidat_iso19139(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader =", "<gmd:northBoundLatitude> # <gco:Decimal>30.968572510749</gco:Decimal> # </gmd:northBoundLatitude> assert '(34.611W, 29.491S, 35.343E, 30.969N)' == doc.spatial_coverage @pytest.mark.xfail(reason='missing", "ISO19139Reader() doc = reader.read(point_file) assert 'Number of avalanche fatalities' in doc.title[0] assert 'Avalanche", "45.81802 10.49203))\" == doc.spatial_coverage # noqa # assert \"{'type': 'Polygon', 'coordinates': (((45.81802, 10.49203),", "10.49203), (45.81802, 47.80838), (5.95587, 47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa", "def test_envidat_iso19139(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader()", "['AVALANCHE ACCIDENT STATISTICS', 'AVALANCHE ACCIDENTS', 'AVALANCHE FATALITIES'] == doc.keywords # assert \"POLYGON ((45.81802", "<reponame>cehbrecht/md-ingestion<gh_stars>1-10 import os import pytest from mdingestion.reader import ISO19139Reader from tests.common import TESTDATA_DIR", "reader.read(point_file) # <gmd:westBoundLongitude> # <gco:Decimal>34.611499754704</gco:Decimal> # </gmd:westBoundLongitude> # <gmd:eastBoundLongitude> # <gco:Decimal>35.343095815055</gco:Decimal> # </gmd:eastBoundLongitude>", "TESTDATA_DIR, 'deims', 'raw', '8708dd68-f413-5414-80fb-da439a4224f9.xml') reader = ISO19139Reader() doc = reader.read(point_file) # <gmd:westBoundLongitude> #", "# noqa # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_end_date def", "os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file) #", "'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file) # assert \"POLYGON ((45.81802", "</gmd:southBoundLatitude> # <gmd:northBoundLatitude> # <gco:Decimal>30.968572510749</gco:Decimal> # </gmd:northBoundLatitude> assert '(34.611W, 29.491S, 35.343E, 30.969N)' ==", "assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587 47.80838, 5.95587 10.49203, 45.81802 10.49203))\" ==", "47.80838), (5.95587, 47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa # assert", "# </gmd:westBoundLongitude> # <gmd:eastBoundLongitude> # <gco:Decimal>35.343095815055</gco:Decimal> # </gmd:eastBoundLongitude> # <gmd:southBoundLatitude> # <gco:Decimal>29.491402811787</gco:Decimal> #", "in doc.publisher[0] assert '2018' == doc.publication_year assert ['AVALANCHE ACCIDENT STATISTICS', 'AVALANCHE ACCIDENTS', 'AVALANCHE", "# </gmd:northBoundLatitude> assert '(34.611W, 29.491S, 35.343E, 30.969N)' == doc.spatial_coverage @pytest.mark.xfail(reason='missing in reader') def", "test_boundingbox(): point_file = os.path.join( TESTDATA_DIR, 'deims', 'raw', '8708dd68-f413-5414-80fb-da439a4224f9.xml') reader = ISO19139Reader() doc =", "10.49203, 45.81802 47.80838, 5.95587 47.80838, 5.95587 10.49203, 45.81802 10.49203))\" == doc.spatial_coverage # noqa", "'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file) assert 'Number of avalanche fatalities'", "doc.publication_year assert ['AVALANCHE ACCIDENT STATISTICS', 'AVALANCHE ACCIDENTS', 'AVALANCHE FATALITIES'] == doc.keywords # assert", "doc.publisher[0] assert '2018' == doc.publication_year assert ['AVALANCHE ACCIDENT STATISTICS', 'AVALANCHE ACCIDENTS', 'AVALANCHE FATALITIES']", "# <gmd:westBoundLongitude> # <gco:Decimal>34.611499754704</gco:Decimal> # </gmd:westBoundLongitude> # <gmd:eastBoundLongitude> # <gco:Decimal>35.343095815055</gco:Decimal> # </gmd:eastBoundLongitude> #", "== doc.keywords # assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587 47.80838, 5.95587 10.49203,", "assert \"{'type': 'Polygon', 'coordinates': (((45.81802, 10.49203), (45.81802, 47.80838), (5.95587, 47.80838), (5.95587, 10.49203), (45.81802,", "== doc.temporal_coverage_end_date def test_boundingbox(): point_file = os.path.join( TESTDATA_DIR, 'deims', 'raw', '8708dd68-f413-5414-80fb-da439a4224f9.xml') reader =", "= os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file)", "'Polygon', 'coordinates': (((45.81802, 10.49203), (45.81802, 47.80838), (5.95587, 47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\" ==", "'AVALANCHE FATALITIES'] == doc.keywords # assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587 47.80838,", "assert '(34.611W, 29.491S, 35.343E, 30.969N)' == doc.spatial_coverage @pytest.mark.xfail(reason='missing in reader') def test_iso19139_temporal_coverage(): point_file", "reader = ISO19139Reader() doc = reader.read(point_file) assert 'Number of avalanche fatalities' in doc.title[0]", "'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file) assert 'Number of", "47.80838, 5.95587 10.49203, 45.81802 10.49203))\" == doc.spatial_coverage # noqa # assert \"{'type': 'Polygon',", "doc.temporal_coverage_begin_date # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_end_date def test_boundingbox(): point_file = os.path.join( TESTDATA_DIR, 'deims',", "(5.95587, 47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa assert '2018-12-31T00:00:00Z' ==", "# <gmd:eastBoundLongitude> # <gco:Decimal>35.343095815055</gco:Decimal> # </gmd:eastBoundLongitude> # <gmd:southBoundLatitude> # <gco:Decimal>29.491402811787</gco:Decimal> # </gmd:southBoundLatitude> #", "47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa # assert '2018-12-31T00:00:00Z' ==", "assert '2018' == doc.publication_year assert ['AVALANCHE ACCIDENT STATISTICS', 'AVALANCHE ACCIDENTS', 'AVALANCHE FATALITIES'] ==", "reader = ISO19139Reader() doc = reader.read(point_file) # assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838,", "of avalanche fatalities' in doc.title[0] assert 'Avalanche Warning Service SLF' in doc.creator[0] assert", "reader.read(point_file) assert 'Number of avalanche fatalities' in doc.title[0] assert 'Avalanche Warning Service SLF'", "assert 'Avalanche Warning Service SLF' in doc.creator[0] assert 'WSL Institute for Snow' in", "Snow' in doc.publisher[0] assert '2018' == doc.publication_year assert ['AVALANCHE ACCIDENT STATISTICS', 'AVALANCHE ACCIDENTS',", "test_envidat_iso19139(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc", "(5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date", "5.95587 10.49203, 45.81802 10.49203))\" == doc.spatial_coverage # noqa # assert \"{'type': 'Polygon', 'coordinates':", "47.80838), (5.95587, 47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa assert '2018-12-31T00:00:00Z'", "reader') def test_iso19139_temporal_coverage(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader =", "ISO19139Reader from tests.common import TESTDATA_DIR def test_envidat_iso19139(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1',", "doc.title[0] assert 'Avalanche Warning Service SLF' in doc.creator[0] assert 'WSL Institute for Snow'", "'WSL Institute for Snow' in doc.publisher[0] assert '2018' == doc.publication_year assert ['AVALANCHE ACCIDENT", "doc.keywords # assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587 47.80838, 5.95587 10.49203, 45.81802", "<gco:Decimal>35.343095815055</gco:Decimal> # </gmd:eastBoundLongitude> # <gmd:southBoundLatitude> # <gco:Decimal>29.491402811787</gco:Decimal> # </gmd:southBoundLatitude> # <gmd:northBoundLatitude> # <gco:Decimal>30.968572510749</gco:Decimal>", "doc = reader.read(point_file) assert 'Number of avalanche fatalities' in doc.title[0] assert 'Avalanche Warning", "'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file) # assert \"POLYGON ((45.81802 10.49203, 45.81802", "(5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date assert", "ACCIDENT STATISTICS', 'AVALANCHE ACCIDENTS', 'AVALANCHE FATALITIES'] == doc.keywords # assert \"POLYGON ((45.81802 10.49203,", "assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_end_date def test_boundingbox(): point_file =", "5.95587 47.80838, 5.95587 10.49203, 45.81802 10.49203))\" == doc.spatial_coverage # noqa # assert \"{'type':", "ACCIDENTS', 'AVALANCHE FATALITIES'] == doc.keywords # assert \"POLYGON ((45.81802 10.49203, 45.81802 47.80838, 5.95587", "<gmd:southBoundLatitude> # <gco:Decimal>29.491402811787</gco:Decimal> # </gmd:southBoundLatitude> # <gmd:northBoundLatitude> # <gco:Decimal>30.968572510749</gco:Decimal> # </gmd:northBoundLatitude> assert '(34.611W,", "import ISO19139Reader from tests.common import TESTDATA_DIR def test_envidat_iso19139(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139',", "<gmd:westBoundLongitude> # <gco:Decimal>34.611499754704</gco:Decimal> # </gmd:westBoundLongitude> # <gmd:eastBoundLongitude> # <gco:Decimal>35.343095815055</gco:Decimal> # </gmd:eastBoundLongitude> # <gmd:southBoundLatitude>", "Service SLF' in doc.creator[0] assert 'WSL Institute for Snow' in doc.publisher[0] assert '2018'", "tests.common import TESTDATA_DIR def test_envidat_iso19139(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml')", "@pytest.mark.xfail(reason='missing in reader') def test_iso19139_temporal_coverage(): point_file = os.path.join( TESTDATA_DIR, 'envidat-iso19139', 'SET_1', 'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml')", "<gco:Decimal>29.491402811787</gco:Decimal> # </gmd:southBoundLatitude> # <gmd:northBoundLatitude> # <gco:Decimal>30.968572510749</gco:Decimal> # </gmd:northBoundLatitude> assert '(34.611W, 29.491S, 35.343E,", "47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date", "# assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_end_date def test_boundingbox(): point_file = os.path.join( TESTDATA_DIR, 'deims', 'raw',", "doc = reader.read(point_file) # <gmd:westBoundLongitude> # <gco:Decimal>34.611499754704</gco:Decimal> # </gmd:westBoundLongitude> # <gmd:eastBoundLongitude> # <gco:Decimal>35.343095815055</gco:Decimal>", "10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date #", "'xml', 'bbox_2ea750c6-4354-5f0a-9b67-2275d922d06f.xml') reader = ISO19139Reader() doc = reader.read(point_file) # assert \"POLYGON ((45.81802 10.49203,", "in doc.creator[0] assert 'WSL Institute for Snow' in doc.publisher[0] assert '2018' == doc.publication_year", "</gmd:westBoundLongitude> # <gmd:eastBoundLongitude> # <gco:Decimal>35.343095815055</gco:Decimal> # </gmd:eastBoundLongitude> # <gmd:southBoundLatitude> # <gco:Decimal>29.491402811787</gco:Decimal> # </gmd:southBoundLatitude>", "# assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_end_date def test_boundingbox(): point_file", "(45.81802, 47.80838), (5.95587, 47.80838), (5.95587, 10.49203), (45.81802, 10.49203)),)}\" == doc.spatial # noqa assert", "assert ['AVALANCHE ACCIDENT STATISTICS', 'AVALANCHE ACCIDENTS', 'AVALANCHE FATALITIES'] == doc.keywords # assert \"POLYGON", "== doc.spatial # noqa # assert '2018-12-31T00:00:00Z' == doc.temporal_coverage_begin_date # assert '2018-12-31T00:00:00Z' ==" ]
[ "image if ``True`` (default is ``False``). show : boolean, optional Show the image", "Getch() while True: ch = getch() if ch not in keys2translation.keys(): break while", "b - 1: translate('Z-') break translate('Y+P', confirm) y += 1 # To the", "produce the trajectory of the tool printing the image. ''' # Standard library", "system. printerc drives printerm through mcircuit; printerc stablishes a serial connection with mcircuit,", "a time. Parameters ---------- adm: str *adm* stands for Axis, Direction, Mode. Use", "subroutine_key: subroutine_body = subroutine_body.format(ntransitions=ntransitions) print >>f, subroutine_body def prepare_img(imgpath, invert=False, show=False): '''Perform any", ": 'X+p', 'j' : 'Y+p', 'k' : 'Y-p', 'i' : 'Z+', 'o' :", "sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: '''Windows implementation of class", "optional If ``True``, the user must confirm the translation by pressing Enter (default", "cm # Same as **printer73x**. __version__ = '0.09' # GLOBAL CONSTANT names. *if", "as plt import matplotlib.cm as cm # Same as **printer73x**. __version__ = '0.09'", "or :math:`Y` axes.''' SRV_SIGNAL_CHANNEL_TARGET_OFF = 940 ''':math:`Z` axis servo motor pulse width in", "virtual serial ports. Returns ------- available : list of tuples Each element of", "``False`` perform translation in units of pixels (default is True). ''' if precise:", "try: print >>logf, 'Closing ``{0}`` *command port*'.format(sp.port) sp.close() except NameError: pass print >>logf,", "corresponding pixel is black then the tool prints it. ''' def report_position(x, y):", "invert=False, show=False): '''Perform any necessary processing for the input image to be reproduced", ": 1, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_pos_pulse', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X-P'", "__call__(self): return self.impl() class _GetchUnix: '''Unix implementation of class ``Getch``.''' def __init__(self): import", "servo # set direction begin dup while {off} {step_channel} servo {{delay}} delay {on}", "'X-p', 'l' : 'X+p', 'j' : 'Y+p', 'k' : 'Y-p', 'i' : 'Z+',", "with open(fpath, 'w') as f: print >>f, MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration, servo_speed=servo_speed) for i in range(len(", "position (:math:`Z`). ``Z+`` move the tool to the on position (:math:`Z`). ======= ================================================================", "while True: report_position(x, y) print_img_pixel(x, y, confirm) if x == 0: break translate('X-P',", "== b - 1: translate('Z-') break translate('Y+P', confirm) y += 1 # To", "'Closing ``{0}`` *command port*'.format(sp.port) sp.close() except NameError: pass print >>logf, 'END' logf.close() print", "units of pixels,''' SUB_STEPPER_PULSE_TEMPLATE = '''sub {name} {dir} {dir_channel} servo # set direction", "translation across :math:`Y`. ``Z-`` move the tool to the off position (:math:`Z`). ``Z+``", "boolean, optional If ``True``, the user must confirm the translation by pressing Enter", "print 'Operation interrupted, flushing command port' def print_image_better_better(confirm=False): '''Automatically print the input image.", "x += 1 print 'Returning to a_{{{0}, 0}}'.format(y) while True: if x ==", "across the :math:`X` or :math:`Y` axes.''' TRANSITIONS_PER_PIXEL = STEPS_PER_PIXEL * TRANSITIONS_PER_STEP '''Number of", "2 #if 'Z' in adm: #time.sleep(0.1) def build_mm12_script(fpath, ntransitions=TRANSITIONS_PER_PIXEL, delay=1, servo_acceleration=0, servo_speed=100): '''Build", "sp.flush() print 'Operation interrupted, flushing command port' def print_image_better_better(confirm=False): '''Automatically print the input", "# wait until is is no longer moving. repeat 75 delay quit '''", "rows and {1} columns'.format(b, w) print msg x = y = 0 #", "perform (where :math:`n` is the number of pulses for the printerm tool to", "mcircuit). If ``False`` perform translation in units of pixels (default is True). '''", "========================================================================== # ========================================================================== LOGF = 'log.rst' '''Path to the log file.''' INTRO_MSG =", "sets the microstepping format with the jumpers *MS1* and *MS2*. Use the following", "of the MM12 channels for the servo and stepper motors outputs.''' SUB_STEPPER_PIXEL_TEMPLATE =", "from the HOME position the printerm tool visit every element of the row", "the row {0}'.format(y) while True: report_position(x, y) print_img_pixel(x, y, confirm) if x ==", "XMS1, XMS2, YMS1, YMS2 jumpers in mcircuit). If ``False`` perform translation in units", "import gc import time # Related third party imports. import serial import IPython", "tool to the off position (:math:`Z`). ``Z+`` move the tool to the on", "disconnected 8 ============ ============ =============== .. note:: Both stepper motor driver boards must", "============ ============ =============== .. note:: Both stepper motor driver boards must have the", "range(w): if img[i][j] < 0.9: img[i][j] = 0.0 else: img[i][j] = 1.0 if", "y == 0: break translate('Y-P', confirm) y -= 1 while True: if x", "if 'Z' not in subroutine_key: subroutine_body = subroutine_body.format(delay=delay) if 'P' in subroutine_key: subroutine_body", "same jumper configuration. ''' STEPS_PER_PIXEL = 90 '''Number of steps the stepper motor", "range(b): for j in range(w): if img[i][j] > 0.0: nnotprints += 1 else:", "in its memory the routines that correspond to the translations across the :math:`X`,", "= '''\\ **printerc** Welcome! ''' '''Welcome message for command line interface.''' # MM12", "'h' : 'X-P', 'l' : 'X+P', 'j' : 'Y+P', 'k' : 'Y-P', 'i'", "__call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno())", "'''Welcome message for command line interface.''' # MM12 # ========================================================================== TRANSITIONS_PER_STEP = 2", "input image. Starting from the HOME position the printerm tool visit every element", "negative translation across :math:`Y`. ``Y+P`` send :math:`n` pulses for positive translation across :math:`Y`.", "at a time. Parameters ---------- adm: str *adm* stands for Axis, Direction, Mode.", "while mm12_script_status() == MM12_SCRIPT_RUNNING: pass subroutine_id = chr( MM12_SUBROUTINES[adm]['subroutine_id']) str2write = ''.join(['\\xa7', subroutine_id])", "''' # Start until script is not running. while mm12_script_status() == MM12_SCRIPT_RUNNING: pass", "image if ``True`` (default is ``False``). Notes ----- This function sets the following", "of steps the stepper motor needs to translate 1 pixel across the :math:`X`", ": int, optional Number of low-to-high transitions to perform in the subroutines that", "width in units of quarter-:math:`\\\\mu s` that enables printing (moves the tool down).'''", "name='y_pos_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Z-' : { 'subroutine_id' :", "transition in the subroutines that perform translation through the stepper motors (default is", "}, } '''Configuration of the MM12 channels for the servo and stepper motors", "1 assert (nnotprints + nprints) == npixels # If ``nprints == 0`` then", "STEPPER_CHANNELS_TARGET_ON, 'dir_negative' : STEPPER_CHANNELS_TARGET_OFF, 'step_channel': 3, }, 'Z' : { 'channel' : 4,", "the number of pulses for the printerm tool to translate a pixel unit", "visit every element of the row from :math:`a_{0,0}` to :math:`a_{0,w-1}` then moves to", "the stepper motor drivers (how much the tool is translated depends on the", "from `pyserial <http://sourceforge.net/projects/pyserial/files/package>`_ project. ''' available = [] for i in range(256): try:", ": int, optional Sets the speed of the servo signal channel in units", "=============== .. note:: Both stepper motor driver boards must have the same jumper", "1 return sp.read(1) def translate(adm, confirm=False): '''Translate the printerm tool across the :math:`XYZ`", "---------- fpath : str-like Path location where to save the script file. ntransitions", "be printed. assert nprints > 0 print 'Loaded ``{0}`` with {1} pixels, {2}", "1: break translate('X+P', confirm) x += 1 if y == b - 1:", "select the kind of translation you want to perform (where :math:`n` is the", "to the on position (:math:`Z`). ======= ================================================================ confirm: boolean, optional If ``True``, the", "= serial.Serial(port=commandport_id) assert sp.isOpen() print >>logf, '``{0}`` just opened *command port* ``{1}``'.format(PN, sp.port)", "scan_serial_ports(): '''Scan system for available physical or virtual serial ports. Returns ------- available", "visit. In any position, if the corresponding pixel is black then the tool", "__init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return", "''' if precise: keys2translation = { 'h' : 'X-p', 'l' : 'X+p', 'j'", "number and name of the port. Notes ----- Directly copied from example from", "for Axis, Direction, Mode. Use the following table to select the kind of", "# Check for pixel with and without color. for i in range(b): for", "where to save the script file. ntransitions : int, optional Number of low-to-high", "XMS2, YMS1, YMS2 jumpers in mcircuit). If ``False`` perform translation in units of", "if x == w - 1: break translate('X+P', confirm) x += 1 print", ": 9, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_on', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['on']*4) }, } '''Structure that builds", "in range(b): for j in range(w): if img[i][j] > 0.0: nnotprints += 1", "SUB_STEPPER_PULSE_TEMPLATE.format( name='x_pos_pulse', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X-P' : { 'subroutine_id' :", "import pprint import sys import os import atexit import gc import time #", "or stopped. Returns ------- script_status : {``MM12_SCRIPT_RUNNING``, ``MM12_SCRIPT_STOPPED``} ''' assert sp.write('\\xae') == 1", "def __call__(self): import msvcrt return msvcrt.getch() def on_exit(): '''Actions to do on exit.'''", "the input image. #. :math:`a_{b-1,w-1}` corresponds to the lower right corner of the", "== w - 1: break translate('X+P', confirm) x += 1 print 'Returning to", "= MM12_SUBROUTINES[subroutine_key]['subroutine_body'] if 'Z' not in subroutine_key: subroutine_body = subroutine_body.format(delay=delay) if 'P' in", "motor in units of low-to-high transitions, for a precise but slow translation.''' SUB_SERVO_TEMPLATE", ">>f, msg def manual_translation_mode(precise=True): '''Manually translate the printerm tool across the :math:`XY` plane.", "x += 1 if y == b - 1: translate('Z-') break translate('Y+P', confirm)", "list is a ``(num, name)`` tuple with the number and name of the", "'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_on', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['on']*4) }, } '''Structure that builds and identifies", "'w') as f: print >>f, MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration, servo_speed=servo_speed) for i in range(len( MM12_SUBROUTINES)): subroutine_key", ": SUB_STEPPER_PULSE_TEMPLATE.format( name='x_pos_pulse', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X-P' : { 'subroutine_id'", "'''Manually translate the printerm tool across the :math:`XY` plane. Parameters ---------- precise :", ":math:`X`, :math:`Y` and :math:`Z` axis, and then printerc execute these routines in order", "print 'Operation interrupted, flushing command port' if __name__ == \"__main__\": # program name", "names too. # ========================================================================== # ========================================================================== LOGF = 'log.rst' '''Path to the log", "if x == 0: translate('Z-') break translate('X-P', confirm) x -= 1 if y", "keys2translation = { 'h' : 'X-P', 'l' : 'X+P', 'j' : 'Y+P', 'k'", "to a_{{{0}, 0}}'.format(y) while True: if x == 0: break translate('X-P', confirm) x", "matplotlib.cm as cm # Same as **printer73x**. __version__ = '0.09' # GLOBAL CONSTANT", ": { 'subroutine_id' : 6, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_neg_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'],", "SUB_STEPPER_PIXEL_TEMPLATE = '''sub {name} {{{{ntransitions}}}} {dir} {dir_channel} servo # set direction begin dup", "right corner of the input image. Starting from the HOME position the printerm", "print >>f, MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration, servo_speed=servo_speed) for i in range(len( MM12_SUBROUTINES)): subroutine_key = get_subroutine_key_by_id(i) subroutine_body", "while mm12_script_status() == MM12_SCRIPT_RUNNING: pass translate(keys2translation[ch], confirm=False) def print_pixel(confirm=False): if confirm: raw_input() translate('Z+',", "get_subroutine_key_by_id(subroutine_id): for key, value in MM12_SUBROUTINES.items(): if subroutine_id is value['subroutine_id']: return key for", "assert sp.isOpen() print >>logf, '``{0}`` just opened *command port* ``{1}``'.format(PN, sp.port) msg =", "__version__ = '0.09' # GLOBAL CONSTANT names. *if main* section at bottom sets", "``True`` (default is ``False``). Notes ----- This function sets the following global names:", "__init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno()", "begin dup while {off} {step_channel} servo {{delay}} delay {on} {step_channel} servo {{delay}} delay", "moves to the next row (:math:`a_{1,w-1}`) and visits every element of the row", "send 1 single pulse for negative translation across :math:`Y`. ``Y+p`` send 1 single", "the following table to select the kind of translation you want to perform", "is 0). servo_speed : int, optional Sets the speed of the servo signal", "MM12 # ========================================================================== TRANSITIONS_PER_STEP = 2 '''The board sets the microstepping format with", "0). servo_speed : int, optional Sets the speed of the servo signal channel", "of pixels (default is True). ''' if precise: keys2translation = { 'h' :", "mm12_script_status() == MM12_SCRIPT_RUNNING: pass subroutine_id = chr( MM12_SUBROUTINES[adm]['subroutine_id']) str2write = ''.join(['\\xa7', subroutine_id]) if", "for positive translation across :math:`Y`. ``Y-P`` send :math:`n` pulses for negative translation across", "YMS2 jumpers in mcircuit). If ``False`` perform translation in units of pixels (default", "units of (0.25 us)/(10 ms) (default is 100). ''' def get_subroutine_key_by_id(subroutine_id): for key,", "SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_neg_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y+P' : { 'subroutine_id'", "'subroutine_id' : 9, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_on', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['on']*4) }, } '''Structure that", ": str or int Serial device name or port number number of the", "msg = '``{0}`` is now connected to ``printerm`` through ``{1}``'.format( PN, sp.port) for", "if y == 0: break translate('Y-P', confirm) y -= 1 print 'The image", "for j in range(w): if img[i][j] < 0.9: img[i][j] = 0.0 else: img[i][j]", "is not running. while mm12_script_status() == MM12_SCRIPT_RUNNING: pass subroutine_id = chr( MM12_SUBROUTINES[adm]['subroutine_id']) str2write", "self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: '''Unix implementation of class", "in the array representation. ''' global img, b, w print 'Loading ``{0}``...'.format(imgpath) img", "on the MM12. Parameters ---------- fpath : str-like Path location where to save", "range(b): for j in range(w): if img[i][j] > 0.0: img[i][j] = 0.0 else:", "only total black and white, no grays. for i in range(b): for j", "- 1: translate('Z-') break translate('Y+P', confirm) y += 1 # To the left.", "'Inverting image...' for i in range(b): for j in range(w): if img[i][j] >", "been printed' except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' def print_image_better_better(confirm=False):", "connected 1 disconnected connected 2 connected disconnected 4 disconnected disconnected 8 ============ ============", "s.portstr)) s.close() except serial.SerialException: pass return available def mm12_script_status(): '''Indicate whether the MM12", "drive a stepper motor in units of pixels,''' SUB_STEPPER_PULSE_TEMPLATE = '''sub {name} {dir}", "{ 'subroutine_id' : 8, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_off', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['off']*4) }, 'Z+' :", "ch = getch() if ch not in keys2translation.keys(): break while mm12_script_status() == MM12_SCRIPT_RUNNING:", "right. print 'Printing across the row {0}'.format(y) while True: report_position(x, y) if img[y][x]", "print_img_pixel(x, y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm) try: msg = 'Preparing to", "the acceleration of the servo signal channel in units of (0.25 us)/(10 ms)/(80", "'Operation interrupted, flushing command port' def print_image_better_better(confirm=False): '''Automatically print the input image. Parameters", "sp.close() except NameError: pass print >>logf, 'END' logf.close() print '\\nThanks for using ``printerc``!\\n'", "the script is running.''' MM12_SCRIPT_STOPPED = '\\x01' '''Byte value that the MM12 returns", "0 print 'Loaded ``{0}`` with {1} pixels, {2} of which have color'.format( imgpath,", "servo_speed=100): '''Build a script to be loaded on the MM12. Parameters ---------- fpath", "to printerm through the motors. mcircuit (actually MM12, its subsystem) loads in its", "1, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_pos_pulse', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X-P' :", "to print an image with {0} rows and {1} columns'.format(b, w) print msg", "Serial device name or port number number of the MM12 serial command port.", "and {1} columns'.format(b, w) print msg x = y = 0 # We", "Parameters ---------- imgpath : str-like Path to the image file. Must be PNG,", "STEPS_PER_PIXEL * TRANSITIONS_PER_STEP '''Number of low-to-high transitions the stepper motors need to translate", "'i' : 'Z+', 'o' : 'Z-', } getch = Getch() while True: ch", ": 5, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_pos_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y-P'", "transitions to perform in the subroutines that performs translation in units of pixels", "on=STEPPER_CHANNELS_TARGET_ON ), }, 'Z-' : { 'subroutine_id' : 8, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_off',", "i in range(b): for j in range(w): if img[i][j] > 0.0: nnotprints +=", "off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X+p' : { 'subroutine_id' : 1, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format(", "w) print msg x = y = 0 # We are at HOME", "= 'Preparing to print an image with {0} rows and {1} columns'.format(b, w)", "{1} pixels, {2} of which have color'.format( imgpath, npixels, nprints) plt.close('all') if show:", "# We are at HOME position. while True: print 'Printing across the row", "on until there are no more rows to visit. In any position, if", "ntransitions : int, optional Number of low-to-high transitions to perform in the subroutines", "of the servo signal channel in units of (0.25 us)/(10 ms) (default is", "range(b): for j in range(w): if img[i][j] < 0.9: img[i][j] = 0.0 else:", "in range(w): if img[i][j] > 0.0: img[i][j] = 0.0 else: img[i][j] = 1.0", "msg x = y = 0 # We are at HOME position. while", "translated depends on the microstep format selected through the XMS1, XMS2, YMS1, YMS2", ": 2, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_neg_pixel', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), },", "SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_neg_pixel', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'X+P' : { 'subroutine_id'", "name)`` tuple with the number and name of the port. Notes ----- Directly", "'''sub {name} {{{{ntransitions}}}} {dir} {dir_channel} servo # set direction begin dup while {off}", "flushing command port' def print_image_better(confirm=False): def report_position(x, y): print 'At row {0}, column", "send :math:`n` pulses for positive translation across :math:`Y`. ``Z-`` move the tool to", "'\\x00' '''Byte value that the MM12 returns when the script is running.''' MM12_SCRIPT_STOPPED", "the jumpers *MS1* and *MS2*. Use the following table to set this constant:", "of quarter-:math:`\\\\mu s` that drives the stepper channels low.''' MM12_AXES_CHANNELS = { 'X'", "name of the port. Notes ----- Directly copied from example from `pyserial <http://sourceforge.net/projects/pyserial/files/package>`_", "prepare_img(imgpath, invert=False, show=False): '''Perform any necessary processing for the input image to be", "device name or port number number of the MM12 serial command port. '''", "row {0}'.format(y) while True: report_position(x, y) print_img_pixel(x, y, confirm) if x == w", "confirm) if x == 0: break translate('X-P', confirm) x -= 1 if y", ":math:`Y`. ``Y-P`` send :math:`n` pulses for negative translation across :math:`Y`. ``Y+P`` send :math:`n`", "quarter-:math:`\\\\mu s` that drives the stepper channels high.''' STEPPER_CHANNELS_TARGET_OFF = 5600 '''Target value", "columns'.format(b, w) print msg x = y = 0 # We are at", "np # remove import matplotlib.image as mpimg import matplotlib.pyplot as plt import matplotlib.cm", "img, b, w print 'Loading ``{0}``...'.format(imgpath) img = mpimg.imread(fname=imgpath, format='png') b, w =", "---------- adm: str *adm* stands for Axis, Direction, Mode. Use the following table", "available : list of tuples Each element of the list is a ``(num,", "until is is no longer moving. repeat 75 delay quit ''' '''Template for", "interrupted, flushing command port' def print_image_better(confirm=False): def report_position(x, y): print 'At row {0},", "img[y][x-1] != 0.0: translate('Z-', confirm) if x == 0: translate('Z-') break translate('X-P', confirm)", "{{delay}} delay {on} {step_channel} servo {{delay}} delay 1 minus repeat quit ''' '''Template", "name='x_pos_pulse', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X-P' : { 'subroutine_id' : 2,", "pulses for positive translation across :math:`X`. ``Y-p`` send 1 single pulse for negative", "printerm through the motors. mcircuit (actually MM12, its subsystem) loads in its memory", "the trajectory of the tool printing the image. ''' # Standard library imports.", "``Z-`` move the tool to the off position (:math:`Z`). ``Z+`` move the tool", "(w > 0) print 'Processing the image...' # only total black and white,", "{1} columns'.format(b, w) print msg x = y = z = 0 #", "1.0 # Check for pixel with and without color. for i in range(b):", "**printerc** Welcome! ''' '''Welcome message for command line interface.''' # MM12 # ==========================================================================", "), }, 'Z-' : { 'subroutine_id' : 8, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_off', channel=MM12_AXES_CHANNELS['Z']['channel'],", "connected connected 1 disconnected connected 2 connected disconnected 4 disconnected disconnected 8 ============", "value in units of quarter-:math:`\\\\mu s` that drives the stepper channels high.''' STEPPER_CHANNELS_TARGET_OFF", "=============== MS1 MS2 TRANSITIONS_PER_STEP ============ ============ =============== connected connected 1 disconnected connected 2", "global names too. # ========================================================================== # ========================================================================== LOGF = 'log.rst' '''Path to the", "s` that enables printing (moves the tool down).''' SRV_SIGNAL_CHANNEL_TARGET_ON = 2175 SRV_SIGNAL_CHANNEL_TARGET_ON =", "script to be loaded on the MM12. Parameters ---------- fpath : str-like Path", "'subroutine_id' : 2, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_neg_pixel', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ),", "= 1.0 # Check for pixel with and without color. for i in", "========================================================================== class Getch: \"\"\"Gets a single character from standard input. Does not echo", "''' def report_position(x, y): print 'At row {0}, column {1}'.format(y, x) def print_img_pixel(x,", "corresponds to the upper left corner of the input image. #. :math:`a_{b-1,w-1}` corresponds", "return self.impl() class _GetchUnix: '''Unix implementation of class ``Getch``.''' def __init__(self): import tty,", "i in range(b): for j in range(w): if img[i][j] < 0.9: img[i][j] =", "in units of pixels,''' SUB_STEPPER_PULSE_TEMPLATE = '''sub {name} {dir} {dir_channel} servo # set", "{1} columns'.format(b, w) print msg x = y = 0 # We are", "will be printed. assert nprints > 0 print 'Loaded ``{0}`` with {1} pixels,", "0.9: img[i][j] = 0.0 else: img[i][j] = 1.0 if invert: print 'Inverting image...'", "through the XMS1, XMS2, YMS1, YMS2 jumpers in mcircuit). If ``False`` perform translation", ": int Image's width, number of columns in the array representation. ''' global", "command port' def print_image_better_better(confirm=False): '''Automatically print the input image. Parameters ---------- confirm :", "sp.port) for f in (logf, sys.stdout): print >>f, msg def manual_translation_mode(precise=True): '''Manually translate", "======= ================================================================ confirm: boolean, optional If ``True``, the user must confirm the translation", "'Operation interrupted, flushing command port' def print_image_better(confirm=False): def report_position(x, y): print 'At row", "optional Wait for confirmation before any translation (default is ``False``). Notes ----- Let", "break translate('X+P', confirm) x += 1 if y == b - 1: translate('Z-')", "f in (logf, sys.stdout): print >>f, msg def manual_translation_mode(precise=True): '''Manually translate the printerm", ": int, optional Sets the acceleration of the servo signal channel in units", "the row from :math:`a_{1,w-1}` to :math:`a_{1,0}`, and so on until there are no", "of quarter-:math:`\\\\mu s` that enables printing (moves the tool down).''' SRV_SIGNAL_CHANNEL_TARGET_ON = 2175", "grayscale, non-interlaced. invert : boolean, optional Invert the image if ``True`` (default is", "{ 'h' : 'X-P', 'l' : 'X+P', 'j' : 'Y+P', 'k' : 'Y-P',", "mcircuit; printerc stablishes a serial connection with mcircuit, and mcircuit is coupled to", "to translate a pixel unit across the respective axis). ======= ================================================================ *adm* translation", "int, optional Delay (in milliseconds) between each transition in the subroutines that perform", "axes.''' TRANSITIONS_PER_PIXEL = STEPS_PER_PIXEL * TRANSITIONS_PER_STEP '''Number of low-to-high transitions the stepper motors", "units of quarter-:math:`\\\\mu s` that enables printing (moves the tool down).''' SRV_SIGNAL_CHANNEL_TARGET_ON =", "1). servo_acceleration : int, optional Sets the acceleration of the servo signal channel", "file name. PN = os.path.splitext(sys.argv[0])[0] logf = open(LOGF, 'w') print >>logf, 'START' atexit.register(on_exit)", "to produce the trajectory of the tool printing the image. ''' # Standard", ": SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_neg_pixel', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'X+P' : {", "y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm) try: msg = 'Preparing to print", "'subroutine_id' : 1, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_pos_pulse', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), },", "'step_channel': 1, }, 'Y' : { 'dir_channel' : 2, 'dir_positive' : STEPPER_CHANNELS_TARGET_ON, 'dir_negative'", "{2} of which have color'.format( imgpath, npixels, nprints) plt.close('all') if show: plt.imshow(img, cmap=cm.gray)", "for a precise but slow translation.''' SUB_SERVO_TEMPLATE = '''sub {name} {position} {channel} servo", "on=STEPPER_CHANNELS_TARGET_ON ), }, 'X+P' : { 'subroutine_id' : 3, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_pos_pixel',", "img[i][j] = 1.0 # Check for pixel with and without color. for i", "if img[i][j] < 0.9: img[i][j] = 0.0 else: img[i][j] = 1.0 if invert:", "if img[y][x+1] != 0.0: translate('Z-', confirm) except IndexError as e: pass if x", "'i' : 'Z+', 'o' : 'Z-', } else: keys2translation = { 'h' :", "of low-to-high transitions to perform in the subroutines that performs translation in units", "and without color. for i in range(b): for j in range(w): if img[i][j]", "print msg x = y = z = 0 # We are at", "for the printer73x system. **printerc** is an interactive command line interface for the", "single pulse for positive translation across :math:`Y`. ``Y-P`` send :math:`n` pulses for negative", "across a single axis at a time. Parameters ---------- adm: str *adm* stands", "= { 'X-p' : { 'subroutine_id' : 0, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_neg_pulse', dir=MM12_AXES_CHANNELS['X']['dir_negative'],", "servo signal channel in units of (0.25 us)/(10 ms)/(80 ms) (default is 0).", "character from standard input. Does not echo to the screen. References ========== ..", "100). ''' def get_subroutine_key_by_id(subroutine_id): for key, value in MM12_SUBROUTINES.items(): if subroutine_id is value['subroutine_id']:", "import matplotlib.cm as cm # Same as **printer73x**. __version__ = '0.09' # GLOBAL", "representation. **w** : int Image's width, number of columns in the array representation.", "w nprints = nnotprints = 0 assert (b > 0) and (w >", "(default is True). ''' if precise: keys2translation = { 'h' : 'X-p', 'l'", "memory the routines that correspond to the translations across the :math:`X`, :math:`Y` and", ": SUB_STEPPER_PULSE_TEMPLATE.format( name='x_neg_pulse', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X+p' : { 'subroutine_id'", "(0.25 us)/(10 ms) (default is 100). ''' def get_subroutine_key_by_id(subroutine_id): for key, value in", "optional If ``True``, perform translation in units of single low-to-high transitions sent to", "or :math:`Y` axes.''' TRANSITIONS_PER_PIXEL = STEPS_PER_PIXEL * TRANSITIONS_PER_STEP '''Number of low-to-high transitions the", "0: break translate('X-P', confirm) x -= 1 print 'The image has been printed'", "x == 0: translate('Z-') break translate('X-P', confirm) x -= 1 if y ==", "import msvcrt def __call__(self): import msvcrt return msvcrt.getch() def on_exit(): '''Actions to do", "printed' except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' def print_image_better(confirm=False): def", "while True: # To the right. print 'Printing across the row {0}'.format(y) while", "user must confirm the translation by pressing Enter (default is ``False``). ''' #", "has been printed' except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' if", "white, no grays. for i in range(b): for j in range(w): if img[i][j]", ": boolean, optional If ``True``, perform translation in units of single low-to-high transitions", "def print_image_better_better(confirm=False): '''Automatically print the input image. Parameters ---------- confirm : boolean, optional", "no grays. for i in range(b): for j in range(w): if img[i][j] <", "function sets the following global names: **img** : array of booleans 2-d array", "serial command port. ''' global sp sp = serial.Serial(port=commandport_id) assert sp.isOpen() print >>logf,", "__future__ import division from pprint import pprint import sys import os import atexit", ": SRV_SIGNAL_CHANNEL_TARGET_OFF, 'off' : SRV_SIGNAL_CHANNEL_TARGET_ON, }, } '''Configuration of the MM12 channels for", "speed '''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel']) '''MM12 script initialization.''' MM12_SUBROUTINES = { 'X-p' : { 'subroutine_id' :", "== 0.0: return True return False try: msg = 'Preparing to print an", "0.0: img[i][j] = 0.0 else: img[i][j] = 1.0 # Check for pixel with", "{ 'subroutine_id' : 6, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_neg_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON", "the printer73x system. **printerc** is an interactive command line interface for the numerical", "connected to ``printerm`` through ``{1}``'.format( PN, sp.port) for f in (logf, sys.stdout): print", "''' available = [] for i in range(256): try: s = serial.Serial(i) available.append(", "assert (b > 0) and (w > 0) print 'Processing the image...' #", "the MM12 script is running or stopped. Returns ------- script_status : {``MM12_SCRIPT_RUNNING``, ``MM12_SCRIPT_STOPPED``}", "set direction {off} {step_channel} servo {{delay}} delay {on} {step_channel} servo {{delay}} delay quit", "pprint import pprint import sys import os import atexit import gc import time", "precise: keys2translation = { 'h' : 'X-p', 'l' : 'X+p', 'j' : 'Y+p',", "tool down).''' SRV_SIGNAL_CHANNEL_TARGET_ON = 2175 SRV_SIGNAL_CHANNEL_TARGET_ON = 1580 ''':math:`Z` axis servo motor pulse", "if y == 0: break translate('Y-P', confirm) y -= 1 while True: if", "``printerc``!\\n' # Invoke the garbage collector. gc.collect() def scan_serial_ports(): '''Scan system for available", "for the numerical control of the **printer73x** system. printerc drives printerm through mcircuit;", "and white, no grays. for i in range(b): for j in range(w): if", "'''Target value in units of quarter-:math:`\\\\mu s` that drives the stepper channels low.'''", "rows and {1} columns'.format(b, w) print msg x = y = z =", "acceleration {{servo_speed}} {servo_channel} speed '''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel']) '''MM12 script initialization.''' MM12_SUBROUTINES = { 'X-p' :", "to be reproduced by printerm. Parameters ---------- imgpath : str-like Path to the", "front perspective: #. :math:`a_{0,0}` corresponds to the upper left corner of the input", "drive a stepper motor in units of low-to-high transitions, for a precise but", "y) print_img_pixel(x, y, confirm) if x == 0: break translate('X-P', confirm) x -=", "Must be PNG, 8-bit grayscale, non-interlaced. invert : boolean, optional Invert the image", "reproduced by printerm. Parameters ---------- imgpath : str-like Path to the image file.", "True: report_position(x, y) print_img_pixel(x, y, confirm) if x == w - 1: break", "tuples Each element of the list is a ``(num, name)`` tuple with the", "pixels,''' SUB_STEPPER_PULSE_TEMPLATE = '''sub {name} {dir} {dir_channel} servo # set direction {off} {step_channel}", "milliseconds) between each transition in the subroutines that perform translation through the stepper", "+= 1 print 'Returning to a_{{{0}, 0}}'.format(y) while True: if x == 0:", "print an image with {0} rows and {1} columns'.format(b, w) print msg x", "y == 0: break translate('Y-P', confirm) y -= 1 print 'The image has", "'''Configuration of the MM12 channels for the servo and stepper motors outputs.''' SUB_STEPPER_PIXEL_TEMPLATE", "True: if y == 0: break translate('Y-P', confirm) y -= 1 while True:", "75 delay quit ''' '''Template for the MM12 script subroutine that drives the", "in range(w): if img[i][j] < 0.9: img[i][j] = 0.0 else: img[i][j] = 1.0", "STEPPER_CHANNELS_TARGET_ON = 6800 '''Target value in units of quarter-:math:`\\\\mu s` that drives the", ": SUB_STEPPER_PULSE_TEMPLATE.format( name='y_neg_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y+p' : { 'subroutine_id'", "implementation of class ``Getch``.''' def __init__(self): import tty, sys def __call__(self): import sys,", "**printer73x** system. printerc drives printerm through mcircuit; printerc stablishes a serial connection with", "the image file. Must be PNG, 8-bit grayscale, non-interlaced. invert : boolean, optional", "to perform in the subroutines that performs translation in units of pixels through", "column {1}'.format(y, x) def print_img_pixel(x, y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm) def", "across :math:`Y`. ``Z-`` move the tool to the off position (:math:`Z`). ``Z+`` move", "the MM12 script subroutines.''' MM12_SCRIPT_RUNNING = '\\x00' '''Byte value that the MM12 returns", "serial.Serial(port=commandport_id) assert sp.isOpen() print >>logf, '``{0}`` just opened *command port* ``{1}``'.format(PN, sp.port) msg", "= '``{0}`` is now connected to ``printerm`` through ``{1}``'.format( PN, sp.port) for f", "= chr( MM12_SUBROUTINES[adm]['subroutine_id']) str2write = ''.join(['\\xa7', subroutine_id]) if confirm: raw_input() assert sp.write(str2write) ==", ":math:`n` pulses for positive translation across :math:`X`. ``Y-p`` send 1 single pulse for", "running. while mm12_script_status() == MM12_SCRIPT_RUNNING: pass subroutine_id = chr( MM12_SUBROUTINES[adm]['subroutine_id']) str2write = ''.join(['\\xa7',", "represents a pixel. Comparing :math:`\\mathbf{A}` with the input image from a front perspective:", "subroutines that drive a stepper motor in units of low-to-high transitions, for a", "{name} {dir} {dir_channel} servo # set direction {off} {step_channel} servo {{delay}} delay {on}", "(how much the tool is translated depends on the microstep format selected through", "'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_neg_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y+p' : {", "y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm) def color_in_this_row(row): for pixel in row:", "Returns ------- available : list of tuples Each element of the list is", "4, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_neg_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y+p' :", "gc import time # Related third party imports. import serial import IPython import", "break translate('Y-P', confirm) y -= 1 while True: if x == 0: break", "off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y+p' : { 'subroutine_id' : 5, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format(", "# program name from file name. PN = os.path.splitext(sys.argv[0])[0] logf = open(LOGF, 'w')", "confirm) y -= 1 while True: if x == 0: break translate('X-P', confirm)", "third party imports. import serial import IPython import numpy as np # remove", "{ 'subroutine_id' : 2, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_neg_pixel', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON", "from standard input. Does not echo to the screen. References ========== .. [GETCHRECIPE]", "sp.isOpen() print >>logf, '``{0}`` just opened *command port* ``{1}``'.format(PN, sp.port) msg = '``{0}``", "'``{0}`` is now connected to ``printerm`` through ``{1}``'.format( PN, sp.port) for f in", "MM12 returns when the script is stopped.''' # ========================================================================== # ========================================================================== # ==========================================================================", "units of quarter-:math:`\\\\mu s` that drives the stepper channels high.''' STEPPER_CHANNELS_TARGET_OFF = 5600", "printed' except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' if __name__ ==", "port' def print_image_better_better(confirm=False): '''Automatically print the input image. Parameters ---------- confirm : boolean,", "the matrix representation of the input image. :math:`a_{y,x}` as an element of :math:`\\mathbf{A}`,", "print >>f, msg def manual_translation_mode(precise=True): '''Manually translate the printerm tool across the :math:`XY`", "``X-P`` send :math:`n` pulses for negative translation across :math:`X`. ``X+P`` send :math:`n` pulses", "= 1.0 if invert: print 'Inverting image...' for i in range(b): for j", "dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Z-' : { 'subroutine_id' : 8,", "name='y_neg_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y+p' : { 'subroutine_id' : 5,", "perform translations across a single axis at a time. Parameters ---------- adm: str", "getch() if ch not in keys2translation.keys(): break while mm12_script_status() == MM12_SCRIPT_RUNNING: pass translate(keys2translation[ch],", "necessary processing for the input image to be reproduced by printerm. Parameters ----------", "precise : boolean, optional If ``True``, perform translation in units of single low-to-high", "jumpers *MS1* and *MS2*. Use the following table to set this constant: ============", "for j in range(w): if img[i][j] > 0.0: nnotprints += 1 else: nprints", "SUB_STEPPER_PULSE_TEMPLATE.format( name='y_pos_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y-P' : { 'subroutine_id' :", "boolean, optional If ``True``, perform translation in units of single low-to-high transitions sent", "the stepper motor (default is ``TRANSITIONS_PER_PIXEL``). delay : int, optional Delay (in milliseconds)", "'subroutine_id' : 4, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_neg_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), },", ": STEPPER_CHANNELS_TARGET_OFF, 'step_channel': 3, }, 'Z' : { 'channel' : 4, 'on' :", "x) def print_img_pixel(x, y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm) def color_in_this_row(row): for", "as e: pass if x == w - 1: translate('Z-') break translate('X+P', confirm)", "boards must have the same jumper configuration. ''' STEPS_PER_PIXEL = 90 '''Number of", "of the list is a ``(num, name)`` tuple with the number and name", "''':math:`Z` axis servo motor pulse width in units of quarter-:math:`\\\\mu s` that enables", "is running.''' MM12_SCRIPT_STOPPED = '\\x01' '''Byte value that the MM12 returns when the", "log file.''' INTRO_MSG = '''\\ **printerc** Welcome! ''' '''Welcome message for command line", "representation of the input image. :math:`a_{y,x}` as an element of :math:`\\mathbf{A}`, represents a", "def connect_printerm(commandport_id): '''Connect printerc with printerm through the MM12 command port. Parameters ----------", "if img[y][x] == 0.0: print_pixel(confirm) def color_in_this_row(row): for pixel in row: if pixel", "to the lower right corner of the input image. Starting from the HOME", "servo signal channel in units of (0.25 us)/(10 ms) (default is 100). '''", "`pyserial <http://sourceforge.net/projects/pyserial/files/package>`_ project. ''' available = [] for i in range(256): try: s", "translate('Y+P', confirm) y += 1 # To the left. print 'Printing across the", "pixel across the :math:`X` or :math:`Y` axes.''' SRV_SIGNAL_CHANNEL_TARGET_OFF = 940 ''':math:`Z` axis servo", "confirm) x += 1 if y == b - 1: translate('Z-') break translate('Y+P',", "+= 1 assert (nnotprints + nprints) == npixels # If ``nprints == 0``", "w - 1: break translate('X+P', confirm) x += 1 if y == b", "the user must confirm the translation by pressing Enter (default is ``False``). '''", "SUB_STEPPER_PULSE_TEMPLATE = '''sub {name} {dir} {dir_channel} servo # set direction {off} {step_channel} servo", "def print_image(confirm=False): def report_position(x, y): print 'At row {0}, column {1}'.format(y, x) def", "Directly copied from example from `pyserial <http://sourceforge.net/projects/pyserial/files/package>`_ project. ''' available = [] for", "if x == 0: break translate('X-P', confirm) x -= 1 if y ==", "w print 'Loading ``{0}``...'.format(imgpath) img = mpimg.imread(fname=imgpath, format='png') b, w = img.shape npixels", "get_subroutine_key_by_id(i) subroutine_body = MM12_SUBROUTINES[subroutine_key]['subroutine_body'] if 'Z' not in subroutine_key: subroutine_body = subroutine_body.format(delay=delay) if", "array representation. ''' global img, b, w print 'Loading ``{0}``...'.format(imgpath) img = mpimg.imread(fname=imgpath,", "HOME position. while True: print 'Printing across the row {0}'.format(y) while True: report_position(x,", ": { 'subroutine_id' : 9, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_on', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['on']*4) }, }", "Parameters ---------- commandport_id : str or int Serial device name or port number", "'Z' not in subroutine_key: subroutine_body = subroutine_body.format(delay=delay) if 'P' in subroutine_key: subroutine_body =", "translate('X-P', confirm) x -= 1 print 'The image has been printed' except KeyboardInterrupt:", "number of pulses for the printerm tool to translate a pixel unit across", "image. #. :math:`a_{b-1,w-1}` corresponds to the lower right corner of the input image.", "print_image_better(confirm=False): def report_position(x, y): print 'At row {0}, column {1}'.format(y, x) def print_img_pixel(x,", "This function sets the following global names: **img** : array of booleans 2-d", "print 'At row {0}, column {1}'.format(y, x) def print_img_pixel(x, y, confirm=False): if img[y][x]", "print_pixel(confirm) def color_in_this_row(row): for pixel in row: if pixel == 0.0: return True", "ms) (default is 0). servo_speed : int, optional Sets the speed of the", "== 0.0: translate('Z+', confirm) if img[y][x-1] != 0.0: translate('Z-', confirm) if x ==", "to the off position (:math:`Z`). ``Z+`` move the tool to the on position", "print_img_pixel(x, y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm) def color_in_this_row(row): for pixel in", "y, confirm) if x == 0: break translate('X-P', confirm) x -= 1 if", "port. ''' global sp sp = serial.Serial(port=commandport_id) assert sp.isOpen() print >>logf, '``{0}`` just", "======= ================================================================ ``X-p`` send 1 single pulse for negative translation across :math:`X`. ``X+p``", "confirm) try: if img[y][x+1] != 0.0: translate('Z-', confirm) except IndexError as e: pass", "== w - 1: break translate('X+P', confirm) x += 1 if y ==", "pixel == 0.0: return True return False try: msg = 'Preparing to print", "YMS1, YMS2 jumpers in mcircuit). If ``False`` perform translation in units of pixels", "``False``). Notes ----- This function sets the following global names: **img** : array", "the row {0}'.format(y) while True: report_position(x, y) if img[y][x] == 0.0: translate('Z+', confirm)", "of pixels through the stepper motor (default is ``TRANSITIONS_PER_PIXEL``). delay : int, optional", "sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)", "= '''sub {name} {position} {channel} servo begin get_moving_state while # wait until is", "of the MM12 serial command port. ''' global sp sp = serial.Serial(port=commandport_id) assert", "then moves to the next row (:math:`a_{1,w-1}`) and visits every element of the", "= y = 0 # We are at HOME position. while True: print", ": boolean, optional Wait for confirmation before any translation (default is ``False``). Notes", "'o' : 'Z-', } getch = Getch() while True: ch = getch() if", "TRANSITIONS_PER_PIXEL = STEPS_PER_PIXEL * TRANSITIONS_PER_STEP '''Number of low-to-high transitions the stepper motors need", "while {off} {step_channel} servo {{delay}} delay {on} {step_channel} servo {{delay}} delay 1 minus", ": { 'subroutine_id' : 8, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_off', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['off']*4) }, 'Z+'", "Comparing :math:`\\mathbf{A}` with the input image from a front perspective: #. :math:`a_{0,0}` corresponds", "try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows:", "save the script file. ntransitions : int, optional Number of low-to-high transitions to", "npixels = b * w nprints = nnotprints = 0 assert (b >", "the subroutines that performs translation in units of pixels through the stepper motor", "), }, 'X+P' : { 'subroutine_id' : 3, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_pos_pixel', dir=MM12_AXES_CHANNELS['X']['dir_positive'],", "plt.show() def connect_printerm(commandport_id): '''Connect printerc with printerm through the MM12 command port. Parameters", "(nnotprints + nprints) == npixels # If ``nprints == 0`` then no pixel", "of which have color'.format( imgpath, npixels, nprints) plt.close('all') if show: plt.imshow(img, cmap=cm.gray) plt.show()", "1 if y == b - 1: translate('Z-') break translate('Y+P', confirm) y +=", "TRANSITIONS_PER_STEP = 2 '''The board sets the microstepping format with the jumpers *MS1*", "off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y+P' : { 'subroutine_id' : 7, 'subroutine_body' :", "y) print_img_pixel(x, y, confirm) if x == w - 1: break translate('X+P', confirm)", "low-to-high transitions, for a precise but slow translation.''' SUB_SERVO_TEMPLATE = '''sub {name} {position}", "img[y][x] == 0.0: translate('Z+', confirm) try: if img[y][x+1] != 0.0: translate('Z-', confirm) except", ": int, optional Delay (in milliseconds) between each transition in the subroutines that", "def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self):", "and so on until there are no more rows to visit. In any", "tool to translate a pixel unit across the respective axis). ======= ================================================================ *adm*", "in range(b): for j in range(w): if img[i][j] > 0.0: img[i][j] = 0.0", "MM12_SCRIPT_RUNNING: pass subroutine_id = chr( MM12_SUBROUTINES[adm]['subroutine_id']) str2write = ''.join(['\\xa7', subroutine_id]) if confirm: raw_input()", "it. ''' def report_position(x, y): print 'At row {0}, column {1}'.format(y, x) def", "flushing command port' if __name__ == \"__main__\": # program name from file name.", "printed. assert nprints > 0 print 'Loaded ``{0}`` with {1} pixels, {2} of", "available.append( (i, s.portstr)) s.close() except serial.SerialException: pass return available def mm12_script_status(): '''Indicate whether", "of :math:`\\mathbf{A}`, represents a pixel. Comparing :math:`\\mathbf{A}` with the input image from a", "the MM12 script subroutine that drives the servo motor.''' MM12_SCRIPT_INIT = '''\\ {{servo_acceleration}}", "int) with open(fpath, 'w') as f: print >>f, MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration, servo_speed=servo_speed) for i in", "'Returning to a_{{0, 0}}'.format(y) while True: if y == 0: break translate('Y-P', confirm)", "+= 1 # To the left. print 'Printing across the row {0}'.format(y) while", "Sets the speed of the servo signal channel in units of (0.25 us)/(10", "its memory the routines that correspond to the translations across the :math:`X`, :math:`Y`", ": list of tuples Each element of the list is a ``(num, name)``", "perform translation through the stepper motors (default is 1). servo_acceleration : int, optional", "time # Related third party imports. import serial import IPython import numpy as", "ntransitions=TRANSITIONS_PER_PIXEL, delay=1, servo_acceleration=0, servo_speed=100): '''Build a script to be loaded on the MM12.", "TRANSITIONS_PER_STEP '''Number of low-to-high transitions the stepper motors need to translate 1 pixel", "in units of pixels (default is True). ''' if precise: keys2translation = {", "Use the following table to select the kind of translation you want to", "board sets the microstepping format with the jumpers *MS1* and *MS2*. Use the", "'X' : { 'dir_channel' : 0, 'dir_positive' : STEPPER_CHANNELS_TARGET_OFF, 'dir_negative' : STEPPER_CHANNELS_TARGET_ON, 'step_channel':", "acceleration of the servo signal channel in units of (0.25 us)/(10 ms)/(80 ms)", "(default is 1). servo_acceleration : int, optional Sets the acceleration of the servo", "``True`` (default is ``False``). show : boolean, optional Show the image if ``True``", "1: translate('Z-') break translate('Y+P', confirm) y += 1 print 'Returning to a_{{0, 0}}'.format(y)", "element of the list is a ``(num, name)`` tuple with the number and", "''' STEPS_PER_PIXEL = 90 '''Number of steps the stepper motor needs to translate", "with mcircuit, and mcircuit is coupled to printerm through the motors. mcircuit (actually", "optional Show the image if ``True`` (default is ``False``). Notes ----- This function", "{ 'subroutine_id' : 1, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_pos_pulse', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON),", "builds and identifies the MM12 script subroutines.''' MM12_SCRIPT_RUNNING = '\\x00' '''Byte value that", "'off' : SRV_SIGNAL_CHANNEL_TARGET_ON, }, } '''Configuration of the MM12 channels for the servo", "{1}'.format(y, x) def print_img_pixel(x, y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm) def color_in_this_row(row):", "b, w = img.shape npixels = b * w nprints = nnotprints =", "on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y+P' : { 'subroutine_id' : 7, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_pos_pixel',", "MM12_SUBROUTINES[adm]['subroutine_id']) str2write = ''.join(['\\xa7', subroutine_id]) if confirm: raw_input() assert sp.write(str2write) == 2 #if", "''':math:`Z` axis servo motor pulse width in units of quarter-:math:`\\\\mu s` that disables", "(:math:`Z`). ``Z+`` move the tool to the on position (:math:`Z`). ======= ================================================================ confirm:", "), }, 'Y+P' : { 'subroutine_id' : 7, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_pos_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_positive'],", "'''Byte value that the MM12 returns when the script is running.''' MM12_SCRIPT_STOPPED =", "that builds and identifies the MM12 script subroutines.''' MM12_SCRIPT_RUNNING = '\\x00' '''Byte value", "if img[y][x] == 0.0: print_pixel(confirm) try: msg = 'Preparing to print an image", "\"__main__\": # program name from file name. PN = os.path.splitext(sys.argv[0])[0] logf = open(LOGF,", "'l' : 'X+p', 'j' : 'Y+p', 'k' : 'Y-p', 'i' : 'Z+', 'o'", "class ``Getch``.''' def __init__(self): import tty, sys def __call__(self): import sys, tty, termios", "motors. mcircuit (actually MM12, its subsystem) loads in its memory the routines that", "sp = serial.Serial(port=commandport_id) assert sp.isOpen() print >>logf, '``{0}`` just opened *command port* ``{1}``'.format(PN,", "mm12_script_status() == MM12_SCRIPT_RUNNING: pass translate(keys2translation[ch], confirm=False) def print_pixel(confirm=False): if confirm: raw_input() translate('Z+', confirm=False)", "- 1: break translate('Y+P', confirm) y += 1 print 'Printing across the row", "img = mpimg.imread(fname=imgpath, format='png') b, w = img.shape npixels = b * w", "while True: if x == 0: break translate('X-P', confirm) x -= 1 print", "for negative translation across :math:`X`. ``X+p`` send 1 single pulse for positive translation", "{ 'subroutine_id' : 0, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_neg_pulse', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON),", "{ 'subroutine_id' : 4, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_neg_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON),", "port. Parameters ---------- commandport_id : str or int Serial device name or port", "'\\nThanks for using ``printerc``!\\n' # Invoke the garbage collector. gc.collect() def scan_serial_ports(): '''Scan", "printing the image. ''' # Standard library imports. from __future__ import division from", "dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y-p' : { 'subroutine_id' : 4,", "== 0: break translate('X-P', confirm) x -= 1 if y == b -", "in range(b): for j in range(w): if img[i][j] < 0.9: img[i][j] = 0.0", "if invert: print 'Inverting image...' for i in range(b): for j in range(w):", ": 7, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_pos_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), },", "pass subroutine_id = chr( MM12_SUBROUTINES[adm]['subroutine_id']) str2write = ''.join(['\\xa7', subroutine_id]) if confirm: raw_input() assert", "tool is translated depends on the microstep format selected through the XMS1, XMS2,", "*MS2*. Use the following table to set this constant: ============ ============ =============== MS1", "{ 'subroutine_id' : 3, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_pos_pixel', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON", "0: translate('Z-') break translate('X-P', confirm) x -= 1 if y == b -", "MM12. Parameters ---------- fpath : str-like Path location where to save the script", "``MM12_SCRIPT_STOPPED``} ''' assert sp.write('\\xae') == 1 return sp.read(1) def translate(adm, confirm=False): '''Translate the", "of the port. Notes ----- Directly copied from example from `pyserial <http://sourceforge.net/projects/pyserial/files/package>`_ project.", "translation (default is ``False``). Notes ----- Let :math:`\\mathbf{A}` be the matrix representation of", "for command line interface.''' # MM12 # ========================================================================== TRANSITIONS_PER_STEP = 2 '''The board", "``Y-p`` send 1 single pulse for negative translation across :math:`Y`. ``Y+p`` send 1", "is black then the tool prints it. ''' def report_position(x, y): print 'At", "command port. Parameters ---------- commandport_id : str or int Serial device name or", "translation across :math:`X`. ``X+P`` send :math:`n` pulses for positive translation across :math:`X`. ``Y-p``", "'Z-', } else: keys2translation = { 'h' : 'X-P', 'l' : 'X+P', 'j'", "True: print 'Printing across the row {0}'.format(y) while True: report_position(x, y) print_img_pixel(x, y,", "{ 'subroutine_id' : 7, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_pos_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON", "+ nprints) == npixels # If ``nprints == 0`` then no pixel will", "if ch not in keys2translation.keys(): break while mm12_script_status() == MM12_SCRIPT_RUNNING: pass translate(keys2translation[ch], confirm=False)", "longer moving. repeat 75 delay quit ''' '''Template for the MM12 script subroutine", "``Z+`` move the tool to the on position (:math:`Z`). ======= ================================================================ confirm: boolean,", "perform in the subroutines that performs translation in units of pixels through the", "'h' : 'X-p', 'l' : 'X+p', 'j' : 'Y+p', 'k' : 'Y-p', 'i'", "{ 'subroutine_id' : 5, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_pos_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON),", "plt.imshow(img, cmap=cm.gray) plt.show() def connect_printerm(commandport_id): '''Connect printerc with printerm through the MM12 command", "#. :math:`a_{b-1,w-1}` corresponds to the lower right corner of the input image. Starting", "the tool prints it. ''' def report_position(x, y): print 'At row {0}, column", "x = y = 0 # We are at HOME position. while True:", ": 3, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_pos_pixel', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), },", ": SUB_STEPPER_PULSE_TEMPLATE.format( name='y_pos_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y-P' : { 'subroutine_id'", "of quarter-:math:`\\\\mu s` that disables printing (moves the tool up).''' STEPPER_CHANNELS_TARGET_ON = 6800", "command line interface for the numerical control of the **printer73x** system. printerc drives", "KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' if __name__ == \"__main__\": #", "msvcrt.getch() def on_exit(): '''Actions to do on exit.''' try: print >>logf, 'Closing ``{0}``", ": boolean, optional Show the image if ``True`` (default is ``False``). Notes -----", "and visits every element of the row from :math:`a_{1,w-1}` to :math:`a_{1,0}`, and so", "STEPS_PER_PIXEL = 90 '''Number of steps the stepper motor needs to translate 1", "def print_pixel(confirm=False): if confirm: raw_input() translate('Z+', confirm=False) translate('Z-', confirm=False) def print_image(confirm=False): def report_position(x,", "= '''\\ {{servo_acceleration}} {servo_channel} acceleration {{servo_speed}} {servo_channel} speed '''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel']) '''MM12 script initialization.''' MM12_SUBROUTINES", "boolean, optional Show the image if ``True`` (default is ``False``). Notes ----- This", "with the jumpers *MS1* and *MS2*. Use the following table to set this", "confirm) x -= 1 if y == b - 1: translate('Z-') break translate('Y+P',", "'''Numerical controller for the printer73x system. **printerc** is an interactive command line interface", "_GetchUnix: '''Unix implementation of class ``Getch``.''' def __init__(self): import tty, sys def __call__(self):", "an interactive command line interface for the numerical control of the **printer73x** system.", "us)/(10 ms)/(80 ms) (default is 0). servo_speed : int, optional Sets the speed", "= 90 '''Number of steps the stepper motor needs to translate 1 pixel", "'Processing the image...' # only total black and white, no grays. for i", "'X+p' : { 'subroutine_id' : 1, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_pos_pulse', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF,", "print >>f, subroutine_body def prepare_img(imgpath, invert=False, show=False): '''Perform any necessary processing for the", "''' # Standard library imports. from __future__ import division from pprint import pprint", "until there are no more rows to visit. In any position, if the", "# ========================================================================== # ========================================================================== LOGF = 'log.rst' '''Path to the log file.''' INTRO_MSG", "pulse width in units of quarter-:math:`\\\\mu s` that enables printing (moves the tool", "0.0: translate('Z+', confirm) try: if img[y][x+1] != 0.0: translate('Z-', confirm) except IndexError as", "termios.TCSADRAIN, old_settings) return ch class _GetchWindows: '''Windows implementation of class ``Getch``.''' def __init__(self):", "script is stopped.''' # ========================================================================== # ========================================================================== # ========================================================================== class Getch: \"\"\"Gets a", "motor.''' MM12_SCRIPT_INIT = '''\\ {{servo_acceleration}} {servo_channel} acceleration {{servo_speed}} {servo_channel} speed '''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel']) '''MM12 script", "s` that disables printing (moves the tool up).''' STEPPER_CHANNELS_TARGET_ON = 6800 '''Target value", "in units of (0.25 us)/(10 ms) (default is 100). ''' def get_subroutine_key_by_id(subroutine_id): for", "each transition in the subroutines that perform translation through the stepper motors (default", "now connected to ``printerm`` through ``{1}``'.format( PN, sp.port) for f in (logf, sys.stdout):", "in MM12_SUBROUTINES.items(): if subroutine_id is value['subroutine_id']: return key for intarg in (ntransitions, delay,", "respective axis). ======= ================================================================ *adm* translation ======= ================================================================ ``X-p`` send 1 single pulse", "{step_channel} servo {{delay}} delay {on} {step_channel} servo {{delay}} delay quit ''' '''Template for", "translation across :math:`X`. ``X+p`` send 1 single pulse for positive translation across :math:`X`.", "'''Template for the MM12 script subroutine that drives the servo motor.''' MM12_SCRIPT_INIT =", "translation by pressing Enter (default is ``False``). ''' # Start until script is", "Image's height, number of rows in the array representation. **w** : int Image's", "import sys import os import atexit import gc import time # Related third", "script is running or stopped. Returns ------- script_status : {``MM12_SCRIPT_RUNNING``, ``MM12_SCRIPT_STOPPED``} ''' assert", "logf.close() print '\\nThanks for using ``printerc``!\\n' # Invoke the garbage collector. gc.collect() def", "> 0) print 'Processing the image...' # only total black and white, no", "and *MS2*. Use the following table to set this constant: ============ ============ ===============", "matrix representation of the input image. :math:`a_{y,x}` as an element of :math:`\\mathbf{A}`, represents", "str2write = ''.join(['\\xa7', subroutine_id]) if confirm: raw_input() assert sp.write(str2write) == 2 #if 'Z'", "number number of the MM12 serial command port. ''' global sp sp =", "SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_pos_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Z-' : { 'subroutine_id'", "''' '''Welcome message for command line interface.''' # MM12 # ========================================================================== TRANSITIONS_PER_STEP =", "(:math:`Z`). ======= ================================================================ confirm: boolean, optional If ``True``, the user must confirm the", "the corresponding pixel is black then the tool prints it. ''' def report_position(x,", "5, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_pos_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y-P' :", "available = [] for i in range(256): try: s = serial.Serial(i) available.append( (i,", "off position (:math:`Z`). ``Z+`` move the tool to the on position (:math:`Z`). =======", "'Y+p' : { 'subroutine_id' : 5, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_pos_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF,", "int Image's width, number of columns in the array representation. ''' global img,", "else: img[i][j] = 1.0 # Check for pixel with and without color. for", "Parameters ---------- adm: str *adm* stands for Axis, Direction, Mode. Use the following", "the MM12 channels for the servo and stepper motors outputs.''' SUB_STEPPER_PIXEL_TEMPLATE = '''sub", "list of tuples Each element of the list is a ``(num, name)`` tuple", "'''sub {name} {position} {channel} servo begin get_moving_state while # wait until is is", "Start until script is not running. while mm12_script_status() == MM12_SCRIPT_RUNNING: pass subroutine_id =", "= subroutine_body.format(delay=delay) if 'P' in subroutine_key: subroutine_body = subroutine_body.format(ntransitions=ntransitions) print >>f, subroutine_body def", ": 'X+P', 'j' : 'Y+P', 'k' : 'Y-P', 'i' : 'Z+', 'o' :", "'''sub {name} {dir} {dir_channel} servo # set direction {off} {step_channel} servo {{delay}} delay", "flushing command port' def print_image_better_better(confirm=False): '''Automatically print the input image. Parameters ---------- confirm", "name. PN = os.path.splitext(sys.argv[0])[0] logf = open(LOGF, 'w') print >>logf, 'START' atexit.register(on_exit) IPython.Shell.IPShellEmbed()(", "been printed' except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' def print_image_better(confirm=False):", "as f: print >>f, MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration, servo_speed=servo_speed) for i in range(len( MM12_SUBROUTINES)): subroutine_key =", "intarg in (ntransitions, delay, servo_acceleration, servo_speed): assert isinstance(intarg, int) with open(fpath, 'w') as", "To the left. print 'Printing across the row {0}'.format(y) while True: report_position(x, y)", "low-to-high transitions the stepper motors need to translate 1 pixel across the :math:`X`", "``{1}``'.format( PN, sp.port) for f in (logf, sys.stdout): print >>f, msg def manual_translation_mode(precise=True):", "import division from pprint import pprint import sys import os import atexit import", "script is not running. while mm12_script_status() == MM12_SCRIPT_RUNNING: pass subroutine_id = chr( MM12_SUBROUTINES[adm]['subroutine_id'])", "print 'Loading ``{0}``...'.format(imgpath) img = mpimg.imread(fname=imgpath, format='png') b, w = img.shape npixels =", "the input image to be reproduced by printerm. Parameters ---------- imgpath : str-like", ">>f, MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration, servo_speed=servo_speed) for i in range(len( MM12_SUBROUTINES)): subroutine_key = get_subroutine_key_by_id(i) subroutine_body =", "confirm) if img[y][x-1] != 0.0: translate('Z-', confirm) if x == 0: translate('Z-') break", "SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_pos_pixel', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y-p' : { 'subroutine_id'", "translate('X+P', confirm) x += 1 print 'Returning to a_{{{0}, 0}}'.format(y) while True: if", "True return False try: msg = 'Preparing to print an image with {0}", "confirm : boolean, optional Wait for confirmation before any translation (default is ``False``).", "'subroutine_id' : 7, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_pos_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ),", "w - 1: break translate('X+P', confirm) x += 1 print 'Returning to a_{{{0},", "PN, sp.port) for f in (logf, sys.stdout): print >>f, msg def manual_translation_mode(precise=True): '''Manually", "to be loaded on the MM12. Parameters ---------- fpath : str-like Path location", "dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X+p' : { 'subroutine_id' : 1, 'subroutine_body'", ":math:`a_{1,w-1}` to :math:`a_{1,0}`, and so on until there are no more rows to", "1 if y == b - 1: break translate('Y+P', confirm) y += 1", ": { 'subroutine_id' : 2, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_neg_pixel', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'],", "nnotprints += 1 else: nprints += 1 assert (nnotprints + nprints) == npixels", "matplotlib.image as mpimg import matplotlib.pyplot as plt import matplotlib.cm as cm # Same", "jumper configuration. ''' STEPS_PER_PIXEL = 90 '''Number of steps the stepper motor needs", "1: break translate('Y+P', confirm) y += 1 print 'Returning to a_{{0, 0}}'.format(y) while", "*adm* translation ======= ================================================================ ``X-p`` send 1 single pulse for negative translation across", "else: nprints += 1 assert (nnotprints + nprints) == npixels # If ``nprints", "MM12 script subroutines.''' MM12_SCRIPT_RUNNING = '\\x00' '''Byte value that the MM12 returns when", "``X+p`` send 1 single pulse for positive translation across :math:`X`. ``X-P`` send :math:`n`", "across the row {0}'.format(y) while True: report_position(x, y) if img[y][x] == 0.0: translate('Z+',", "import IPython import numpy as np # remove import matplotlib.image as mpimg import", "Notes ----- This function sets the following global names: **img** : array of", "y == b - 1: break translate('Y+P', confirm) y += 1 print 'Printing", "the image if ``True`` (default is ``False``). Notes ----- This function sets the", "a serial connection with mcircuit, and mcircuit is coupled to printerm through the", "while True: report_position(x, y) if img[y][x] == 0.0: translate('Z+', confirm) try: if img[y][x+1]", "to the next row (:math:`a_{1,w-1}`) and visits every element of the row from", "!= 0.0: translate('Z-', confirm) if x == 0: translate('Z-') break translate('X-P', confirm) x", "these routines in order to produce the trajectory of the tool printing the", ":math:`n` pulses for positive translation across :math:`Y`. ``Z-`` move the tool to the", "= sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN,", "dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'X+P' : { 'subroutine_id' : 3,", "the input image from a front perspective: #. :math:`a_{0,0}` corresponds to the upper", "the printerm tool to translate a pixel unit across the respective axis). =======", "single pulse for positive translation across :math:`X`. ``X-P`` send :math:`n` pulses for negative", "the MM12 script subroutines that drive a stepper motor in units of pixels,'''", "y = 0 # We are at HOME position. while True: print 'Printing", "negative translation across :math:`X`. ``X+p`` send 1 single pulse for positive translation across", "confirm: boolean, optional If ``True``, the user must confirm the translation by pressing", "0.0 else: img[i][j] = 1.0 # Check for pixel with and without color.", "is the number of pulses for the printerm tool to translate a pixel", "Parameters ---------- confirm : boolean, optional Wait for confirmation before any translation (default", "MM12 script subroutines that drive a stepper motor in units of pixels,''' SUB_STEPPER_PULSE_TEMPLATE", "subroutine_body = MM12_SUBROUTINES[subroutine_key]['subroutine_body'] if 'Z' not in subroutine_key: subroutine_body = subroutine_body.format(delay=delay) if 'P'", "negative translation across :math:`X`. ``X+P`` send :math:`n` pulses for positive translation across :math:`X`.", "translate a pixel unit across the respective axis). ======= ================================================================ *adm* translation =======", "stepper motor driver boards must have the same jumper configuration. ''' STEPS_PER_PIXEL =", "def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try:", "with the number and name of the port. Notes ----- Directly copied from", "array representation of the image. **b** : int Image's height, number of rows", "axes.''' SRV_SIGNAL_CHANNEL_TARGET_OFF = 940 ''':math:`Z` axis servo motor pulse width in units of", "= nnotprints = 0 assert (b > 0) and (w > 0) print", "# ========================================================================== # ========================================================================== class Getch: \"\"\"Gets a single character from standard input.", "(actually MM12, its subsystem) loads in its memory the routines that correspond to", "of class ``Getch``.''' def __init__(self): import tty, sys def __call__(self): import sys, tty,", "_GetchWindows: '''Windows implementation of class ``Getch``.''' def __init__(self): import msvcrt def __call__(self): import", "the image...' # only total black and white, no grays. for i in", "to :math:`a_{0,w-1}` then moves to the next row (:math:`a_{1,w-1}`) and visits every element", "{{{{ntransitions}}}} {dir} {dir_channel} servo # set direction begin dup while {off} {step_channel} servo", "prints it. ''' def report_position(x, y): print 'At row {0}, column {1}'.format(y, x)", "'Y-P' : { 'subroutine_id' : 6, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_neg_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF,", "<NAME> # Contact: <EMAIL> '''Numerical controller for the printer73x system. **printerc** is an", "optional Number of low-to-high transitions to perform in the subroutines that performs translation", "{0}'.format(y) while True: report_position(x, y) print_img_pixel(x, y, confirm) if x == w -", "= 2 '''The board sets the microstepping format with the jumpers *MS1* and", "the tool up).''' STEPPER_CHANNELS_TARGET_ON = 6800 '''Target value in units of quarter-:math:`\\\\mu s`", "img.shape npixels = b * w nprints = nnotprints = 0 assert (b", "subroutine that drives the servo motor.''' MM12_SCRIPT_INIT = '''\\ {{servo_acceleration}} {servo_channel} acceleration {{servo_speed}}", "printerc stablishes a serial connection with mcircuit, and mcircuit is coupled to printerm", "delay quit ''' '''Template for the MM12 script subroutines that drive a stepper", "its subsystem) loads in its memory the routines that correspond to the translations", "subroutines that perform translation through the stepper motors (default is 1). servo_acceleration :", "(moves the tool down).''' SRV_SIGNAL_CHANNEL_TARGET_ON = 2175 SRV_SIGNAL_CHANNEL_TARGET_ON = 1580 ''':math:`Z` axis servo", "motors need to translate 1 pixel across the :math:`X` or :math:`Y` axes.''' SRV_SIGNAL_CHANNEL_TARGET_OFF", "'Y' : { 'dir_channel' : 2, 'dir_positive' : STEPPER_CHANNELS_TARGET_ON, 'dir_negative' : STEPPER_CHANNELS_TARGET_OFF, 'step_channel':", "import matplotlib.pyplot as plt import matplotlib.cm as cm # Same as **printer73x**. __version__", "translation across :math:`Y`. ``Y+P`` send :math:`n` pulses for positive translation across :math:`Y`. ``Z-``", "0) and (w > 0) print 'Processing the image...' # only total black", ": { 'subroutine_id' : 4, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_neg_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'],", "'''Connect printerc with printerm through the MM12 command port. Parameters ---------- commandport_id :", "tool across the :math:`XY` plane. Parameters ---------- precise : boolean, optional If ``True``,", "single axis at a time. Parameters ---------- adm: str *adm* stands for Axis,", "pixels (default is True). ''' if precise: keys2translation = { 'h' : 'X-p',", "'Y+P' : { 'subroutine_id' : 7, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_pos_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF,", "img[y][x+1] != 0.0: translate('Z-', confirm) except IndexError as e: pass if x ==", "old_settings) return ch class _GetchWindows: '''Windows implementation of class ``Getch``.''' def __init__(self): import", "servo {{delay}} delay {on} {step_channel} servo {{delay}} delay 1 minus repeat quit '''", "across :math:`Y`. ``Y-P`` send :math:`n` pulses for negative translation across :math:`Y`. ``Y+P`` send", "Parameters ---------- precise : boolean, optional If ``True``, perform translation in units of", ":math:`X`. ``X+P`` send :math:`n` pulses for positive translation across :math:`X`. ``Y-p`` send 1", "1.0 if invert: print 'Inverting image...' for i in range(b): for j in", "1: break translate('Y+P', confirm) y += 1 print 'Printing across the row {0}'.format(y)", "through the motors. mcircuit (actually MM12, its subsystem) loads in its memory the", "class _GetchWindows: '''Windows implementation of class ``Getch``.''' def __init__(self): import msvcrt def __call__(self):", "name='z_position_on', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['on']*4) }, } '''Structure that builds and identifies the MM12 script", "through the stepper motors (default is 1). servo_acceleration : int, optional Sets the", "Direction, Mode. Use the following table to select the kind of translation you", "color. for i in range(b): for j in range(w): if img[i][j] > 0.0:", ": 'Y-p', 'i' : 'Z+', 'o' : 'Z-', } else: keys2translation = {", "'Z-', } getch = Getch() while True: ch = getch() if ch not", "Same as **printer73x**. __version__ = '0.09' # GLOBAL CONSTANT names. *if main* section", "= b * w nprints = nnotprints = 0 assert (b > 0)", "position=MM12_AXES_CHANNELS['Z']['off']*4) }, 'Z+' : { 'subroutine_id' : 9, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_on', channel=MM12_AXES_CHANNELS['Z']['channel'],", "'''Unix implementation of class ``Getch``.''' def __init__(self): import tty, sys def __call__(self): import", "``printerm`` through ``{1}``'.format( PN, sp.port) for f in (logf, sys.stdout): print >>f, msg", "format selected through the XMS1, XMS2, YMS1, YMS2 jumpers in mcircuit). If ``False``", "'Y-p', 'i' : 'Z+', 'o' : 'Z-', } else: keys2translation = { 'h'", "__call__(self): import msvcrt return msvcrt.getch() def on_exit(): '''Actions to do on exit.''' try:", "printerc with printerm through the MM12 command port. Parameters ---------- commandport_id : str", "We are at HOME position. while True: # To the right. print 'Printing", "dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X-P' : { 'subroutine_id' : 2, 'subroutine_body'", "translate('Z+', confirm) if img[y][x-1] != 0.0: translate('Z-', confirm) if x == 0: translate('Z-')", "delay {on} {step_channel} servo {{delay}} delay 1 minus repeat quit ''' '''Template for", "slow translation.''' SUB_SERVO_TEMPLATE = '''sub {name} {position} {channel} servo begin get_moving_state while #", "x = y = z = 0 # We are at HOME position.", "and then printerc execute these routines in order to produce the trajectory of", ": array of booleans 2-d array representation of the image. **b** : int", "on position (:math:`Z`). ======= ================================================================ confirm: boolean, optional If ``True``, the user must", "y): print 'At row {0}, column {1}'.format(y, x) def print_img_pixel(x, y, confirm=False): if", "connected 2 connected disconnected 4 disconnected disconnected 8 ============ ============ =============== .. note::", "}, 'X-P' : { 'subroutine_id' : 2, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_neg_pixel', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'],", "dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y+p' : { 'subroutine_id' : 5, 'subroutine_body'", "selected through the XMS1, XMS2, YMS1, YMS2 jumpers in mcircuit). If ``False`` perform", "in the subroutines that performs translation in units of pixels through the stepper", "whether the MM12 script is running or stopped. Returns ------- script_status : {``MM12_SCRIPT_RUNNING``,", "left. print 'Printing across the row {0}'.format(y) while True: report_position(x, y) if img[y][x]", "if show: plt.imshow(img, cmap=cm.gray) plt.show() def connect_printerm(commandport_id): '''Connect printerc with printerm through the", "if x == w - 1: translate('Z-') break translate('X+P', confirm) x += 1", "off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y-p' : { 'subroutine_id' : 4, 'subroutine_body' :", "MM12_SUBROUTINES[subroutine_key]['subroutine_body'] if 'Z' not in subroutine_key: subroutine_body = subroutine_body.format(delay=delay) if 'P' in subroutine_key:", "program name from file name. PN = os.path.splitext(sys.argv[0])[0] logf = open(LOGF, 'w') print", "'''Perform any necessary processing for the input image to be reproduced by printerm.", "b * w nprints = nnotprints = 0 assert (b > 0) and", "Welcome! ''' '''Welcome message for command line interface.''' # MM12 # ========================================================================== TRANSITIONS_PER_STEP", "tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings =", "'log.rst' '''Path to the log file.''' INTRO_MSG = '''\\ **printerc** Welcome! ''' '''Welcome", "======= ================================================================ *adm* translation ======= ================================================================ ``X-p`` send 1 single pulse for negative", "the on position (:math:`Z`). ======= ================================================================ confirm: boolean, optional If ``True``, the user", "print the input image. Parameters ---------- confirm : boolean, optional Wait for confirmation", "atexit import gc import time # Related third party imports. import serial import", "return sp.read(1) def translate(adm, confirm=False): '''Translate the printerm tool across the :math:`XYZ` space.", "If ``True``, perform translation in units of single low-to-high transitions sent to the", "dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y+P' : { 'subroutine_id' : 7,", "{servo_channel} speed '''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel']) '''MM12 script initialization.''' MM12_SUBROUTINES = { 'X-p' : { 'subroutine_id'", "True). ''' if precise: keys2translation = { 'h' : 'X-p', 'l' : 'X+p',", "image. **b** : int Image's height, number of rows in the array representation.", "have the same jumper configuration. ''' STEPS_PER_PIXEL = 90 '''Number of steps the", "except IndexError as e: pass if x == w - 1: translate('Z-') break", "or port number number of the MM12 serial command port. ''' global sp", "across :math:`X`. ``X+P`` send :math:`n` pulses for positive translation across :math:`X`. ``Y-p`` send", "0.0: translate('Z-', confirm) if x == 0: translate('Z-') break translate('X-P', confirm) x -=", "(i, s.portstr)) s.close() except serial.SerialException: pass return available def mm12_script_status(): '''Indicate whether the", "to the translations across the :math:`X`, :math:`Y` and :math:`Z` axis, and then printerc", "subroutines that performs translation in units of pixels through the stepper motor (default", "pixels, {2} of which have color'.format( imgpath, npixels, nprints) plt.close('all') if show: plt.imshow(img,", "the garbage collector. gc.collect() def scan_serial_ports(): '''Scan system for available physical or virtual", "pixel is black then the tool prints it. ''' def report_position(x, y): print", "'''Structure that builds and identifies the MM12 script subroutines.''' MM12_SCRIPT_RUNNING = '\\x00' '''Byte", "in units of (0.25 us)/(10 ms)/(80 ms) (default is 0). servo_speed : int,", "KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' def print_image_better_better(confirm=False): '''Automatically print the", "translate('X-P', confirm) x -= 1 if y == b - 1: translate('Z-') break", "confirm) y -= 1 print 'The image has been printed' except KeyboardInterrupt: sp.flush()", "ms)/(80 ms) (default is 0). servo_speed : int, optional Sets the speed of", "printerm tool across the :math:`XYZ` space. printer73x can only perform translations across a", "SUB_SERVO_TEMPLATE.format( name='z_position_on', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['on']*4) }, } '''Structure that builds and identifies the MM12", "space. printer73x can only perform translations across a single axis at a time.", "confirm=False): '''Translate the printerm tool across the :math:`XYZ` space. printer73x can only perform", "_GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: '''Unix", "= '\\x00' '''Byte value that the MM12 returns when the script is running.'''", "= 940 ''':math:`Z` axis servo motor pulse width in units of quarter-:math:`\\\\mu s`", "outputs.''' SUB_STEPPER_PIXEL_TEMPLATE = '''sub {name} {{{{ntransitions}}}} {dir} {dir_channel} servo # set direction begin", "int Serial device name or port number number of the MM12 serial command", "True: if x == 0: break translate('X-P', confirm) x -= 1 if y", "and name of the port. Notes ----- Directly copied from example from `pyserial", "across :math:`X`. ``X+p`` send 1 single pulse for positive translation across :math:`X`. ``X-P``", "stepper motor (default is ``TRANSITIONS_PER_PIXEL``). delay : int, optional Delay (in milliseconds) between", "break translate('Y+P', confirm) y += 1 # To the left. print 'Printing across", "off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'X+P' : { 'subroutine_id' : 3, 'subroutine_body' :", "units of (0.25 us)/(10 ms)/(80 ms) (default is 0). servo_speed : int, optional", "if x == 0: break translate('X-P', confirm) x -= 1 print 'The image", "stepper motor drivers (how much the tool is translated depends on the microstep", "print_image(confirm=False): def report_position(x, y): print 'At row {0}, column {1}'.format(y, x) def print_img_pixel(x,", "report_position(x, y): print 'At row {0}, column {1}'.format(y, x) def print_img_pixel(x, y, confirm=False):", "element of :math:`\\mathbf{A}`, represents a pixel. Comparing :math:`\\mathbf{A}` with the input image from", ": { 'channel' : 4, 'on' : SRV_SIGNAL_CHANNEL_TARGET_OFF, 'off' : SRV_SIGNAL_CHANNEL_TARGET_ON, }, }", ": 'Z+', 'o' : 'Z-', } getch = Getch() while True: ch =", "img[i][j] = 0.0 else: img[i][j] = 1.0 # Check for pixel with and", "= termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch", "STEPPER_CHANNELS_TARGET_ON, 'step_channel': 1, }, 'Y' : { 'dir_channel' : 2, 'dir_positive' : STEPPER_CHANNELS_TARGET_ON,", "subroutines.''' MM12_SCRIPT_RUNNING = '\\x00' '''Byte value that the MM12 returns when the script", "''' def get_subroutine_key_by_id(subroutine_id): for key, value in MM12_SUBROUTINES.items(): if subroutine_id is value['subroutine_id']: return", "which have color'.format( imgpath, npixels, nprints) plt.close('all') if show: plt.imshow(img, cmap=cm.gray) plt.show() def", "been printed' except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' if __name__", "class _GetchUnix: '''Unix implementation of class ``Getch``.''' def __init__(self): import tty, sys def", "implementation of class ``Getch``.''' def __init__(self): import msvcrt def __call__(self): import msvcrt return", "``False``). Notes ----- Let :math:`\\mathbf{A}` be the matrix representation of the input image.", "manual_translation_mode(precise=True): '''Manually translate the printerm tool across the :math:`XY` plane. Parameters ---------- precise", "(default is 100). ''' def get_subroutine_key_by_id(subroutine_id): for key, value in MM12_SUBROUTINES.items(): if subroutine_id", "'''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel']) '''MM12 script initialization.''' MM12_SUBROUTINES = { 'X-p' : { 'subroutine_id' : 0,", "__init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() def on_exit(): '''Actions to", "of the row from :math:`a_{1,w-1}` to :math:`a_{1,0}`, and so on until there are", "if the corresponding pixel is black then the tool prints it. ''' def", "If ``True``, the user must confirm the translation by pressing Enter (default is", ":math:`Y`. ``Z-`` move the tool to the off position (:math:`Z`). ``Z+`` move the", "'Loading ``{0}``...'.format(imgpath) img = mpimg.imread(fname=imgpath, format='png') b, w = img.shape npixels = b", "= '0.09' # GLOBAL CONSTANT names. *if main* section at bottom sets global", "=============== connected connected 1 disconnected connected 2 connected disconnected 4 disconnected disconnected 8", "s` that drives the stepper channels high.''' STEPPER_CHANNELS_TARGET_OFF = 5600 '''Target value in", "following table to select the kind of translation you want to perform (where", "signal channel in units of (0.25 us)/(10 ms) (default is 100). ''' def", "if y == b - 1: break translate('Y+P', confirm) y += 1 print", "confirm) y += 1 print 'Returning to a_{{0, 0}}'.format(y) while True: if y", "as an element of :math:`\\mathbf{A}`, represents a pixel. Comparing :math:`\\mathbf{A}` with the input", "input image. :math:`a_{y,x}` as an element of :math:`\\mathbf{A}`, represents a pixel. Comparing :math:`\\mathbf{A}`", "================================================================ ``X-p`` send 1 single pulse for negative translation across :math:`X`. ``X+p`` send", "if img[i][j] > 0.0: nnotprints += 1 else: nprints += 1 assert (nnotprints", "0, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_neg_pulse', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X+p' :", "'Preparing to print an image with {0} rows and {1} columns'.format(b, w) print", "'Z' in adm: #time.sleep(0.1) def build_mm12_script(fpath, ntransitions=TRANSITIONS_PER_PIXEL, delay=1, servo_acceleration=0, servo_speed=100): '''Build a script", "{{servo_acceleration}} {servo_channel} acceleration {{servo_speed}} {servo_channel} speed '''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel']) '''MM12 script initialization.''' MM12_SUBROUTINES = {", "more rows to visit. In any position, if the corresponding pixel is black", "single pulse for negative translation across :math:`X`. ``X+p`` send 1 single pulse for", "the stepper channels high.''' STEPPER_CHANNELS_TARGET_OFF = 5600 '''Target value in units of quarter-:math:`\\\\mu", "x += 1 if y == b - 1: break translate('Y+P', confirm) y", "quarter-:math:`\\\\mu s` that enables printing (moves the tool down).''' SRV_SIGNAL_CHANNEL_TARGET_ON = 2175 SRV_SIGNAL_CHANNEL_TARGET_ON", "``{0}`` with {1} pixels, {2} of which have color'.format( imgpath, npixels, nprints) plt.close('all')", "the input image. :math:`a_{y,x}` as an element of :math:`\\mathbf{A}`, represents a pixel. Comparing", "assert isinstance(intarg, int) with open(fpath, 'w') as f: print >>f, MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration, servo_speed=servo_speed) for", "is value['subroutine_id']: return key for intarg in (ntransitions, delay, servo_acceleration, servo_speed): assert isinstance(intarg,", "tool prints it. ''' def report_position(x, y): print 'At row {0}, column {1}'.format(y,", ":math:`a_{1,0}`, and so on until there are no more rows to visit. In", "'X-P' : { 'subroutine_id' : 2, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_neg_pixel', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF,", "translation in units of single low-to-high transitions sent to the stepper motor drivers", "i in range(256): try: s = serial.Serial(i) available.append( (i, s.portstr)) s.close() except serial.SerialException:", "x -= 1 if y == b - 1: break translate('Y+P', confirm) y", "x == w - 1: break translate('X+P', confirm) x += 1 if y", "of pixels,''' SUB_STEPPER_PULSE_TEMPLATE = '''sub {name} {dir} {dir_channel} servo # set direction {off}", "speed of the servo signal channel in units of (0.25 us)/(10 ms) (default", "black then the tool prints it. ''' def report_position(x, y): print 'At row", "sent to the stepper motor drivers (how much the tool is translated depends", "Does not echo to the screen. References ========== .. [GETCHRECIPE] http://code.activestate.com/recipes/134892/ \"\"\" def", "delay=1, servo_acceleration=0, servo_speed=100): '''Build a script to be loaded on the MM12. Parameters", "printerc execute these routines in order to produce the trajectory of the tool", "image has been printed' except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port'", "*MS1* and *MS2*. Use the following table to set this constant: ============ ============", "Let :math:`\\mathbf{A}` be the matrix representation of the input image. :math:`a_{y,x}` as an", "y += 1 # To the left. print 'Printing across the row {0}'.format(y)", "except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' if __name__ == \"__main__\":", "the numerical control of the **printer73x** system. printerc drives printerm through mcircuit; printerc", "that drive a stepper motor in units of pixels,''' SUB_STEPPER_PULSE_TEMPLATE = '''sub {name}", "pulses for positive translation across :math:`Y`. ``Z-`` move the tool to the off", "'Printing across the row {0}'.format(y) while True: report_position(x, y) print_img_pixel(x, y, confirm) if", "SRV_SIGNAL_CHANNEL_TARGET_ON, }, } '''Configuration of the MM12 channels for the servo and stepper", "''' '''Template for the MM12 script subroutines that drive a stepper motor in", "not echo to the screen. References ========== .. [GETCHRECIPE] http://code.activestate.com/recipes/134892/ \"\"\" def __init__(self):", "{position} {channel} servo begin get_moving_state while # wait until is is no longer", "Returns ------- script_status : {``MM12_SCRIPT_RUNNING``, ``MM12_SCRIPT_STOPPED``} ''' assert sp.write('\\xae') == 1 return sp.read(1)", "port number number of the MM12 serial command port. ''' global sp sp", "2, 'dir_positive' : STEPPER_CHANNELS_TARGET_ON, 'dir_negative' : STEPPER_CHANNELS_TARGET_OFF, 'step_channel': 3, }, 'Z' : {", "corner of the input image. #. :math:`a_{b-1,w-1}` corresponds to the lower right corner", "mcircuit is coupled to printerm through the motors. mcircuit (actually MM12, its subsystem)", "project. ''' available = [] for i in range(256): try: s = serial.Serial(i)", "line interface for the numerical control of the **printer73x** system. printerc drives printerm", "visits every element of the row from :math:`a_{1,w-1}` to :math:`a_{1,0}`, and so on", "(default is ``False``). Notes ----- This function sets the following global names: **img**", "j in range(w): if img[i][j] < 0.9: img[i][j] = 0.0 else: img[i][j] =", "'''Number of steps the stepper motor needs to translate 1 pixel across the", ".. note:: Both stepper motor driver boards must have the same jumper configuration.", "positive translation across :math:`X`. ``Y-p`` send 1 single pulse for negative translation across", "+= 1 if y == b - 1: translate('Z-') break translate('Y+P', confirm) y", "that drives the stepper channels high.''' STEPPER_CHANNELS_TARGET_OFF = 5600 '''Target value in units", "image. Starting from the HOME position the printerm tool visit every element of", "1 single pulse for negative translation across :math:`Y`. ``Y+p`` send 1 single pulse", "while True: ch = getch() if ch not in keys2translation.keys(): break while mm12_script_status()", "'k' : 'Y-P', 'i' : 'Z+', 'o' : 'Z-', } getch = Getch()", "quarter-:math:`\\\\mu s` that disables printing (moves the tool up).''' STEPPER_CHANNELS_TARGET_ON = 6800 '''Target", "'''Byte value that the MM12 returns when the script is stopped.''' # ==========================================================================", "then no pixel will be printed. assert nprints > 0 print 'Loaded ``{0}``", "nprints) plt.close('all') if show: plt.imshow(img, cmap=cm.gray) plt.show() def connect_printerm(commandport_id): '''Connect printerc with printerm", "send 1 single pulse for positive translation across :math:`Y`. ``Y-P`` send :math:`n` pulses", "controller for the printer73x system. **printerc** is an interactive command line interface for", "boolean, optional Invert the image if ``True`` (default is ``False``). show : boolean,", "+= 1 print 'Printing across the row {0}'.format(y) while True: report_position(x, y) print_img_pixel(x,", "'subroutine_id' : 3, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_pos_pixel', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ),", "if pixel == 0.0: return True return False try: msg = 'Preparing to", "width in units of quarter-:math:`\\\\mu s` that disables printing (moves the tool up).'''", "no longer moving. repeat 75 delay quit ''' '''Template for the MM12 script", "= 5600 '''Target value in units of quarter-:math:`\\\\mu s` that drives the stepper", "# Invoke the garbage collector. gc.collect() def scan_serial_ports(): '''Scan system for available physical", "#. :math:`a_{0,0}` corresponds to the upper left corner of the input image. #.", "def scan_serial_ports(): '''Scan system for available physical or virtual serial ports. Returns -------", "name='x_pos_pixel', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y-p' : { 'subroutine_id' :", "must have the same jumper configuration. ''' STEPS_PER_PIXEL = 90 '''Number of steps", "serial.Serial(i) available.append( (i, s.portstr)) s.close() except serial.SerialException: pass return available def mm12_script_status(): '''Indicate", "or virtual serial ports. Returns ------- available : list of tuples Each element", "============ ============ =============== MS1 MS2 TRANSITIONS_PER_STEP ============ ============ =============== connected connected 1 disconnected", "units of quarter-:math:`\\\\mu s` that disables printing (moves the tool up).''' STEPPER_CHANNELS_TARGET_ON =", "'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_pos_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Z-' :", "while # wait until is is no longer moving. repeat 75 delay quit", "columns in the array representation. ''' global img, b, w print 'Loading ``{0}``...'.format(imgpath)", "needs to translate 1 pixel across the :math:`X` or :math:`Y` axes.''' TRANSITIONS_PER_PIXEL =", "not in keys2translation.keys(): break while mm12_script_status() == MM12_SCRIPT_RUNNING: pass translate(keys2translation[ch], confirm=False) def print_pixel(confirm=False):", "== 0: break translate('Y-P', confirm) y -= 1 print 'The image has been", "1 else: nprints += 1 assert (nnotprints + nprints) == npixels # If", ":math:`n` pulses for negative translation across :math:`X`. ``X+P`` send :math:`n` pulses for positive", "while True: print 'Printing across the row {0}'.format(y) while True: report_position(x, y) print_img_pixel(x,", "line interface.''' # MM12 # ========================================================================== TRANSITIONS_PER_STEP = 2 '''The board sets the", "get_moving_state while # wait until is is no longer moving. repeat 75 delay", "# Author: <NAME> # Contact: <EMAIL> '''Numerical controller for the printer73x system. **printerc**", "positive translation across :math:`Y`. ``Z-`` move the tool to the off position (:math:`Z`).", "---------- imgpath : str-like Path to the image file. Must be PNG, 8-bit", "through the stepper motor (default is ``TRANSITIONS_PER_PIXEL``). delay : int, optional Delay (in", "[] for i in range(256): try: s = serial.Serial(i) available.append( (i, s.portstr)) s.close()", "translation in units of pixels (default is True). ''' if precise: keys2translation =", "sets global names too. # ========================================================================== # ========================================================================== LOGF = 'log.rst' '''Path to", "range(len( MM12_SUBROUTINES)): subroutine_key = get_subroutine_key_by_id(i) subroutine_body = MM12_SUBROUTINES[subroutine_key]['subroutine_body'] if 'Z' not in subroutine_key:", "garbage collector. gc.collect() def scan_serial_ports(): '''Scan system for available physical or virtual serial", "motor pulse width in units of quarter-:math:`\\\\mu s` that disables printing (moves the", "1 disconnected connected 2 connected disconnected 4 disconnected disconnected 8 ============ ============ ===============", "nprints = nnotprints = 0 assert (b > 0) and (w > 0)", "'dir_negative' : STEPPER_CHANNELS_TARGET_OFF, 'step_channel': 3, }, 'Z' : { 'channel' : 4, 'on'", ": str-like Path location where to save the script file. ntransitions : int,", "confirm) x -= 1 print 'The image has been printed' except KeyboardInterrupt: sp.flush()", "== npixels # If ``nprints == 0`` then no pixel will be printed.", "# Related third party imports. import serial import IPython import numpy as np", "b - 1: break translate('Y+P', confirm) y += 1 print 'Printing across the", "translation across :math:`X`. ``Y-p`` send 1 single pulse for negative translation across :math:`Y`.", "assert nprints > 0 print 'Loaded ``{0}`` with {1} pixels, {2} of which", "the MM12 script subroutines that drive a stepper motor in units of low-to-high", "msg x = y = z = 0 # We are at HOME", "off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y-P' : { 'subroutine_id' : 6, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format(", "5600 '''Target value in units of quarter-:math:`\\\\mu s` that drives the stepper channels", "units of pixels through the stepper motor (default is ``TRANSITIONS_PER_PIXEL``). delay : int,", "of low-to-high transitions the stepper motors need to translate 1 pixel across the", "the image. ''' # Standard library imports. from __future__ import division from pprint", "confirm=False): if img[y][x] == 0.0: print_pixel(confirm) try: msg = 'Preparing to print an", ":math:`X` or :math:`Y` axes.''' TRANSITIONS_PER_PIXEL = STEPS_PER_PIXEL * TRANSITIONS_PER_STEP '''Number of low-to-high transitions", "confirm) x += 1 print 'Returning to a_{{{0}, 0}}'.format(y) while True: if x", "stopped.''' # ========================================================================== # ========================================================================== # ========================================================================== class Getch: \"\"\"Gets a single character", "number of the MM12 serial command port. ''' global sp sp = serial.Serial(port=commandport_id)", "True: report_position(x, y) if img[y][x] == 0.0: translate('Z+', confirm) try: if img[y][x+1] !=", "'''Automatically print the input image. Parameters ---------- confirm : boolean, optional Wait for", "= { 'X' : { 'dir_channel' : 0, 'dir_positive' : STEPPER_CHANNELS_TARGET_OFF, 'dir_negative' :", "{{delay}} delay 1 minus repeat quit ''' '''Template for the MM12 script subroutines", "example from `pyserial <http://sourceforge.net/projects/pyserial/files/package>`_ project. ''' available = [] for i in range(256):", "in mcircuit). If ``False`` perform translation in units of pixels (default is True).", "'Y+P', 'k' : 'Y-P', 'i' : 'Z+', 'o' : 'Z-', } getch =", "the tool down).''' SRV_SIGNAL_CHANNEL_TARGET_ON = 2175 SRV_SIGNAL_CHANNEL_TARGET_ON = 1580 ''':math:`Z` axis servo motor", "plt.close('all') if show: plt.imshow(img, cmap=cm.gray) plt.show() def connect_printerm(commandport_id): '''Connect printerc with printerm through", "us)/(10 ms) (default is 100). ''' def get_subroutine_key_by_id(subroutine_id): for key, value in MM12_SUBROUTINES.items():", "MM12_SUBROUTINES = { 'X-p' : { 'subroutine_id' : 0, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_neg_pulse',", "translations across a single axis at a time. Parameters ---------- adm: str *adm*", "sp.read(1) def translate(adm, confirm=False): '''Translate the printerm tool across the :math:`XYZ` space. printer73x", ": 'X-P', 'l' : 'X+P', 'j' : 'Y+P', 'k' : 'Y-P', 'i' :", "3, }, 'Z' : { 'channel' : 4, 'on' : SRV_SIGNAL_CHANNEL_TARGET_OFF, 'off' :", "the tool is translated depends on the microstep format selected through the XMS1,", "high.''' STEPPER_CHANNELS_TARGET_OFF = 5600 '''Target value in units of quarter-:math:`\\\\mu s` that drives", "to a_{{0, 0}}'.format(y) while True: if y == 0: break translate('Y-P', confirm) y", "1 single pulse for positive translation across :math:`Y`. ``Y-P`` send :math:`n` pulses for", "Path location where to save the script file. ntransitions : int, optional Number", "table to select the kind of translation you want to perform (where :math:`n`", "physical or virtual serial ports. Returns ------- available : list of tuples Each", "the following table to set this constant: ============ ============ =============== MS1 MS2 TRANSITIONS_PER_STEP", "a precise but slow translation.''' SUB_SERVO_TEMPLATE = '''sub {name} {position} {channel} servo begin", "if subroutine_id is value['subroutine_id']: return key for intarg in (ntransitions, delay, servo_acceleration, servo_speed):", "(logf, sys.stdout): print >>f, msg def manual_translation_mode(precise=True): '''Manually translate the printerm tool across", "STEPPER_CHANNELS_TARGET_OFF, 'dir_negative' : STEPPER_CHANNELS_TARGET_ON, 'step_channel': 1, }, 'Y' : { 'dir_channel' : 2,", "------- available : list of tuples Each element of the list is a", "confirm=False) translate('Z-', confirm=False) def print_image(confirm=False): def report_position(x, y): print 'At row {0}, column", "tool visit every element of the row from :math:`a_{0,0}` to :math:`a_{0,w-1}` then moves", "msg = 'Preparing to print an image with {0} rows and {1} columns'.format(b,", "interface.''' # MM12 # ========================================================================== TRANSITIONS_PER_STEP = 2 '''The board sets the microstepping", "return True return False try: msg = 'Preparing to print an image with", "-= 1 if y == b - 1: break translate('Y+P', confirm) y +=", "the port. Notes ----- Directly copied from example from `pyserial <http://sourceforge.net/projects/pyserial/files/package>`_ project. '''", "printing (moves the tool down).''' SRV_SIGNAL_CHANNEL_TARGET_ON = 2175 SRV_SIGNAL_CHANNEL_TARGET_ON = 1580 ''':math:`Z` axis", "References ========== .. [GETCHRECIPE] http://code.activestate.com/recipes/134892/ \"\"\" def __init__(self): try: self.impl = _GetchWindows() except", "CONSTANT names. *if main* section at bottom sets global names too. # ==========================================================================", "serial import IPython import numpy as np # remove import matplotlib.image as mpimg", "control of the **printer73x** system. printerc drives printerm through mcircuit; printerc stablishes a", "''.join(['\\xa7', subroutine_id]) if confirm: raw_input() assert sp.write(str2write) == 2 #if 'Z' in adm:", "microstep format selected through the XMS1, XMS2, YMS1, YMS2 jumpers in mcircuit). If", "kind of translation you want to perform (where :math:`n` is the number of", "}, 'Z-' : { 'subroutine_id' : 8, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_off', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['off']*4)", "True: report_position(x, y) if img[y][x] == 0.0: translate('Z+', confirm) if img[y][x-1] != 0.0:", "for f in (logf, sys.stdout): print >>f, msg def manual_translation_mode(precise=True): '''Manually translate the", "'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_pos_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y-P' : {", "pulse width in units of quarter-:math:`\\\\mu s` that disables printing (moves the tool", "delay {on} {step_channel} servo {{delay}} delay quit ''' '''Template for the MM12 script", "), }, 'Y-p' : { 'subroutine_id' : 4, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_neg_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_negative'],", "If ``False`` perform translation in units of pixels (default is True). ''' if", "from :math:`a_{1,w-1}` to :math:`a_{1,0}`, and so on until there are no more rows", "(in milliseconds) between each transition in the subroutines that perform translation through the", "= y = z = 0 # We are at HOME position. while", "``True``, the user must confirm the translation by pressing Enter (default is ``False``).", "PN = os.path.splitext(sys.argv[0])[0] logf = open(LOGF, 'w') print >>logf, 'START' atexit.register(on_exit) IPython.Shell.IPShellEmbed()( INTRO_MSG)", "black and white, no grays. for i in range(b): for j in range(w):", "stablishes a serial connection with mcircuit, and mcircuit is coupled to printerm through", "translation across :math:`Y`. ``Y+p`` send 1 single pulse for positive translation across :math:`Y`.", "< 0.9: img[i][j] = 0.0 else: img[i][j] = 1.0 if invert: print 'Inverting", "delay 1 minus repeat quit ''' '''Template for the MM12 script subroutines that", "'j' : 'Y+p', 'k' : 'Y-p', 'i' : 'Z+', 'o' : 'Z-', }", "to translate 1 pixel across the :math:`X` or :math:`Y` axes.''' SRV_SIGNAL_CHANNEL_TARGET_OFF = 940", "msvcrt return msvcrt.getch() def on_exit(): '''Actions to do on exit.''' try: print >>logf,", "{ 'dir_channel' : 2, 'dir_positive' : STEPPER_CHANNELS_TARGET_ON, 'dir_negative' : STEPPER_CHANNELS_TARGET_OFF, 'step_channel': 3, },", "step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y-P' : { 'subroutine_id' : 6, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_neg_pixel',", "translate 1 pixel across the :math:`X` or :math:`Y` axes.''' TRANSITIONS_PER_PIXEL = STEPS_PER_PIXEL *", "running or stopped. Returns ------- script_status : {``MM12_SCRIPT_RUNNING``, ``MM12_SCRIPT_STOPPED``} ''' assert sp.write('\\xae') ==", "subroutine_id = chr( MM12_SUBROUTINES[adm]['subroutine_id']) str2write = ''.join(['\\xa7', subroutine_id]) if confirm: raw_input() assert sp.write(str2write)", "the list is a ``(num, name)`` tuple with the number and name of", "numpy as np # remove import matplotlib.image as mpimg import matplotlib.pyplot as plt", "0`` then no pixel will be printed. assert nprints > 0 print 'Loaded", ": str-like Path to the image file. Must be PNG, 8-bit grayscale, non-interlaced.", "just opened *command port* ``{1}``'.format(PN, sp.port) msg = '``{0}`` is now connected to", "subroutines that drive a stepper motor in units of pixels,''' SUB_STEPPER_PULSE_TEMPLATE = '''sub", "# MM12 # ========================================================================== TRANSITIONS_PER_STEP = 2 '''The board sets the microstepping format", "1 print 'Returning to a_{{0, 0}}'.format(y) while True: if y == 0: break", ":math:`Z` axis, and then printerc execute these routines in order to produce the", "== 0.0: print_pixel(confirm) def color_in_this_row(row): for pixel in row: if pixel == 0.0:", "int, optional Sets the acceleration of the servo signal channel in units of", "command port' if __name__ == \"__main__\": # program name from file name. PN", "for negative translation across :math:`Y`. ``Y+p`` send 1 single pulse for positive translation", "delay : int, optional Delay (in milliseconds) between each transition in the subroutines", "{step_channel} servo {{delay}} delay quit ''' '''Template for the MM12 script subroutines that", "stopped. Returns ------- script_status : {``MM12_SCRIPT_RUNNING``, ``MM12_SCRIPT_STOPPED``} ''' assert sp.write('\\xae') == 1 return", "across :math:`Y`. ``Y+P`` send :math:`n` pulses for positive translation across :math:`Y`. ``Z-`` move", "= z = 0 # We are at HOME position. while True: #", "1: translate('Z-') break translate('Y+P', confirm) y += 1 # To the left. print", "is stopped.''' # ========================================================================== # ========================================================================== # ========================================================================== class Getch: \"\"\"Gets a single", "any position, if the corresponding pixel is black then the tool prints it.", "if confirm: raw_input() assert sp.write(str2write) == 2 #if 'Z' in adm: #time.sleep(0.1) def", "optional Sets the acceleration of the servo signal channel in units of (0.25", ":math:`X`. ``X+p`` send 1 single pulse for positive translation across :math:`X`. ``X-P`` send", ":math:`XYZ` space. printer73x can only perform translations across a single axis at a", "be PNG, 8-bit grayscale, non-interlaced. invert : boolean, optional Invert the image if", "print 'Inverting image...' for i in range(b): for j in range(w): if img[i][j]", "the :math:`X`, :math:`Y` and :math:`Z` axis, and then printerc execute these routines in", "as cm # Same as **printer73x**. __version__ = '0.09' # GLOBAL CONSTANT names.", "str or int Serial device name or port number number of the MM12", "print_img_pixel(x, y, confirm) if x == w - 1: break translate('X+P', confirm) x", "b, w print 'Loading ``{0}``...'.format(imgpath) img = mpimg.imread(fname=imgpath, format='png') b, w = img.shape", "os import atexit import gc import time # Related third party imports. import", "is translated depends on the microstep format selected through the XMS1, XMS2, YMS1,", "def report_position(x, y): print 'At row {0}, column {1}'.format(y, x) def print_img_pixel(x, y,", "= sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: '''Windows implementation of", ":math:`a_{0,0}` corresponds to the upper left corner of the input image. #. :math:`a_{b-1,w-1}`", "========================================================================== # ========================================================================== # ========================================================================== class Getch: \"\"\"Gets a single character from standard", "gc.collect() def scan_serial_ports(): '''Scan system for available physical or virtual serial ports. Returns", "with printerm through the MM12 command port. Parameters ---------- commandport_id : str or", "coupled to printerm through the motors. mcircuit (actually MM12, its subsystem) loads in", "image from a front perspective: #. :math:`a_{0,0}` corresponds to the upper left corner", "is True). ''' if precise: keys2translation = { 'h' : 'X-p', 'l' :", "'channel' : 4, 'on' : SRV_SIGNAL_CHANNEL_TARGET_OFF, 'off' : SRV_SIGNAL_CHANNEL_TARGET_ON, }, } '''Configuration of", "print '\\nThanks for using ``printerc``!\\n' # Invoke the garbage collector. gc.collect() def scan_serial_ports():", "pixels through the stepper motor (default is ``TRANSITIONS_PER_PIXEL``). delay : int, optional Delay", "command port. ''' global sp sp = serial.Serial(port=commandport_id) assert sp.isOpen() print >>logf, '``{0}``", "KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' def print_image_better(confirm=False): def report_position(x, y):", "*adm* stands for Axis, Direction, Mode. Use the following table to select the", "using ``printerc``!\\n' # Invoke the garbage collector. gc.collect() def scan_serial_ports(): '''Scan system for", "low.''' MM12_AXES_CHANNELS = { 'X' : { 'dir_channel' : 0, 'dir_positive' : STEPPER_CHANNELS_TARGET_OFF,", "{name} {{{{ntransitions}}}} {dir} {dir_channel} servo # set direction begin dup while {off} {step_channel}", "0.0: print_pixel(confirm) try: msg = 'Preparing to print an image with {0} rows", "translate('Y+P', confirm) y += 1 print 'Returning to a_{{0, 0}}'.format(y) while True: if", "'dir_channel' : 0, 'dir_positive' : STEPPER_CHANNELS_TARGET_OFF, 'dir_negative' : STEPPER_CHANNELS_TARGET_ON, 'step_channel': 1, }, 'Y'", "remove import matplotlib.image as mpimg import matplotlib.pyplot as plt import matplotlib.cm as cm", "across the :math:`X`, :math:`Y` and :math:`Z` axis, and then printerc execute these routines", "To the right. print 'Printing across the row {0}'.format(y) while True: report_position(x, y)", "STEPPER_CHANNELS_TARGET_OFF, 'step_channel': 3, }, 'Z' : { 'channel' : 4, 'on' : SRV_SIGNAL_CHANNEL_TARGET_OFF,", "position=MM12_AXES_CHANNELS['Z']['on']*4) }, } '''Structure that builds and identifies the MM12 script subroutines.''' MM12_SCRIPT_RUNNING", "delay quit ''' '''Template for the MM12 script subroutine that drives the servo", "'''Actions to do on exit.''' try: print >>logf, 'Closing ``{0}`` *command port*'.format(sp.port) sp.close()", "while True: report_position(x, y) print_img_pixel(x, y, confirm) if x == w - 1:", "{{servo_speed}} {servo_channel} speed '''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel']) '''MM12 script initialization.''' MM12_SUBROUTINES = { 'X-p' : {", ": 'Z-', } getch = Getch() while True: ch = getch() if ch", "axis servo motor pulse width in units of quarter-:math:`\\\\mu s` that enables printing", "range(256): try: s = serial.Serial(i) available.append( (i, s.portstr)) s.close() except serial.SerialException: pass return", "the input image. Starting from the HOME position the printerm tool visit every", "servo {{delay}} delay {on} {step_channel} servo {{delay}} delay quit ''' '''Template for the", "Invoke the garbage collector. gc.collect() def scan_serial_ports(): '''Scan system for available physical or", "while True: report_position(x, y) if img[y][x] == 0.0: translate('Z+', confirm) if img[y][x-1] !=", "= ''.join(['\\xa7', subroutine_id]) if confirm: raw_input() assert sp.write(str2write) == 2 #if 'Z' in", "section at bottom sets global names too. # ========================================================================== # ========================================================================== LOGF =", "y, confirm) if x == w - 1: break translate('X+P', confirm) x +=", "to select the kind of translation you want to perform (where :math:`n` is", "have color'.format( imgpath, npixels, nprints) plt.close('all') if show: plt.imshow(img, cmap=cm.gray) plt.show() def connect_printerm(commandport_id):", "drives the servo motor.''' MM12_SCRIPT_INIT = '''\\ {{servo_acceleration}} {servo_channel} acceleration {{servo_speed}} {servo_channel} speed", "optional Invert the image if ``True`` (default is ``False``). show : boolean, optional", "at HOME position. while True: # To the right. print 'Printing across the", "mm12_script_status(): '''Indicate whether the MM12 script is running or stopped. Returns ------- script_status", "in units of pixels through the stepper motor (default is ``TRANSITIONS_PER_PIXEL``). delay :", "j in range(w): if img[i][j] > 0.0: nnotprints += 1 else: nprints +=", "in units of low-to-high transitions, for a precise but slow translation.''' SUB_SERVO_TEMPLATE =", ":math:`Y`. ``Y+P`` send :math:`n` pulses for positive translation across :math:`Y`. ``Z-`` move the", "by printerm. Parameters ---------- imgpath : str-like Path to the image file. Must", "== 0: break translate('Y-P', confirm) y -= 1 while True: if x ==", "img[y][x] == 0.0: print_pixel(confirm) try: msg = 'Preparing to print an image with", "pulses for the printerm tool to translate a pixel unit across the respective", "disables printing (moves the tool up).''' STEPPER_CHANNELS_TARGET_ON = 6800 '''Target value in units", "the row from :math:`a_{0,0}` to :math:`a_{0,w-1}` then moves to the next row (:math:`a_{1,w-1}`)", "sp.write('\\xae') == 1 return sp.read(1) def translate(adm, confirm=False): '''Translate the printerm tool across", "if ``True`` (default is ``False``). show : boolean, optional Show the image if", ": 8, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_off', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['off']*4) }, 'Z+' : { 'subroutine_id'", "in units of quarter-:math:`\\\\mu s` that disables printing (moves the tool up).''' STEPPER_CHANNELS_TARGET_ON", "of single low-to-high transitions sent to the stepper motor drivers (how much the", "!= 0.0: translate('Z-', confirm) except IndexError as e: pass if x == w", "translate('Y-P', confirm) y -= 1 print 'The image has been printed' except KeyboardInterrupt:", "========== .. [GETCHRECIPE] http://code.activestate.com/recipes/134892/ \"\"\" def __init__(self): try: self.impl = _GetchWindows() except ImportError:", "break translate('X-P', confirm) x -= 1 if y == b - 1: translate('Z-')", "assert sp.write('\\xae') == 1 return sp.read(1) def translate(adm, confirm=False): '''Translate the printerm tool", "1580 ''':math:`Z` axis servo motor pulse width in units of quarter-:math:`\\\\mu s` that", "= mpimg.imread(fname=imgpath, format='png') b, w = img.shape npixels = b * w nprints", "(default is ``False``). show : boolean, optional Show the image if ``True`` (default", "img[i][j] < 0.9: img[i][j] = 0.0 else: img[i][j] = 1.0 if invert: print", "copied from example from `pyserial <http://sourceforge.net/projects/pyserial/files/package>`_ project. ''' available = [] for i", "9, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_on', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['on']*4) }, } '''Structure that builds and", "self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class", "command line interface.''' # MM12 # ========================================================================== TRANSITIONS_PER_STEP = 2 '''The board sets", "identifies the MM12 script subroutines.''' MM12_SCRIPT_RUNNING = '\\x00' '''Byte value that the MM12", "MM12 command port. Parameters ---------- commandport_id : str or int Serial device name", "name or port number number of the MM12 serial command port. ''' global", "termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: '''Windows implementation of class ``Getch``.''' def", "def on_exit(): '''Actions to do on exit.''' try: print >>logf, 'Closing ``{0}`` *command", "color'.format( imgpath, npixels, nprints) plt.close('all') if show: plt.imshow(img, cmap=cm.gray) plt.show() def connect_printerm(commandport_id): '''Connect", "1 print 'Printing across the row {0}'.format(y) while True: report_position(x, y) print_img_pixel(x, y,", "print 'The image has been printed' except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing", "a ``(num, name)`` tuple with the number and name of the port. Notes", "+= 1 if y == b - 1: break translate('Y+P', confirm) y +=", "try: msg = 'Preparing to print an image with {0} rows and {1}", "stepper channels high.''' STEPPER_CHANNELS_TARGET_OFF = 5600 '''Target value in units of quarter-:math:`\\\\mu s`", "We are at HOME position. while True: print 'Printing across the row {0}'.format(y)", "print >>logf, 'END' logf.close() print '\\nThanks for using ``printerc``!\\n' # Invoke the garbage", "open(fpath, 'w') as f: print >>f, MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration, servo_speed=servo_speed) for i in range(len( MM12_SUBROUTINES)):", "2175 SRV_SIGNAL_CHANNEL_TARGET_ON = 1580 ''':math:`Z` axis servo motor pulse width in units of", "image. ''' # Standard library imports. from __future__ import division from pprint import", "Axis, Direction, Mode. Use the following table to select the kind of translation", "for positive translation across :math:`X`. ``X-P`` send :math:`n` pulses for negative translation across", "> 0.0: img[i][j] = 0.0 else: img[i][j] = 1.0 # Check for pixel", "for negative translation across :math:`Y`. ``Y+P`` send :math:`n` pulses for positive translation across", "servo_speed=servo_speed) for i in range(len( MM12_SUBROUTINES)): subroutine_key = get_subroutine_key_by_id(i) subroutine_body = MM12_SUBROUTINES[subroutine_key]['subroutine_body'] if", "interrupted, flushing command port' if __name__ == \"__main__\": # program name from file", "MS1 MS2 TRANSITIONS_PER_STEP ============ ============ =============== connected connected 1 disconnected connected 2 connected", "---------- commandport_id : str or int Serial device name or port number number", "row {0}, column {1}'.format(y, x) def print_img_pixel(x, y, confirm=False): if img[y][x] == 0.0:", "= 2175 SRV_SIGNAL_CHANNEL_TARGET_ON = 1580 ''':math:`Z` axis servo motor pulse width in units", "when the script is running.''' MM12_SCRIPT_STOPPED = '\\x01' '''Byte value that the MM12", "raw_input() translate('Z+', confirm=False) translate('Z-', confirm=False) def print_image(confirm=False): def report_position(x, y): print 'At row", "while True: if x == 0: break translate('X-P', confirm) x -= 1 if", "'The image has been printed' except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command", "element of the row from :math:`a_{1,w-1}` to :math:`a_{1,0}`, and so on until there", "image...' # only total black and white, no grays. for i in range(b):", "script subroutines.''' MM12_SCRIPT_RUNNING = '\\x00' '''Byte value that the MM12 returns when the", "'X-p' : { 'subroutine_id' : 0, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_neg_pulse', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF,", "print 'Printing across the row {0}'.format(y) while True: report_position(x, y) if img[y][x] ==", ".. [GETCHRECIPE] http://code.activestate.com/recipes/134892/ \"\"\" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl", "you want to perform (where :math:`n` is the number of pulses for the", "} else: keys2translation = { 'h' : 'X-P', 'l' : 'X+P', 'j' :", "import os import atexit import gc import time # Related third party imports.", "note:: Both stepper motor driver boards must have the same jumper configuration. '''", "until script is not running. while mm12_script_status() == MM12_SCRIPT_RUNNING: pass subroutine_id = chr(", "break translate('Y-P', confirm) y -= 1 print 'The image has been printed' except", "row from :math:`a_{1,w-1}` to :math:`a_{1,0}`, and so on until there are no more", ": SUB_SERVO_TEMPLATE.format( name='z_position_on', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['on']*4) }, } '''Structure that builds and identifies the", "def translate(adm, confirm=False): '''Translate the printerm tool across the :math:`XYZ` space. printer73x can", "GLOBAL CONSTANT names. *if main* section at bottom sets global names too. #", ": 4, 'on' : SRV_SIGNAL_CHANNEL_TARGET_OFF, 'off' : SRV_SIGNAL_CHANNEL_TARGET_ON, }, } '''Configuration of the", "by pressing Enter (default is ``False``). ''' # Start until script is not", "left corner of the input image. #. :math:`a_{b-1,w-1}` corresponds to the lower right", "off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Z-' : { 'subroutine_id' : 8, 'subroutine_body' :", "stepper motor in units of low-to-high transitions, for a precise but slow translation.'''", "Show the image if ``True`` (default is ``False``). Notes ----- This function sets", "dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y+P' : { 'subroutine_id' : 7, 'subroutine_body'", "pulses for negative translation across :math:`X`. ``X+P`` send :math:`n` pulses for positive translation", "= getch() if ch not in keys2translation.keys(): break while mm12_script_status() == MM12_SCRIPT_RUNNING: pass", "Invert the image if ``True`` (default is ``False``). show : boolean, optional Show", "from a front perspective: #. :math:`a_{0,0}` corresponds to the upper left corner of", "and mcircuit is coupled to printerm through the motors. mcircuit (actually MM12, its", "return ch class _GetchWindows: '''Windows implementation of class ``Getch``.''' def __init__(self): import msvcrt", "pass print >>logf, 'END' logf.close() print '\\nThanks for using ``printerc``!\\n' # Invoke the", "'Z+', 'o' : 'Z-', } else: keys2translation = { 'h' : 'X-P', 'l'", "then printerc execute these routines in order to produce the trajectory of the", "subroutine_body.format(ntransitions=ntransitions) print >>f, subroutine_body def prepare_img(imgpath, invert=False, show=False): '''Perform any necessary processing for", "time. Parameters ---------- adm: str *adm* stands for Axis, Direction, Mode. Use the", "while True: if y == 0: break translate('Y-P', confirm) y -= 1 while", "perform translation in units of single low-to-high transitions sent to the stepper motor", "of the **printer73x** system. printerc drives printerm through mcircuit; printerc stablishes a serial", "``TRANSITIONS_PER_PIXEL``). delay : int, optional Delay (in milliseconds) between each transition in the", "of (0.25 us)/(10 ms) (default is 100). ''' def get_subroutine_key_by_id(subroutine_id): for key, value", "for negative translation across :math:`X`. ``X+P`` send :math:`n` pulses for positive translation across", "# If ``nprints == 0`` then no pixel will be printed. assert nprints", "'X+p', 'j' : 'Y+p', 'k' : 'Y-p', 'i' : 'Z+', 'o' : 'Z-',", "of low-to-high transitions, for a precise but slow translation.''' SUB_SERVO_TEMPLATE = '''sub {name}", "'l' : 'X+P', 'j' : 'Y+P', 'k' : 'Y-P', 'i' : 'Z+', 'o'", "subroutine_key = get_subroutine_key_by_id(i) subroutine_body = MM12_SUBROUTINES[subroutine_key]['subroutine_body'] if 'Z' not in subroutine_key: subroutine_body =", "break translate('X-P', confirm) x -= 1 print 'The image has been printed' except", "motor (default is ``TRANSITIONS_PER_PIXEL``). delay : int, optional Delay (in milliseconds) between each", "representation of the image. **b** : int Image's height, number of rows in", "# set direction {off} {step_channel} servo {{delay}} delay {on} {step_channel} servo {{delay}} delay", "= 0 # We are at HOME position. while True: print 'Printing across", "= '''sub {name} {{{{ntransitions}}}} {dir} {dir_channel} servo # set direction begin dup while", "*command port*'.format(sp.port) sp.close() except NameError: pass print >>logf, 'END' logf.close() print '\\nThanks for", "global names: **img** : array of booleans 2-d array representation of the image.", "through mcircuit; printerc stablishes a serial connection with mcircuit, and mcircuit is coupled", "screen. References ========== .. [GETCHRECIPE] http://code.activestate.com/recipes/134892/ \"\"\" def __init__(self): try: self.impl = _GetchWindows()", "except NameError: pass print >>logf, 'END' logf.close() print '\\nThanks for using ``printerc``!\\n' #", "a script to be loaded on the MM12. Parameters ---------- fpath : str-like", ": { 'subroutine_id' : 0, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_neg_pulse', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'],", "translate the printerm tool across the :math:`XY` plane. Parameters ---------- precise : boolean,", "for positive translation across :math:`X`. ``Y-p`` send 1 single pulse for negative translation", "``{0}``...'.format(imgpath) img = mpimg.imread(fname=imgpath, format='png') b, w = img.shape npixels = b *", "to :math:`a_{1,0}`, and so on until there are no more rows to visit.", "'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_neg_pulse', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X+p' : {", ":math:`n` is the number of pulses for the printerm tool to translate a", "step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X-P' : { 'subroutine_id' : 2, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_neg_pixel',", "str-like Path to the image file. Must be PNG, 8-bit grayscale, non-interlaced. invert", "== 0.0: translate('Z+', confirm) try: if img[y][x+1] != 0.0: translate('Z-', confirm) except IndexError", "translations across the :math:`X`, :math:`Y` and :math:`Z` axis, and then printerc execute these", "row {0}'.format(y) while True: report_position(x, y) if img[y][x] == 0.0: translate('Z+', confirm) if", "} getch = Getch() while True: ch = getch() if ch not in", "translate('Z+', confirm=False) translate('Z-', confirm=False) def print_image(confirm=False): def report_position(x, y): print 'At row {0},", "channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['off']*4) }, 'Z+' : { 'subroutine_id' : 9, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_on',", "a pixel unit across the respective axis). ======= ================================================================ *adm* translation ======= ================================================================", "on_exit(): '''Actions to do on exit.''' try: print >>logf, 'Closing ``{0}`` *command port*'.format(sp.port)", "``X+P`` send :math:`n` pulses for positive translation across :math:`X`. ``Y-p`` send 1 single", "print_image_better_better(confirm=False): '''Automatically print the input image. Parameters ---------- confirm : boolean, optional Wait", "'X-P', 'l' : 'X+P', 'j' : 'Y+P', 'k' : 'Y-P', 'i' : 'Z+',", "off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X-P' : { 'subroutine_id' : 2, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format(", "y += 1 print 'Printing across the row {0}'.format(y) while True: report_position(x, y)", "0 # We are at HOME position. while True: # To the right.", "confirm) except IndexError as e: pass if x == w - 1: translate('Z-')", ": SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_pos_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Z-' : {", "single low-to-high transitions sent to the stepper motor drivers (how much the tool", "are at HOME position. while True: # To the right. print 'Printing across", "1 print 'Returning to a_{{{0}, 0}}'.format(y) while True: if x == 0: break", "> 0) and (w > 0) print 'Processing the image...' # only total", "an element of :math:`\\mathbf{A}`, represents a pixel. Comparing :math:`\\mathbf{A}` with the input image", "termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally:", "Check for pixel with and without color. for i in range(b): for j", "trajectory of the tool printing the image. ''' # Standard library imports. from", "library imports. from __future__ import division from pprint import pprint import sys import", ": 6, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_neg_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), },", "is 1). servo_acceleration : int, optional Sets the acceleration of the servo signal", "True: report_position(x, y) print_img_pixel(x, y, confirm) if x == 0: break translate('X-P', confirm)", "not running. while mm12_script_status() == MM12_SCRIPT_RUNNING: pass subroutine_id = chr( MM12_SUBROUTINES[adm]['subroutine_id']) str2write =", "if ``True`` (default is ``False``). Notes ----- This function sets the following global", "+= 1 print 'Returning to a_{{0, 0}}'.format(y) while True: if y == 0:", "# ========================================================================== LOGF = 'log.rst' '''Path to the log file.''' INTRO_MSG = '''\\", "port' def print_image_better(confirm=False): def report_position(x, y): print 'At row {0}, column {1}'.format(y, x)", "1 single pulse for positive translation across :math:`X`. ``X-P`` send :math:`n` pulses for", "value['subroutine_id']: return key for intarg in (ntransitions, delay, servo_acceleration, servo_speed): assert isinstance(intarg, int)", "to the upper left corner of the input image. #. :math:`a_{b-1,w-1}` corresponds to", "'Printing across the row {0}'.format(y) while True: report_position(x, y) if img[y][x] == 0.0:", "row {0}'.format(y) while True: report_position(x, y) print_img_pixel(x, y, confirm) if x == 0:", "Sets the acceleration of the servo signal channel in units of (0.25 us)/(10", "that drives the stepper channels low.''' MM12_AXES_CHANNELS = { 'X' : { 'dir_channel'", "subroutine_body def prepare_img(imgpath, invert=False, show=False): '''Perform any necessary processing for the input image", "1 print 'The image has been printed' except KeyboardInterrupt: sp.flush() print 'Operation interrupted,", "msg def manual_translation_mode(precise=True): '''Manually translate the printerm tool across the :math:`XY` plane. Parameters", "row from :math:`a_{0,0}` to :math:`a_{0,w-1}` then moves to the next row (:math:`a_{1,w-1}`) and", "channel in units of (0.25 us)/(10 ms) (default is 100). ''' def get_subroutine_key_by_id(subroutine_id):", "system. **printerc** is an interactive command line interface for the numerical control of", "and (w > 0) print 'Processing the image...' # only total black and", "name from file name. PN = os.path.splitext(sys.argv[0])[0] logf = open(LOGF, 'w') print >>logf,", "== 2 #if 'Z' in adm: #time.sleep(0.1) def build_mm12_script(fpath, ntransitions=TRANSITIONS_PER_PIXEL, delay=1, servo_acceleration=0, servo_speed=100):", "8, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_off', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['off']*4) }, 'Z+' : { 'subroutine_id' :", "int Image's height, number of rows in the array representation. **w** : int", "# ========================================================================== class Getch: \"\"\"Gets a single character from standard input. Does not", "much the tool is translated depends on the microstep format selected through the", "plt import matplotlib.cm as cm # Same as **printer73x**. __version__ = '0.09' #", "stepper motors outputs.''' SUB_STEPPER_PIXEL_TEMPLATE = '''sub {name} {{{{ntransitions}}}} {dir} {dir_channel} servo # set", ": 2, 'dir_positive' : STEPPER_CHANNELS_TARGET_ON, 'dir_negative' : STEPPER_CHANNELS_TARGET_OFF, 'step_channel': 3, }, 'Z' :", "with {1} pixels, {2} of which have color'.format( imgpath, npixels, nprints) plt.close('all') if", ": SUB_SERVO_TEMPLATE.format( name='z_position_off', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['off']*4) }, 'Z+' : { 'subroutine_id' : 9, 'subroutine_body'", "{on} {step_channel} servo {{delay}} delay quit ''' '''Template for the MM12 script subroutines", "1 single pulse for negative translation across :math:`X`. ``X+p`` send 1 single pulse", "single character from standard input. Does not echo to the screen. References ==========", "plane. Parameters ---------- precise : boolean, optional If ``True``, perform translation in units", "the HOME position the printerm tool visit every element of the row from", "input image. #. :math:`a_{b-1,w-1}` corresponds to the lower right corner of the input", "of the input image. :math:`a_{y,x}` as an element of :math:`\\mathbf{A}`, represents a pixel.", "class ``Getch``.''' def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() def", "is ``False``). Notes ----- Let :math:`\\mathbf{A}` be the matrix representation of the input", "servo_acceleration=0, servo_speed=100): '''Build a script to be loaded on the MM12. Parameters ----------", "the MM12. Parameters ---------- fpath : str-like Path location where to save the", "tool across the :math:`XYZ` space. printer73x can only perform translations across a single", "column {1}'.format(y, x) def print_img_pixel(x, y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm) try:", "import atexit import gc import time # Related third party imports. import serial", "print >>logf, '``{0}`` just opened *command port* ``{1}``'.format(PN, sp.port) msg = '``{0}`` is", "value in MM12_SUBROUTINES.items(): if subroutine_id is value['subroutine_id']: return key for intarg in (ntransitions,", "show=False): '''Perform any necessary processing for the input image to be reproduced by", "}, 'Y' : { 'dir_channel' : 2, 'dir_positive' : STEPPER_CHANNELS_TARGET_ON, 'dir_negative' : STEPPER_CHANNELS_TARGET_OFF,", ": { 'subroutine_id' : 5, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_pos_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'],", "units of single low-to-high transitions sent to the stepper motor drivers (how much", "'Loaded ``{0}`` with {1} pixels, {2} of which have color'.format( imgpath, npixels, nprints)", "across :math:`Y`. ``Y+p`` send 1 single pulse for positive translation across :math:`Y`. ``Y-P``", "**w** : int Image's width, number of columns in the array representation. '''", "}, 'X+p' : { 'subroutine_id' : 1, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_pos_pulse', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'],", "'''Target value in units of quarter-:math:`\\\\mu s` that drives the stepper channels high.'''", "'X+P' : { 'subroutine_id' : 3, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_pos_pixel', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF,", "optional Delay (in milliseconds) between each transition in the subroutines that perform translation", "{ 'X' : { 'dir_channel' : 0, 'dir_positive' : STEPPER_CHANNELS_TARGET_OFF, 'dir_negative' : STEPPER_CHANNELS_TARGET_ON,", "940 ''':math:`Z` axis servo motor pulse width in units of quarter-:math:`\\\\mu s` that", "``Y+P`` send :math:`n` pulses for positive translation across :math:`Y`. ``Z-`` move the tool", "x -= 1 print 'The image has been printed' except KeyboardInterrupt: sp.flush() print", "of translation you want to perform (where :math:`n` is the number of pulses", "to the stepper motor drivers (how much the tool is translated depends on", "servo_speed : int, optional Sets the speed of the servo signal channel in", "translate(adm, confirm=False): '''Translate the printerm tool across the :math:`XYZ` space. printer73x can only", "{ 'dir_channel' : 0, 'dir_positive' : STEPPER_CHANNELS_TARGET_OFF, 'dir_negative' : STEPPER_CHANNELS_TARGET_ON, 'step_channel': 1, },", ":math:`Y`. ``Y+p`` send 1 single pulse for positive translation across :math:`Y`. ``Y-P`` send", "translate('Z+', confirm) try: if img[y][x+1] != 0.0: translate('Z-', confirm) except IndexError as e:", "row {0}'.format(y) while True: report_position(x, y) if img[y][x] == 0.0: translate('Z+', confirm) try:", "print msg x = y = 0 # We are at HOME position.", "upper left corner of the input image. #. :math:`a_{b-1,w-1}` corresponds to the lower", "the MM12 returns when the script is running.''' MM12_SCRIPT_STOPPED = '\\x01' '''Byte value", "}, 'X+P' : { 'subroutine_id' : 3, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_pos_pixel', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'],", "0: break translate('Y-P', confirm) y -= 1 while True: if x == 0:", "begin get_moving_state while # wait until is is no longer moving. repeat 75", "image. Parameters ---------- confirm : boolean, optional Wait for confirmation before any translation", "a stepper motor in units of low-to-high transitions, for a precise but slow", "MM12_SUBROUTINES)): subroutine_key = get_subroutine_key_by_id(i) subroutine_body = MM12_SUBROUTINES[subroutine_key]['subroutine_body'] if 'Z' not in subroutine_key: subroutine_body", "transitions the stepper motors need to translate 1 pixel across the :math:`X` or", "'j' : 'Y+P', 'k' : 'Y-P', 'i' : 'Z+', 'o' : 'Z-', }", "img[y][x] == 0.0: print_pixel(confirm) def color_in_this_row(row): for pixel in row: if pixel ==", "Use the following table to set this constant: ============ ============ =============== MS1 MS2", "that the MM12 returns when the script is stopped.''' # ========================================================================== # ==========================================================================", "def build_mm12_script(fpath, ntransitions=TRANSITIONS_PER_PIXEL, delay=1, servo_acceleration=0, servo_speed=100): '''Build a script to be loaded on", "value that the MM12 returns when the script is stopped.''' # ========================================================================== #", "1 pixel across the :math:`X` or :math:`Y` axes.''' TRANSITIONS_PER_PIXEL = STEPS_PER_PIXEL * TRANSITIONS_PER_STEP", "of columns in the array representation. ''' global img, b, w print 'Loading", "across the :math:`XYZ` space. printer73x can only perform translations across a single axis", "MM12, its subsystem) loads in its memory the routines that correspond to the", "========================================================================== # ========================================================================== class Getch: \"\"\"Gets a single character from standard input. Does", "in range(256): try: s = serial.Serial(i) available.append( (i, s.portstr)) s.close() except serial.SerialException: pass", "6, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_neg_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y+P'", "- 1: break translate('X+P', confirm) x += 1 if y == b -", "-= 1 if y == b - 1: translate('Z-') break translate('Y+P', confirm) y", "'''Template for the MM12 script subroutines that drive a stepper motor in units", "Author: <NAME> # Contact: <EMAIL> '''Numerical controller for the printer73x system. **printerc** is", "value that the MM12 returns when the script is running.''' MM12_SCRIPT_STOPPED = '\\x01'", "printer73x system. **printerc** is an interactive command line interface for the numerical control", "for using ``printerc``!\\n' # Invoke the garbage collector. gc.collect() def scan_serial_ports(): '''Scan system", "of the servo signal channel in units of (0.25 us)/(10 ms)/(80 ms) (default", "a single character from standard input. Does not echo to the screen. References", "servo_speed): assert isinstance(intarg, int) with open(fpath, 'w') as f: print >>f, MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration, servo_speed=servo_speed)", "invert: print 'Inverting image...' for i in range(b): for j in range(w): if", "pixel across the :math:`X` or :math:`Y` axes.''' TRANSITIONS_PER_PIXEL = STEPS_PER_PIXEL * TRANSITIONS_PER_STEP '''Number", "keys2translation = { 'h' : 'X-p', 'l' : 'X+p', 'j' : 'Y+p', 'k'", "pixel unit across the respective axis). ======= ================================================================ *adm* translation ======= ================================================================ ``X-p``", "pulse for positive translation across :math:`X`. ``X-P`` send :math:`n` pulses for negative translation", "position, if the corresponding pixel is black then the tool prints it. '''", "too. # ========================================================================== # ========================================================================== LOGF = 'log.rst' '''Path to the log file.'''", "x == 0: break translate('X-P', confirm) x -= 1 if y == b", "units of quarter-:math:`\\\\mu s` that drives the stepper channels low.''' MM12_AXES_CHANNELS = {", "import numpy as np # remove import matplotlib.image as mpimg import matplotlib.pyplot as", "1 # To the left. print 'Printing across the row {0}'.format(y) while True:", "'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_neg_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y+P' :", "Getch: \"\"\"Gets a single character from standard input. Does not echo to the", "for pixel in row: if pixel == 0.0: return True return False try:", "across :math:`X`. ``X-P`` send :math:`n` pulses for negative translation across :math:`X`. ``X+P`` send", "the MM12 returns when the script is stopped.''' # ========================================================================== # ========================================================================== #", "the lower right corner of the input image. Starting from the HOME position", "and stepper motors outputs.''' SUB_STEPPER_PIXEL_TEMPLATE = '''sub {name} {{{{ntransitions}}}} {dir} {dir_channel} servo #", "Related third party imports. import serial import IPython import numpy as np #", "order to produce the trajectory of the tool printing the image. ''' #", "corner of the input image. Starting from the HOME position the printerm tool", "Starting from the HOME position the printerm tool visit every element of the", ": 'X-p', 'l' : 'X+p', 'j' : 'Y+p', 'k' : 'Y-p', 'i' :", "'''Scan system for available physical or virtual serial ports. Returns ------- available :", "step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Z-' : { 'subroutine_id' : 8, 'subroutine_body' : SUB_SERVO_TEMPLATE.format(", "ch class _GetchWindows: '''Windows implementation of class ``Getch``.''' def __init__(self): import msvcrt def", "{channel} servo begin get_moving_state while # wait until is is no longer moving.", "is coupled to printerm through the motors. mcircuit (actually MM12, its subsystem) loads", "on exit.''' try: print >>logf, 'Closing ``{0}`` *command port*'.format(sp.port) sp.close() except NameError: pass", "row (:math:`a_{1,w-1}`) and visits every element of the row from :math:`a_{1,w-1}` to :math:`a_{1,0}`,", "through the MM12 command port. Parameters ---------- commandport_id : str or int Serial", "name='y_neg_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y+P' : { 'subroutine_id' :", "stepper motors (default is 1). servo_acceleration : int, optional Sets the acceleration of", "of the tool printing the image. ''' # Standard library imports. from __future__", "delay, servo_acceleration, servo_speed): assert isinstance(intarg, int) with open(fpath, 'w') as f: print >>f,", "imgpath : str-like Path to the image file. Must be PNG, 8-bit grayscale,", "============ =============== .. note:: Both stepper motor driver boards must have the same", "1, }, 'Y' : { 'dir_channel' : 2, 'dir_positive' : STEPPER_CHANNELS_TARGET_ON, 'dir_negative' :", "'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_pos_pixel', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y-p' :", "move the tool to the off position (:math:`Z`). ``Z+`` move the tool to", "motors outputs.''' SUB_STEPPER_PIXEL_TEMPLATE = '''sub {name} {{{{ntransitions}}}} {dir} {dir_channel} servo # set direction", "servo begin get_moving_state while # wait until is is no longer moving. repeat", "{``MM12_SCRIPT_RUNNING``, ``MM12_SCRIPT_STOPPED``} ''' assert sp.write('\\xae') == 1 return sp.read(1) def translate(adm, confirm=False): '''Translate", "'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_pos_pulse', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X-P' : {", "``Getch``.''' def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() def on_exit():", "pass if x == w - 1: translate('Z-') break translate('X+P', confirm) x +=", "channel in units of (0.25 us)/(10 ms)/(80 ms) (default is 0). servo_speed :", "except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' def print_image_better(confirm=False): def report_position(x,", "translate(keys2translation[ch], confirm=False) def print_pixel(confirm=False): if confirm: raw_input() translate('Z+', confirm=False) translate('Z-', confirm=False) def print_image(confirm=False):", "performs translation in units of pixels through the stepper motor (default is ``TRANSITIONS_PER_PIXEL``).", "# Standard library imports. from __future__ import division from pprint import pprint import", "= subroutine_body.format(ntransitions=ntransitions) print >>f, subroutine_body def prepare_img(imgpath, invert=False, show=False): '''Perform any necessary processing", "== 0`` then no pixel will be printed. assert nprints > 0 print", "a pixel. Comparing :math:`\\mathbf{A}` with the input image from a front perspective: #.", "``Y-P`` send :math:`n` pulses for negative translation across :math:`Y`. ``Y+P`` send :math:`n` pulses", "print_img_pixel(x, y, confirm) if x == 0: break translate('X-P', confirm) x -= 1", "#time.sleep(0.1) def build_mm12_script(fpath, ntransitions=TRANSITIONS_PER_PIXEL, delay=1, servo_acceleration=0, servo_speed=100): '''Build a script to be loaded", "python # coding=utf-8 # Author: <NAME> # Contact: <EMAIL> '''Numerical controller for the", "Enter (default is ``False``). ''' # Start until script is not running. while", ">>logf, 'Closing ``{0}`` *command port*'.format(sp.port) sp.close() except NameError: pass print >>logf, 'END' logf.close()", "moving. repeat 75 delay quit ''' '''Template for the MM12 script subroutine that", "``X-p`` send 1 single pulse for negative translation across :math:`X`. ``X+p`` send 1", "image file. Must be PNG, 8-bit grayscale, non-interlaced. invert : boolean, optional Invert", ":math:`\\mathbf{A}`, represents a pixel. Comparing :math:`\\mathbf{A}` with the input image from a front", "next row (:math:`a_{1,w-1}`) and visits every element of the row from :math:`a_{1,w-1}` to", "confirm) x -= 1 if y == b - 1: break translate('Y+P', confirm)", "confirm) if x == w - 1: break translate('X+P', confirm) x += 1", "position (:math:`Z`). ======= ================================================================ confirm: boolean, optional If ``True``, the user must confirm", "the stepper channels low.''' MM12_AXES_CHANNELS = { 'X' : { 'dir_channel' : 0,", "to translate 1 pixel across the :math:`X` or :math:`Y` axes.''' TRANSITIONS_PER_PIXEL = STEPS_PER_PIXEL", "printerm tool across the :math:`XY` plane. Parameters ---------- precise : boolean, optional If", "HOME position the printerm tool visit every element of the row from :math:`a_{0,0}`", "the stepper motors (default is 1). servo_acceleration : int, optional Sets the acceleration", "'dir_channel' : 2, 'dir_positive' : STEPPER_CHANNELS_TARGET_ON, 'dir_negative' : STEPPER_CHANNELS_TARGET_OFF, 'step_channel': 3, }, 'Z'", "printer73x can only perform translations across a single axis at a time. Parameters", "of pulses for the printerm tool to translate a pixel unit across the", "as mpimg import matplotlib.pyplot as plt import matplotlib.cm as cm # Same as", "# ========================================================================== TRANSITIONS_PER_STEP = 2 '''The board sets the microstepping format with the", "x == 0: break translate('X-P', confirm) x -= 1 print 'The image has", "quit ''' '''Template for the MM12 script subroutines that drive a stepper motor", "============ =============== MS1 MS2 TRANSITIONS_PER_STEP ============ ============ =============== connected connected 1 disconnected connected", "connected disconnected 4 disconnected disconnected 8 ============ ============ =============== .. note:: Both stepper", "chr( MM12_SUBROUTINES[adm]['subroutine_id']) str2write = ''.join(['\\xa7', subroutine_id]) if confirm: raw_input() assert sp.write(str2write) == 2", "the off position (:math:`Z`). ``Z+`` move the tool to the on position (:math:`Z`).", "> 0.0: nnotprints += 1 else: nprints += 1 assert (nnotprints + nprints)", "in subroutine_key: subroutine_body = subroutine_body.format(delay=delay) if 'P' in subroutine_key: subroutine_body = subroutine_body.format(ntransitions=ntransitions) print", "_GetchUnix() def __call__(self): return self.impl() class _GetchUnix: '''Unix implementation of class ``Getch``.''' def", "motor driver boards must have the same jumper configuration. ''' STEPS_PER_PIXEL = 90", "def manual_translation_mode(precise=True): '''Manually translate the printerm tool across the :math:`XY` plane. Parameters ----------", "motor pulse width in units of quarter-:math:`\\\\mu s` that enables printing (moves the", "# set direction begin dup while {off} {step_channel} servo {{delay}} delay {on} {step_channel}", "of (0.25 us)/(10 ms)/(80 ms) (default is 0). servo_speed : int, optional Sets", "SRV_SIGNAL_CHANNEL_TARGET_OFF = 940 ''':math:`Z` axis servo motor pulse width in units of quarter-:math:`\\\\mu", "str-like Path location where to save the script file. ntransitions : int, optional", "int, optional Sets the speed of the servo signal channel in units of", "mpimg.imread(fname=imgpath, format='png') b, w = img.shape npixels = b * w nprints =", "every element of the row from :math:`a_{1,w-1}` to :math:`a_{1,0}`, and so on until", "send 1 single pulse for positive translation across :math:`X`. ``X-P`` send :math:`n` pulses", "npixels, nprints) plt.close('all') if show: plt.imshow(img, cmap=cm.gray) plt.show() def connect_printerm(commandport_id): '''Connect printerc with", "**printerc** is an interactive command line interface for the numerical control of the", "'subroutine_id' : 0, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_neg_pulse', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), },", "Both stepper motor driver boards must have the same jumper configuration. ''' STEPS_PER_PIXEL", "is ``False``). Notes ----- This function sets the following global names: **img** :", "}, } '''Structure that builds and identifies the MM12 script subroutines.''' MM12_SCRIPT_RUNNING =", "0: break translate('Y-P', confirm) y -= 1 print 'The image has been printed'", "translate('Y+P', confirm) y += 1 print 'Printing across the row {0}'.format(y) while True:", "that the MM12 returns when the script is running.''' MM12_SCRIPT_STOPPED = '\\x01' '''Byte", "pixel will be printed. assert nprints > 0 print 'Loaded ``{0}`` with {1}", "translate('Z-') break translate('X+P', confirm) x += 1 if y == b - 1:", "for i in range(b): for j in range(w): if img[i][j] > 0.0: img[i][j]", "img[i][j] = 0.0 else: img[i][j] = 1.0 if invert: print 'Inverting image...' for", "import serial import IPython import numpy as np # remove import matplotlib.image as", "''' assert sp.write('\\xae') == 1 return sp.read(1) def translate(adm, confirm=False): '''Translate the printerm", "in units of quarter-:math:`\\\\mu s` that drives the stepper channels high.''' STEPPER_CHANNELS_TARGET_OFF =", "translation across :math:`X`. ``X-P`` send :math:`n` pulses for negative translation across :math:`X`. ``X+P``", ": boolean, optional Invert the image if ``True`` (default is ``False``). show :", "before any translation (default is ``False``). Notes ----- Let :math:`\\mathbf{A}` be the matrix", "pixel with and without color. for i in range(b): for j in range(w):", "'step_channel': 3, }, 'Z' : { 'channel' : 4, 'on' : SRV_SIGNAL_CHANNEL_TARGET_OFF, 'off'", "= 6800 '''Target value in units of quarter-:math:`\\\\mu s` that drives the stepper", ">>logf, 'END' logf.close() print '\\nThanks for using ``printerc``!\\n' # Invoke the garbage collector.", "at HOME position. while True: print 'Printing across the row {0}'.format(y) while True:", ": STEPPER_CHANNELS_TARGET_ON, 'dir_negative' : STEPPER_CHANNELS_TARGET_OFF, 'step_channel': 3, }, 'Z' : { 'channel' :", "== b - 1: translate('Z-') break translate('Y+P', confirm) y += 1 print 'Returning", "0, 'dir_positive' : STEPPER_CHANNELS_TARGET_OFF, 'dir_negative' : STEPPER_CHANNELS_TARGET_ON, 'step_channel': 1, }, 'Y' : {", "image. :math:`a_{y,x}` as an element of :math:`\\mathbf{A}`, represents a pixel. Comparing :math:`\\mathbf{A}` with", "if img[i][j] > 0.0: img[i][j] = 0.0 else: img[i][j] = 1.0 # Check", "return key for intarg in (ntransitions, delay, servo_acceleration, servo_speed): assert isinstance(intarg, int) with", "True: # To the right. print 'Printing across the row {0}'.format(y) while True:", "key, value in MM12_SUBROUTINES.items(): if subroutine_id is value['subroutine_id']: return key for intarg in", "== 0.0: print_pixel(confirm) try: msg = 'Preparing to print an image with {0}", "if x == w - 1: break translate('X+P', confirm) x += 1 if", ": SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_pos_pixel', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y-p' : {", "the translation by pressing Enter (default is ``False``). ''' # Start until script", "script subroutines that drive a stepper motor in units of pixels,''' SUB_STEPPER_PULSE_TEMPLATE =", "confirm) y += 1 print 'Printing across the row {0}'.format(y) while True: report_position(x,", "confirm: raw_input() assert sp.write(str2write) == 2 #if 'Z' in adm: #time.sleep(0.1) def build_mm12_script(fpath,", ":math:`Y` and :math:`Z` axis, and then printerc execute these routines in order to", "to save the script file. ntransitions : int, optional Number of low-to-high transitions", "Number of low-to-high transitions to perform in the subroutines that performs translation in", "input image to be reproduced by printerm. Parameters ---------- imgpath : str-like Path", "width, number of columns in the array representation. ''' global img, b, w", "any necessary processing for the input image to be reproduced by printerm. Parameters", "0.0: print_pixel(confirm) def color_in_this_row(row): for pixel in row: if pixel == 0.0: return", "1 while True: if x == 0: break translate('X-P', confirm) x -= 1", "position. while True: print 'Printing across the row {0}'.format(y) while True: report_position(x, y)", "confirm) if x == 0: translate('Z-') break translate('X-P', confirm) x -= 1 if", "print_pixel(confirm=False): if confirm: raw_input() translate('Z+', confirm=False) translate('Z-', confirm=False) def print_image(confirm=False): def report_position(x, y):", "from __future__ import division from pprint import pprint import sys import os import", "1 minus repeat quit ''' '''Template for the MM12 script subroutines that drive", "if img[y][x-1] != 0.0: translate('Z-', confirm) if x == 0: translate('Z-') break translate('X-P',", "motors (default is 1). servo_acceleration : int, optional Sets the acceleration of the", "in keys2translation.keys(): break while mm12_script_status() == MM12_SCRIPT_RUNNING: pass translate(keys2translation[ch], confirm=False) def print_pixel(confirm=False): if", "INTRO_MSG = '''\\ **printerc** Welcome! ''' '''Welcome message for command line interface.''' #", "names. *if main* section at bottom sets global names too. # ========================================================================== #", "dup while {off} {step_channel} servo {{delay}} delay {on} {step_channel} servo {{delay}} delay 1", "# To the right. print 'Printing across the row {0}'.format(y) while True: report_position(x,", "img[i][j] = 1.0 if invert: print 'Inverting image...' for i in range(b): for", "}, 'Y+p' : { 'subroutine_id' : 5, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_pos_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'],", "party imports. import serial import IPython import numpy as np # remove import", "tool printing the image. ''' # Standard library imports. from __future__ import division", "(default is ``False``). Notes ----- Let :math:`\\mathbf{A}` be the matrix representation of the", "translate('Z-') break translate('Y+P', confirm) y += 1 print 'Returning to a_{{0, 0}}'.format(y) while", "position. while True: # To the right. print 'Printing across the row {0}'.format(y)", ": { 'subroutine_id' : 7, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_pos_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'],", "is ``False``). ''' # Start until script is not running. while mm12_script_status() ==", "the log file.''' INTRO_MSG = '''\\ **printerc** Welcome! ''' '''Welcome message for command", "= 1580 ''':math:`Z` axis servo motor pulse width in units of quarter-:math:`\\\\mu s`", "for the MM12 script subroutine that drives the servo motor.''' MM12_SCRIPT_INIT = '''\\", "class Getch: \"\"\"Gets a single character from standard input. Does not echo to", "the image if ``True`` (default is ``False``). show : boolean, optional Show the", "that perform translation through the stepper motors (default is 1). servo_acceleration : int,", "else: img[i][j] = 1.0 if invert: print 'Inverting image...' for i in range(b):", "img[y][x] == 0.0: translate('Z+', confirm) if img[y][x-1] != 0.0: translate('Z-', confirm) if x", "tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: '''Windows", "key for intarg in (ntransitions, delay, servo_acceleration, servo_speed): assert isinstance(intarg, int) with open(fpath,", "the printerm tool across the :math:`XYZ` space. printer73x can only perform translations across", "0: break translate('X-P', confirm) x -= 1 if y == b - 1:", "for pixel with and without color. for i in range(b): for j in", "'''Translate the printerm tool across the :math:`XYZ` space. printer73x can only perform translations", "port' if __name__ == \"__main__\": # program name from file name. PN =", "(default is ``TRANSITIONS_PER_PIXEL``). delay : int, optional Delay (in milliseconds) between each transition", "input image. Parameters ---------- confirm : boolean, optional Wait for confirmation before any", ":math:`a_{y,x}` as an element of :math:`\\mathbf{A}`, represents a pixel. Comparing :math:`\\mathbf{A}` with the", "3, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_pos_pixel', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y-p'", "disconnected disconnected 8 ============ ============ =============== .. note:: Both stepper motor driver boards", "= { 'h' : 'X-P', 'l' : 'X+P', 'j' : 'Y+P', 'k' :", "axis, and then printerc execute these routines in order to produce the trajectory", "{off} {step_channel} servo {{delay}} delay {on} {step_channel} servo {{delay}} delay quit ''' '''Template", "SUB_STEPPER_PULSE_TEMPLATE.format( name='y_neg_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y+p' : { 'subroutine_id' :", "return msvcrt.getch() def on_exit(): '''Actions to do on exit.''' try: print >>logf, 'Closing", "'Operation interrupted, flushing command port' if __name__ == \"__main__\": # program name from", "========================================================================== LOGF = 'log.rst' '''Path to the log file.''' INTRO_MSG = '''\\ **printerc**", "img[i][j] > 0.0: nnotprints += 1 else: nprints += 1 assert (nnotprints +", "SUB_SERVO_TEMPLATE = '''sub {name} {position} {channel} servo begin get_moving_state while # wait until", "report_position(x, y) if img[y][x] == 0.0: translate('Z+', confirm) try: if img[y][x+1] != 0.0:", "the next row (:math:`a_{1,w-1}`) and visits every element of the row from :math:`a_{1,w-1}`", "``Getch``.''' def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd", "if img[y][x] == 0.0: translate('Z+', confirm) try: if img[y][x+1] != 0.0: translate('Z-', confirm)", "0.0: translate('Z+', confirm) if img[y][x-1] != 0.0: translate('Z-', confirm) if x == 0:", "in row: if pixel == 0.0: return True return False try: msg =", "the :math:`XYZ` space. printer73x can only perform translations across a single axis at", "drives printerm through mcircuit; printerc stablishes a serial connection with mcircuit, and mcircuit", "from file name. PN = os.path.splitext(sys.argv[0])[0] logf = open(LOGF, 'w') print >>logf, 'START'", "{off} {step_channel} servo {{delay}} delay {on} {step_channel} servo {{delay}} delay 1 minus repeat", "'o' : 'Z-', } else: keys2translation = { 'h' : 'X-P', 'l' :", ": { 'subroutine_id' : 1, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_pos_pulse', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'],", "sys import os import atexit import gc import time # Related third party", "0.0: translate('Z-', confirm) except IndexError as e: pass if x == w -", "low-to-high transitions sent to the stepper motor drivers (how much the tool is", "for the input image to be reproduced by printerm. Parameters ---------- imgpath :", "processing for the input image to be reproduced by printerm. Parameters ---------- imgpath", "if img[y][x] == 0.0: translate('Z+', confirm) if img[y][x-1] != 0.0: translate('Z-', confirm) if", "== MM12_SCRIPT_RUNNING: pass subroutine_id = chr( MM12_SUBROUTINES[adm]['subroutine_id']) str2write = ''.join(['\\xa7', subroutine_id]) if confirm:", "format='png') b, w = img.shape npixels = b * w nprints = nnotprints", "y = z = 0 # We are at HOME position. while True:", "is a ``(num, name)`` tuple with the number and name of the port.", "single pulse for negative translation across :math:`Y`. ``Y+p`` send 1 single pulse for", "ports. Returns ------- available : list of tuples Each element of the list", "confirm the translation by pressing Enter (default is ``False``). ''' # Start until", "Standard library imports. from __future__ import division from pprint import pprint import sys", "that drive a stepper motor in units of low-to-high transitions, for a precise", "the subroutines that perform translation through the stepper motors (default is 1). servo_acceleration", "array representation. **w** : int Image's width, number of columns in the array", "total black and white, no grays. for i in range(b): for j in", "* w nprints = nnotprints = 0 assert (b > 0) and (w", "to perform (where :math:`n` is the number of pulses for the printerm tool", "print 'Loaded ``{0}`` with {1} pixels, {2} of which have color'.format( imgpath, npixels,", ": 'Y+p', 'k' : 'Y-p', 'i' : 'Z+', 'o' : 'Z-', } else:", "{0}, column {1}'.format(y, x) def print_img_pixel(x, y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm)", "stepper motor needs to translate 1 pixel across the :math:`X` or :math:`Y` axes.'''", "y += 1 print 'Returning to a_{{0, 0}}'.format(y) while True: if y ==", "subroutine_body = subroutine_body.format(ntransitions=ntransitions) print >>f, subroutine_body def prepare_img(imgpath, invert=False, show=False): '''Perform any necessary", "'''Indicate whether the MM12 script is running or stopped. Returns ------- script_status :", "old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return", "the servo signal channel in units of (0.25 us)/(10 ms)/(80 ms) (default is", "transitions, for a precise but slow translation.''' SUB_SERVO_TEMPLATE = '''sub {name} {position} {channel}", "for i in range(b): for j in range(w): if img[i][j] < 0.9: img[i][j]", "report_position(x, y) print_img_pixel(x, y, confirm) if x == w - 1: break translate('X+P',", "image to be reproduced by printerm. Parameters ---------- imgpath : str-like Path to", "repeat 75 delay quit ''' '''Template for the MM12 script subroutine that drives", "break translate('X+P', confirm) x += 1 print 'Returning to a_{{{0}, 0}}'.format(y) while True:", "# only total black and white, no grays. for i in range(b): for", "{dir} {dir_channel} servo # set direction begin dup while {off} {step_channel} servo {{delay}}", "MS2 TRANSITIONS_PER_STEP ============ ============ =============== connected connected 1 disconnected connected 2 connected disconnected", "across the :math:`X` or :math:`Y` axes.''' SRV_SIGNAL_CHANNEL_TARGET_OFF = 940 ''':math:`Z` axis servo motor", "initialization.''' MM12_SUBROUTINES = { 'X-p' : { 'subroutine_id' : 0, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format(", "STEPPER_CHANNELS_TARGET_OFF = 5600 '''Target value in units of quarter-:math:`\\\\mu s` that drives the", "MM12_SCRIPT_INIT = '''\\ {{servo_acceleration}} {servo_channel} acceleration {{servo_speed}} {servo_channel} speed '''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel']) '''MM12 script initialization.'''", "to set this constant: ============ ============ =============== MS1 MS2 TRANSITIONS_PER_STEP ============ ============ ===============", "division from pprint import pprint import sys import os import atexit import gc", "pulse for positive translation across :math:`Y`. ``Y-P`` send :math:`n` pulses for negative translation", "except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: '''Unix implementation", "depends on the microstep format selected through the XMS1, XMS2, YMS1, YMS2 jumpers", "MM12 script subroutines that drive a stepper motor in units of low-to-high transitions,", "height, number of rows in the array representation. **w** : int Image's width,", "disconnected 4 disconnected disconnected 8 ============ ============ =============== .. note:: Both stepper motor", "configuration. ''' STEPS_PER_PIXEL = 90 '''Number of steps the stepper motor needs to", "servo {{delay}} delay 1 minus repeat quit ''' '''Template for the MM12 script", "number of columns in the array representation. ''' global img, b, w print", "of class ``Getch``.''' def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch()", "(where :math:`n` is the number of pulses for the printerm tool to translate", "0}}'.format(y) while True: if y == 0: break translate('Y-P', confirm) y -= 1", "servo motor pulse width in units of quarter-:math:`\\\\mu s` that disables printing (moves", "translate('Z-') break translate('X-P', confirm) x -= 1 if y == b - 1:", "move the tool to the on position (:math:`Z`). ======= ================================================================ confirm: boolean, optional", "columns'.format(b, w) print msg x = y = z = 0 # We", "available physical or virtual serial ports. Returns ------- available : list of tuples", "Parameters ---------- fpath : str-like Path location where to save the script file.", "confirm) y += 1 # To the left. print 'Printing across the row", "<http://sourceforge.net/projects/pyserial/files/package>`_ project. ''' available = [] for i in range(256): try: s =", "= _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: '''Unix implementation of class ``Getch``.'''", "sp.port) msg = '``{0}`` is now connected to ``printerm`` through ``{1}``'.format( PN, sp.port)", "then the tool prints it. ''' def report_position(x, y): print 'At row {0},", "pulses for negative translation across :math:`Y`. ``Y+P`` send :math:`n` pulses for positive translation", ": 'Z+', 'o' : 'Z-', } else: keys2translation = { 'h' : 'X-P',", "= STEPS_PER_PIXEL * TRANSITIONS_PER_STEP '''Number of low-to-high transitions the stepper motors need to", "perspective: #. :math:`a_{0,0}` corresponds to the upper left corner of the input image.", "printerm. Parameters ---------- imgpath : str-like Path to the image file. Must be", "is running or stopped. Returns ------- script_status : {``MM12_SCRIPT_RUNNING``, ``MM12_SCRIPT_STOPPED``} ''' assert sp.write('\\xae')", "show: plt.imshow(img, cmap=cm.gray) plt.show() def connect_printerm(commandport_id): '''Connect printerc with printerm through the MM12", "servo motor pulse width in units of quarter-:math:`\\\\mu s` that enables printing (moves", "be loaded on the MM12. Parameters ---------- fpath : str-like Path location where", "available def mm12_script_status(): '''Indicate whether the MM12 script is running or stopped. Returns", "translate('X-P', confirm) x -= 1 if y == b - 1: break translate('Y+P',", ":math:`\\mathbf{A}` be the matrix representation of the input image. :math:`a_{y,x}` as an element", ": 0, 'dir_positive' : STEPPER_CHANNELS_TARGET_OFF, 'dir_negative' : STEPPER_CHANNELS_TARGET_ON, 'step_channel': 1, }, 'Y' :", "MM12_SCRIPT_STOPPED = '\\x01' '''Byte value that the MM12 returns when the script is", "90 '''Number of steps the stepper motor needs to translate 1 pixel across", "mcircuit (actually MM12, its subsystem) loads in its memory the routines that correspond", "'Z+' : { 'subroutine_id' : 9, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_on', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['on']*4) },", "script subroutines that drive a stepper motor in units of low-to-high transitions, for", "def print_img_pixel(x, y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm) def color_in_this_row(row): for pixel", "subroutine_body = subroutine_body.format(delay=delay) if 'P' in subroutine_key: subroutine_body = subroutine_body.format(ntransitions=ntransitions) print >>f, subroutine_body", "connection with mcircuit, and mcircuit is coupled to printerm through the motors. mcircuit", "lower right corner of the input image. Starting from the HOME position the", "port* ``{1}``'.format(PN, sp.port) msg = '``{0}`` is now connected to ``printerm`` through ``{1}``'.format(", "the microstep format selected through the XMS1, XMS2, YMS1, YMS2 jumpers in mcircuit).", "'0.09' # GLOBAL CONSTANT names. *if main* section at bottom sets global names", "representation. ''' global img, b, w print 'Loading ``{0}``...'.format(imgpath) img = mpimg.imread(fname=imgpath, format='png')", "SUB_SERVO_TEMPLATE.format( name='z_position_off', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['off']*4) }, 'Z+' : { 'subroutine_id' : 9, 'subroutine_body' :", "1: translate('Z-') break translate('X+P', confirm) x += 1 if y == b -", "step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X+p' : { 'subroutine_id' : 1, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_pos_pulse',", "the speed of the servo signal channel in units of (0.25 us)/(10 ms)", "dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y-P' : { 'subroutine_id' : 6, 'subroutine_body' :", "Each element of the list is a ``(num, name)`` tuple with the number", "that enables printing (moves the tool down).''' SRV_SIGNAL_CHANNEL_TARGET_ON = 2175 SRV_SIGNAL_CHANNEL_TARGET_ON = 1580", "collector. gc.collect() def scan_serial_ports(): '''Scan system for available physical or virtual serial ports.", "f: print >>f, MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration, servo_speed=servo_speed) for i in range(len( MM12_SUBROUTINES)): subroutine_key = get_subroutine_key_by_id(i)", "in units of single low-to-high transitions sent to the stepper motor drivers (how", "break translate('X-P', confirm) x -= 1 if y == b - 1: break", "to visit. In any position, if the corresponding pixel is black then the", "standard input. Does not echo to the screen. References ========== .. [GETCHRECIPE] http://code.activestate.com/recipes/134892/", "------- script_status : {``MM12_SCRIPT_RUNNING``, ``MM12_SCRIPT_STOPPED``} ''' assert sp.write('\\xae') == 1 return sp.read(1) def", "tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1)", "{ 'h' : 'X-p', 'l' : 'X+p', 'j' : 'Y+p', 'k' : 'Y-p',", "'''\\ **printerc** Welcome! ''' '''Welcome message for command line interface.''' # MM12 #", "a_{{0, 0}}'.format(y) while True: if y == 0: break translate('Y-P', confirm) y -=", "} '''Structure that builds and identifies the MM12 script subroutines.''' MM12_SCRIPT_RUNNING = '\\x00'", "on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y-p' : { 'subroutine_id' : 4, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_neg_pulse',", "sp.write(str2write) == 2 #if 'Z' in adm: #time.sleep(0.1) def build_mm12_script(fpath, ntransitions=TRANSITIONS_PER_PIXEL, delay=1, servo_acceleration=0,", "on=STEPPER_CHANNELS_TARGET_ON), }, 'X-P' : { 'subroutine_id' : 2, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_neg_pixel', dir=MM12_AXES_CHANNELS['X']['dir_negative'],", "for intarg in (ntransitions, delay, servo_acceleration, servo_speed): assert isinstance(intarg, int) with open(fpath, 'w')", "confirm=False): if img[y][x] == 0.0: print_pixel(confirm) def color_in_this_row(row): for pixel in row: if", "is 100). ''' def get_subroutine_key_by_id(subroutine_id): for key, value in MM12_SUBROUTINES.items(): if subroutine_id is", "- 1: translate('Z-') break translate('X+P', confirm) x += 1 if y == b", "def __call__(self): return self.impl() class _GetchUnix: '''Unix implementation of class ``Getch``.''' def __init__(self):", "sys.stdout): print >>f, msg def manual_translation_mode(precise=True): '''Manually translate the printerm tool across the", "following global names: **img** : array of booleans 2-d array representation of the", "y == b - 1: translate('Z-') break translate('Y+P', confirm) y += 1 print", "pprint import sys import os import atexit import gc import time # Related", "tool up).''' STEPPER_CHANNELS_TARGET_ON = 6800 '''Target value in units of quarter-:math:`\\\\mu s` that", "the motors. mcircuit (actually MM12, its subsystem) loads in its memory the routines", "x == w - 1: translate('Z-') break translate('X+P', confirm) x += 1 if", "input image from a front perspective: #. :math:`a_{0,0}` corresponds to the upper left", "'k' : 'Y-p', 'i' : 'Z+', 'o' : 'Z-', } else: keys2translation =", "but slow translation.''' SUB_SERVO_TEMPLATE = '''sub {name} {position} {channel} servo begin get_moving_state while", "npixels # If ``nprints == 0`` then no pixel will be printed. assert", "this constant: ============ ============ =============== MS1 MS2 TRANSITIONS_PER_STEP ============ ============ =============== connected connected", "== b - 1: break translate('Y+P', confirm) y += 1 print 'Returning to", "1: break translate('X+P', confirm) x += 1 print 'Returning to a_{{{0}, 0}}'.format(y) while", "pixel in row: if pixel == 0.0: return True return False try: msg", "are no more rows to visit. In any position, if the corresponding pixel", "file. ntransitions : int, optional Number of low-to-high transitions to perform in the", ":math:`a_{b-1,w-1}` corresponds to the lower right corner of the input image. Starting from", "break translate('Y+P', confirm) y += 1 print 'Returning to a_{{0, 0}}'.format(y) while True:", "assert (nnotprints + nprints) == npixels # If ``nprints == 0`` then no", "Contact: <EMAIL> '''Numerical controller for the printer73x system. **printerc** is an interactive command", "MM12_AXES_CHANNELS = { 'X' : { 'dir_channel' : 0, 'dir_positive' : STEPPER_CHANNELS_TARGET_OFF, 'dir_negative'", "import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings", "printerc drives printerm through mcircuit; printerc stablishes a serial connection with mcircuit, and", "range(w): if img[i][j] > 0.0: img[i][j] = 0.0 else: img[i][j] = 1.0 #", "to the log file.''' INTRO_MSG = '''\\ **printerc** Welcome! ''' '''Welcome message for", "x == w - 1: break translate('X+P', confirm) x += 1 print 'Returning", "== w - 1: translate('Z-') break translate('X+P', confirm) x += 1 if y", ": 'Y+P', 'k' : 'Y-P', 'i' : 'Z+', 'o' : 'Z-', } getch", "negative translation across :math:`Y`. ``Y+p`` send 1 single pulse for positive translation across", "============ =============== connected connected 1 disconnected connected 2 connected disconnected 4 disconnected disconnected", "s.close() except serial.SerialException: pass return available def mm12_script_status(): '''Indicate whether the MM12 script", "stands for Axis, Direction, Mode. Use the following table to select the kind", "print 'Operation interrupted, flushing command port' def print_image_better(confirm=False): def report_position(x, y): print 'At", "interrupted, flushing command port' def print_image_better_better(confirm=False): '''Automatically print the input image. Parameters ----------", "channels high.''' STEPPER_CHANNELS_TARGET_OFF = 5600 '''Target value in units of quarter-:math:`\\\\mu s` that", "servo_acceleration, servo_speed): assert isinstance(intarg, int) with open(fpath, 'w') as f: print >>f, MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration,", "that performs translation in units of pixels through the stepper motor (default is", "command port' def print_image_better(confirm=False): def report_position(x, y): print 'At row {0}, column {1}'.format(y,", "the stepper motor needs to translate 1 pixel across the :math:`X` or :math:`Y`", "__name__ == \"__main__\": # program name from file name. PN = os.path.splitext(sys.argv[0])[0] logf", "the microstepping format with the jumpers *MS1* and *MS2*. Use the following table", "is an interactive command line interface for the numerical control of the **printer73x**", "0}}'.format(y) while True: if x == 0: break translate('X-P', confirm) x -= 1", "script_status : {``MM12_SCRIPT_RUNNING``, ``MM12_SCRIPT_STOPPED``} ''' assert sp.write('\\xae') == 1 return sp.read(1) def translate(adm,", "at bottom sets global names too. # ========================================================================== # ========================================================================== LOGF = 'log.rst'", "isinstance(intarg, int) with open(fpath, 'w') as f: print >>f, MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration, servo_speed=servo_speed) for i", "Mode. Use the following table to select the kind of translation you want", "'``{0}`` just opened *command port* ``{1}``'.format(PN, sp.port) msg = '``{0}`` is now connected", "x) def print_img_pixel(x, y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm) try: msg =", "{0}'.format(y) while True: report_position(x, y) if img[y][x] == 0.0: translate('Z+', confirm) if img[y][x-1]", "build_mm12_script(fpath, ntransitions=TRANSITIONS_PER_PIXEL, delay=1, servo_acceleration=0, servo_speed=100): '''Build a script to be loaded on the", "the XMS1, XMS2, YMS1, YMS2 jumpers in mcircuit). If ``False`` perform translation in", "for available physical or virtual serial ports. Returns ------- available : list of", "def color_in_this_row(row): for pixel in row: if pixel == 0.0: return True return", "MM12 serial command port. ''' global sp sp = serial.Serial(port=commandport_id) assert sp.isOpen() print", "interface for the numerical control of the **printer73x** system. printerc drives printerm through", "printerm tool visit every element of the row from :math:`a_{0,0}` to :math:`a_{0,w-1}` then", "exit.''' try: print >>logf, 'Closing ``{0}`` *command port*'.format(sp.port) sp.close() except NameError: pass print", "quit ''' '''Template for the MM12 script subroutine that drives the servo motor.'''", "sp sp = serial.Serial(port=commandport_id) assert sp.isOpen() print >>logf, '``{0}`` just opened *command port*", "str *adm* stands for Axis, Direction, Mode. Use the following table to select", "= img.shape npixels = b * w nprints = nnotprints = 0 assert", "perform translation in units of pixels (default is True). ''' if precise: keys2translation", "``False``). ''' # Start until script is not running. while mm12_script_status() == MM12_SCRIPT_RUNNING:", "the array representation. **w** : int Image's width, number of columns in the", "== 0: translate('Z-') break translate('X-P', confirm) x -= 1 if y == b", "send :math:`n` pulses for negative translation across :math:`X`. ``X+P`` send :math:`n` pulses for", "unit across the respective axis). ======= ================================================================ *adm* translation ======= ================================================================ ``X-p`` send", "no more rows to visit. In any position, if the corresponding pixel is", "MM12_SCRIPT_RUNNING = '\\x00' '''Byte value that the MM12 returns when the script is", "to the screen. References ========== .. [GETCHRECIPE] http://code.activestate.com/recipes/134892/ \"\"\" def __init__(self): try: self.impl", "any translation (default is ``False``). Notes ----- Let :math:`\\mathbf{A}` be the matrix representation", "imports. import serial import IPython import numpy as np # remove import matplotlib.image", "printerm through the MM12 command port. Parameters ---------- commandport_id : str or int", "Notes ----- Let :math:`\\mathbf{A}` be the matrix representation of the input image. :math:`a_{y,x}`", ":math:`a_{0,w-1}` then moves to the next row (:math:`a_{1,w-1}`) and visits every element of", "8-bit grayscale, non-interlaced. invert : boolean, optional Invert the image if ``True`` (default", "that correspond to the translations across the :math:`X`, :math:`Y` and :math:`Z` axis, and", "routines in order to produce the trajectory of the tool printing the image.", "{{delay}} delay {on} {step_channel} servo {{delay}} delay quit ''' '''Template for the MM12", "for j in range(w): if img[i][j] > 0.0: img[i][j] = 0.0 else: img[i][j]", "stepper motor in units of pixels,''' SUB_STEPPER_PULSE_TEMPLATE = '''sub {name} {dir} {dir_channel} servo", "sp.flush() print 'Operation interrupted, flushing command port' if __name__ == \"__main__\": # program", "b - 1: break translate('Y+P', confirm) y += 1 print 'Returning to a_{{0,", "element of the row from :math:`a_{0,0}` to :math:`a_{0,w-1}` then moves to the next", "MM12_SUBROUTINES.items(): if subroutine_id is value['subroutine_id']: return key for intarg in (ntransitions, delay, servo_acceleration,", "8 ============ ============ =============== .. note:: Both stepper motor driver boards must have", "{step_channel} servo {{delay}} delay 1 minus repeat quit ''' '''Template for the MM12", "confirmation before any translation (default is ``False``). Notes ----- Let :math:`\\mathbf{A}` be the", "dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X-P' : { 'subroutine_id' : 2, 'subroutine_body' :", "is no longer moving. repeat 75 delay quit ''' '''Template for the MM12", "step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y+P' : { 'subroutine_id' : 7, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format(", "tool to the on position (:math:`Z`). ======= ================================================================ confirm: boolean, optional If ``True``,", "driver boards must have the same jumper configuration. ''' STEPS_PER_PIXEL = 90 '''Number", "in (logf, sys.stdout): print >>f, msg def manual_translation_mode(precise=True): '''Manually translate the printerm tool", "Path to the image file. Must be PNG, 8-bit grayscale, non-interlaced. invert :", "global img, b, w print 'Loading ``{0}``...'.format(imgpath) img = mpimg.imread(fname=imgpath, format='png') b, w", "port*'.format(sp.port) sp.close() except NameError: pass print >>logf, 'END' logf.close() print '\\nThanks for using", "``{1}``'.format(PN, sp.port) msg = '``{0}`` is now connected to ``printerm`` through ``{1}``'.format( PN,", "a stepper motor in units of pixels,''' SUB_STEPPER_PULSE_TEMPLATE = '''sub {name} {dir} {dir_channel}", "the script file. ntransitions : int, optional Number of low-to-high transitions to perform", "numerical control of the **printer73x** system. printerc drives printerm through mcircuit; printerc stablishes", "echo to the screen. References ========== .. [GETCHRECIPE] http://code.activestate.com/recipes/134892/ \"\"\" def __init__(self): try:", "sp.flush() print 'Operation interrupted, flushing command port' def print_image_better(confirm=False): def report_position(x, y): print", "servo motor.''' MM12_SCRIPT_INIT = '''\\ {{servo_acceleration}} {servo_channel} acceleration {{servo_speed}} {servo_channel} speed '''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel']) '''MM12", "the printerm tool visit every element of the row from :math:`a_{0,0}` to :math:`a_{0,w-1}`", "PNG, 8-bit grayscale, non-interlaced. invert : boolean, optional Invert the image if ``True``", "across the :math:`XY` plane. Parameters ---------- precise : boolean, optional If ``True``, perform", "format with the jumpers *MS1* and *MS2*. Use the following table to set", "+= 1 else: nprints += 1 assert (nnotprints + nprints) == npixels #", "confirm=False) def print_pixel(confirm=False): if confirm: raw_input() translate('Z+', confirm=False) translate('Z-', confirm=False) def print_image(confirm=False): def", "dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y-P' : { 'subroutine_id' : 6, 'subroutine_body'", "'subroutine_id' : 8, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_off', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['off']*4) }, 'Z+' : {", "'\\x01' '''Byte value that the MM12 returns when the script is stopped.''' #", "to do on exit.''' try: print >>logf, 'Closing ``{0}`` *command port*'.format(sp.port) sp.close() except", ">>logf, '``{0}`` just opened *command port* ``{1}``'.format(PN, sp.port) msg = '``{0}`` is now", "**img** : array of booleans 2-d array representation of the image. **b** :", "to ``printerm`` through ``{1}``'.format( PN, sp.port) for f in (logf, sys.stdout): print >>f,", "of quarter-:math:`\\\\mu s` that drives the stepper channels high.''' STEPPER_CHANNELS_TARGET_OFF = 5600 '''Target", "to the image file. Must be PNG, 8-bit grayscale, non-interlaced. invert : boolean,", "# Contact: <EMAIL> '''Numerical controller for the printer73x system. **printerc** is an interactive", "number of rows in the array representation. **w** : int Image's width, number", "4 disconnected disconnected 8 ============ ============ =============== .. note:: Both stepper motor driver", "servo_acceleration : int, optional Sets the acceleration of the servo signal channel in", "of rows in the array representation. **w** : int Image's width, number of", "drives the stepper channels high.''' STEPPER_CHANNELS_TARGET_OFF = 5600 '''Target value in units of", "http://code.activestate.com/recipes/134892/ \"\"\" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix()", "nprints) == npixels # If ``nprints == 0`` then no pixel will be", "6800 '''Target value in units of quarter-:math:`\\\\mu s` that drives the stepper channels", "0 assert (b > 0) and (w > 0) print 'Processing the image...'", "the MM12 serial command port. ''' global sp sp = serial.Serial(port=commandport_id) assert sp.isOpen()", "(default is 0). servo_speed : int, optional Sets the speed of the servo", "if precise: keys2translation = { 'h' : 'X-p', 'l' : 'X+p', 'j' :", "y) if img[y][x] == 0.0: translate('Z+', confirm) if img[y][x-1] != 0.0: translate('Z-', confirm)", "y -= 1 while True: if x == 0: break translate('X-P', confirm) x", "mcircuit, and mcircuit is coupled to printerm through the motors. mcircuit (actually MM12,", "print 'Printing across the row {0}'.format(y) while True: report_position(x, y) print_img_pixel(x, y, confirm)", "# ========================================================================== # ========================================================================== # ========================================================================== class Getch: \"\"\"Gets a single character from", "the number and name of the port. Notes ----- Directly copied from example", "---------- precise : boolean, optional If ``True``, perform translation in units of single", "'Returning to a_{{{0}, 0}}'.format(y) while True: if x == 0: break translate('X-P', confirm)", "the script is stopped.''' # ========================================================================== # ========================================================================== # ========================================================================== class Getch: \"\"\"Gets", "except serial.SerialException: pass return available def mm12_script_status(): '''Indicate whether the MM12 script is", "confirm=False) def print_image(confirm=False): def report_position(x, y): print 'At row {0}, column {1}'.format(y, x)", "y -= 1 print 'The image has been printed' except KeyboardInterrupt: sp.flush() print", "try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl()", "True: if y == 0: break translate('Y-P', confirm) y -= 1 print 'The", "in range(w): if img[i][j] > 0.0: nnotprints += 1 else: nprints += 1", "on the microstep format selected through the XMS1, XMS2, YMS1, YMS2 jumpers in", ">>f, subroutine_body def prepare_img(imgpath, invert=False, show=False): '''Perform any necessary processing for the input", "y == b - 1: break translate('Y+P', confirm) y += 1 print 'Returning", "optional Sets the speed of the servo signal channel in units of (0.25", "``(num, name)`` tuple with the number and name of the port. Notes -----", "{0}'.format(y) while True: report_position(x, y) if img[y][x] == 0.0: translate('Z+', confirm) try: if", "wait until is is no longer moving. repeat 75 delay quit ''' '''Template", "}, 'Y+P' : { 'subroutine_id' : 7, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_pos_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'],", "printerm tool to translate a pixel unit across the respective axis). ======= ================================================================", "{dir_channel} servo # set direction {off} {step_channel} servo {{delay}} delay {on} {step_channel} servo", ": STEPPER_CHANNELS_TARGET_ON, 'step_channel': 1, }, 'Y' : { 'dir_channel' : 2, 'dir_positive' :", "is is no longer moving. repeat 75 delay quit ''' '''Template for the", "break while mm12_script_status() == MM12_SCRIPT_RUNNING: pass translate(keys2translation[ch], confirm=False) def print_pixel(confirm=False): if confirm: raw_input()", "position the printerm tool visit every element of the row from :math:`a_{0,0}` to", "{{delay}} delay quit ''' '''Template for the MM12 script subroutines that drive a", "returns when the script is stopped.''' # ========================================================================== # ========================================================================== # ========================================================================== class", "steps the stepper motor needs to translate 1 pixel across the :math:`X` or", "[GETCHRECIPE] http://code.activestate.com/recipes/134892/ \"\"\" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl =", "between each transition in the subroutines that perform translation through the stepper motors", "on=STEPPER_CHANNELS_TARGET_ON), }, 'Y-P' : { 'subroutine_id' : 6, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_neg_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_negative'],", "or int Serial device name or port number number of the MM12 serial", "of the image. **b** : int Image's height, number of rows in the", "MM12_SCRIPT_INIT.format(servo_acceleration=servo_acceleration, servo_speed=servo_speed) for i in range(len( MM12_SUBROUTINES)): subroutine_key = get_subroutine_key_by_id(i) subroutine_body = MM12_SUBROUTINES[subroutine_key]['subroutine_body']", "-= 1 print 'The image has been printed' except KeyboardInterrupt: sp.flush() print 'Operation", "the :math:`X` or :math:`Y` axes.''' SRV_SIGNAL_CHANNEL_TARGET_OFF = 940 ''':math:`Z` axis servo motor pulse", "print 'Returning to a_{{{0}, 0}}'.format(y) while True: if x == 0: break translate('X-P',", "= 0.0 else: img[i][j] = 1.0 # Check for pixel with and without", "break translate('X+P', confirm) x += 1 if y == b - 1: break", "#!/usr/bin/env python # coding=utf-8 # Author: <NAME> # Contact: <EMAIL> '''Numerical controller for", "the tool to the on position (:math:`Z`). ======= ================================================================ confirm: boolean, optional If", "the upper left corner of the input image. #. :math:`a_{b-1,w-1}` corresponds to the", "MM12_SCRIPT_RUNNING: pass translate(keys2translation[ch], confirm=False) def print_pixel(confirm=False): if confirm: raw_input() translate('Z+', confirm=False) translate('Z-', confirm=False)", "serial ports. Returns ------- available : list of tuples Each element of the", "file. Must be PNG, 8-bit grayscale, non-interlaced. invert : boolean, optional Invert the", "translation you want to perform (where :math:`n` is the number of pulses for", "with {0} rows and {1} columns'.format(b, w) print msg x = y =", "printerm through mcircuit; printerc stablishes a serial connection with mcircuit, and mcircuit is", "axis). ======= ================================================================ *adm* translation ======= ================================================================ ``X-p`` send 1 single pulse for", "pixel. Comparing :math:`\\mathbf{A}` with the input image from a front perspective: #. :math:`a_{0,0}`", "0.0: nnotprints += 1 else: nprints += 1 assert (nnotprints + nprints) ==", "NameError: pass print >>logf, 'END' logf.close() print '\\nThanks for using ``printerc``!\\n' # Invoke", "}, 'Z+' : { 'subroutine_id' : 9, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_on', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['on']*4)", "fpath : str-like Path location where to save the script file. ntransitions :", "import msvcrt return msvcrt.getch() def on_exit(): '''Actions to do on exit.''' try: print", "name='z_position_off', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['off']*4) }, 'Z+' : { 'subroutine_id' : 9, 'subroutine_body' : SUB_SERVO_TEMPLATE.format(", "nprints > 0 print 'Loaded ``{0}`` with {1} pixels, {2} of which have", "raw_input() assert sp.write(str2write) == 2 #if 'Z' in adm: #time.sleep(0.1) def build_mm12_script(fpath, ntransitions=TRANSITIONS_PER_PIXEL,", "ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: '''Windows implementation", "z = 0 # We are at HOME position. while True: # To", "positive translation across :math:`Y`. ``Y-P`` send :math:`n` pulses for negative translation across :math:`Y`.", "= '''sub {name} {dir} {dir_channel} servo # set direction {off} {step_channel} servo {{delay}}", "so on until there are no more rows to visit. In any position,", "not in subroutine_key: subroutine_body = subroutine_body.format(delay=delay) if 'P' in subroutine_key: subroutine_body = subroutine_body.format(ntransitions=ntransitions)", "signal channel in units of (0.25 us)/(10 ms)/(80 ms) (default is 0). servo_speed", "as np # remove import matplotlib.image as mpimg import matplotlib.pyplot as plt import", "row: if pixel == 0.0: return True return False try: msg = 'Preparing", "across the row {0}'.format(y) while True: report_position(x, y) print_img_pixel(x, y, confirm) if x", "# Start until script is not running. while mm12_script_status() == MM12_SCRIPT_RUNNING: pass subroutine_id", "the right. print 'Printing across the row {0}'.format(y) while True: report_position(x, y) if", "the left. print 'Printing across the row {0}'.format(y) while True: report_position(x, y) if", "{servo_channel} acceleration {{servo_speed}} {servo_channel} speed '''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel']) '''MM12 script initialization.''' MM12_SUBROUTINES = { 'X-p'", "minus repeat quit ''' '''Template for the MM12 script subroutines that drive a", "be the matrix representation of the input image. :math:`a_{y,x}` as an element of", "translation.''' SUB_SERVO_TEMPLATE = '''sub {name} {position} {channel} servo begin get_moving_state while # wait", ":math:`n` pulses for negative translation across :math:`Y`. ``Y+P`` send :math:`n` pulses for positive", "dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Z-' : { 'subroutine_id' : 8, 'subroutine_body'", "of the input image. Starting from the HOME position the printerm tool visit", ": { 'dir_channel' : 0, 'dir_positive' : STEPPER_CHANNELS_TARGET_OFF, 'dir_negative' : STEPPER_CHANNELS_TARGET_ON, 'step_channel': 1,", "'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_off', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['off']*4) }, 'Z+' : { 'subroutine_id' : 9,", ": int Image's height, number of rows in the array representation. **w** :", "message for command line interface.''' # MM12 # ========================================================================== TRANSITIONS_PER_STEP = 2 '''The", "the tool printing the image. ''' # Standard library imports. from __future__ import", "``Y+p`` send 1 single pulse for positive translation across :math:`Y`. ``Y-P`` send :math:`n`", "{name} {position} {channel} servo begin get_moving_state while # wait until is is no", "True: if x == 0: break translate('X-P', confirm) x -= 1 print 'The", "the same jumper configuration. ''' STEPS_PER_PIXEL = 90 '''Number of steps the stepper", "global sp sp = serial.Serial(port=commandport_id) assert sp.isOpen() print >>logf, '``{0}`` just opened *command", "low-to-high transitions to perform in the subroutines that performs translation in units of", "= 0 assert (b > 0) and (w > 0) print 'Processing the", "array of booleans 2-d array representation of the image. **b** : int Image's", "'''The board sets the microstepping format with the jumpers *MS1* and *MS2*. Use", "printed' except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' def print_image_better_better(confirm=False): '''Automatically", ": 'Y-P', 'i' : 'Z+', 'o' : 'Z-', } getch = Getch() while", "'''Path to the log file.''' INTRO_MSG = '''\\ **printerc** Welcome! ''' '''Welcome message", "0 # We are at HOME position. while True: print 'Printing across the", "getch = Getch() while True: ch = getch() if ch not in keys2translation.keys():", "up).''' STEPPER_CHANNELS_TARGET_ON = 6800 '''Target value in units of quarter-:math:`\\\\mu s` that drives", "return available def mm12_script_status(): '''Indicate whether the MM12 script is running or stopped.", "of the input image. #. :math:`a_{b-1,w-1}` corresponds to the lower right corner of", "transitions sent to the stepper motor drivers (how much the tool is translated", "\"\"\"Gets a single character from standard input. Does not echo to the screen.", "drivers (how much the tool is translated depends on the microstep format selected", "========================================================================== TRANSITIONS_PER_STEP = 2 '''The board sets the microstepping format with the jumpers", "def mm12_script_status(): '''Indicate whether the MM12 script is running or stopped. Returns -------", "i in range(len( MM12_SUBROUTINES)): subroutine_key = get_subroutine_key_by_id(i) subroutine_body = MM12_SUBROUTINES[subroutine_key]['subroutine_body'] if 'Z' not", "that disables printing (moves the tool up).''' STEPPER_CHANNELS_TARGET_ON = 6800 '''Target value in", "no pixel will be printed. assert nprints > 0 print 'Loaded ``{0}`` with", "and :math:`Z` axis, and then printerc execute these routines in order to produce", "is ``TRANSITIONS_PER_PIXEL``). delay : int, optional Delay (in milliseconds) between each transition in", "table to set this constant: ============ ============ =============== MS1 MS2 TRANSITIONS_PER_STEP ============ ============", "- 1: translate('Z-') break translate('Y+P', confirm) y += 1 print 'Returning to a_{{0,", "name='x_neg_pulse', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X+p' : { 'subroutine_id' : 1,", "'At row {0}, column {1}'.format(y, x) def print_img_pixel(x, y, confirm=False): if img[y][x] ==", "names: **img** : array of booleans 2-d array representation of the image. **b**", "set this constant: ============ ============ =============== MS1 MS2 TRANSITIONS_PER_STEP ============ ============ =============== connected", "'dir_positive' : STEPPER_CHANNELS_TARGET_ON, 'dir_negative' : STEPPER_CHANNELS_TARGET_OFF, 'step_channel': 3, }, 'Z' : { 'channel'", "'''MM12 script initialization.''' MM12_SUBROUTINES = { 'X-p' : { 'subroutine_id' : 0, 'subroutine_body'", ": {``MM12_SCRIPT_RUNNING``, ``MM12_SCRIPT_STOPPED``} ''' assert sp.write('\\xae') == 1 return sp.read(1) def translate(adm, confirm=False):", "0) print 'Processing the image...' # only total black and white, no grays.", "w) print msg x = y = z = 0 # We are", "a_{{{0}, 0}}'.format(y) while True: if x == 0: break translate('X-P', confirm) x -=", "with the input image from a front perspective: #. :math:`a_{0,0}` corresponds to the", "SRV_SIGNAL_CHANNEL_TARGET_OFF, 'off' : SRV_SIGNAL_CHANNEL_TARGET_ON, }, } '''Configuration of the MM12 channels for the", ": { 'dir_channel' : 2, 'dir_positive' : STEPPER_CHANNELS_TARGET_ON, 'dir_negative' : STEPPER_CHANNELS_TARGET_OFF, 'step_channel': 3,", "2 connected disconnected 4 disconnected disconnected 8 ============ ============ =============== .. note:: Both", "translate 1 pixel across the :math:`X` or :math:`Y` axes.''' SRV_SIGNAL_CHANNEL_TARGET_OFF = 940 ''':math:`Z`", "{0} rows and {1} columns'.format(b, w) print msg x = y = z", "= Getch() while True: ch = getch() if ch not in keys2translation.keys(): break", "repeat quit ''' '''Template for the MM12 script subroutines that drive a stepper", "that drives the servo motor.''' MM12_SCRIPT_INIT = '''\\ {{servo_acceleration}} {servo_channel} acceleration {{servo_speed}} {servo_channel}", "Image's width, number of columns in the array representation. ''' global img, b,", "of tuples Each element of the list is a ``(num, name)`` tuple with", "port. Notes ----- Directly copied from example from `pyserial <http://sourceforge.net/projects/pyserial/files/package>`_ project. ''' available", "def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() def on_exit(): '''Actions", "the screen. References ========== .. [GETCHRECIPE] http://code.activestate.com/recipes/134892/ \"\"\" def __init__(self): try: self.impl =", "dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'X+P' : { 'subroutine_id' : 3, 'subroutine_body'", "translate('Y-P', confirm) y -= 1 while True: if x == 0: break translate('X-P',", "Wait for confirmation before any translation (default is ``False``). Notes ----- Let :math:`\\mathbf{A}`", "{ 'channel' : 4, 'on' : SRV_SIGNAL_CHANNEL_TARGET_OFF, 'off' : SRV_SIGNAL_CHANNEL_TARGET_ON, }, } '''Configuration", "(0.25 us)/(10 ms)/(80 ms) (default is 0). servo_speed : int, optional Sets the", "``{0}`` *command port*'.format(sp.port) sp.close() except NameError: pass print >>logf, 'END' logf.close() print '\\nThanks", ": 'Z-', } else: keys2translation = { 'h' : 'X-P', 'l' : 'X+P',", ": STEPPER_CHANNELS_TARGET_OFF, 'dir_negative' : STEPPER_CHANNELS_TARGET_ON, 'step_channel': 1, }, 'Y' : { 'dir_channel' :", "{0} rows and {1} columns'.format(b, w) print msg x = y = 0", "pass return available def mm12_script_status(): '''Indicate whether the MM12 script is running or", "'''Build a script to be loaded on the MM12. Parameters ---------- fpath :", "def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd =", "the kind of translation you want to perform (where :math:`n` is the number", "----- Let :math:`\\mathbf{A}` be the matrix representation of the input image. :math:`a_{y,x}` as", "the :math:`XY` plane. Parameters ---------- precise : boolean, optional If ``True``, perform translation", "in units of quarter-:math:`\\\\mu s` that enables printing (moves the tool down).''' SRV_SIGNAL_CHANNEL_TARGET_ON", "# coding=utf-8 # Author: <NAME> # Contact: <EMAIL> '''Numerical controller for the printer73x", "dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X+p' : { 'subroutine_id' : 1, 'subroutine_body' :", "enables printing (moves the tool down).''' SRV_SIGNAL_CHANNEL_TARGET_ON = 2175 SRV_SIGNAL_CHANNEL_TARGET_ON = 1580 ''':math:`Z`", "'''Number of low-to-high transitions the stepper motors need to translate 1 pixel across", "across the respective axis). ======= ================================================================ *adm* translation ======= ================================================================ ``X-p`` send 1", "microstepping format with the jumpers *MS1* and *MS2*. Use the following table to", "{on} {step_channel} servo {{delay}} delay 1 minus repeat quit ''' '''Template for the", "stepper motors need to translate 1 pixel across the :math:`X` or :math:`Y` axes.'''", "================================================================ *adm* translation ======= ================================================================ ``X-p`` send 1 single pulse for negative translation", "in units of quarter-:math:`\\\\mu s` that drives the stepper channels low.''' MM12_AXES_CHANNELS =", "tuple with the number and name of the port. Notes ----- Directly copied", "from example from `pyserial <http://sourceforge.net/projects/pyserial/files/package>`_ project. ''' available = [] for i in", "'on' : SRV_SIGNAL_CHANNEL_TARGET_OFF, 'off' : SRV_SIGNAL_CHANNEL_TARGET_ON, }, } '''Configuration of the MM12 channels", "be reproduced by printerm. Parameters ---------- imgpath : str-like Path to the image", "# remove import matplotlib.image as mpimg import matplotlib.pyplot as plt import matplotlib.cm as", "quarter-:math:`\\\\mu s` that drives the stepper channels low.''' MM12_AXES_CHANNELS = { 'X' :", "\"\"\" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def", "serial connection with mcircuit, and mcircuit is coupled to printerm through the motors.", "of booleans 2-d array representation of the image. **b** : int Image's height,", "for positive translation across :math:`Y`. ``Z-`` move the tool to the off position", "units of low-to-high transitions, for a precise but slow translation.''' SUB_SERVO_TEMPLATE = '''sub", "0.0 else: img[i][j] = 1.0 if invert: print 'Inverting image...' for i in", "LOGF = 'log.rst' '''Path to the log file.''' INTRO_MSG = '''\\ **printerc** Welcome!", "(ntransitions, delay, servo_acceleration, servo_speed): assert isinstance(intarg, int) with open(fpath, 'w') as f: print", "'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_neg_pixel', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'X+P' :", "termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class", ":math:`XY` plane. Parameters ---------- precise : boolean, optional If ``True``, perform translation in", "rows to visit. In any position, if the corresponding pixel is black then", "7, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_pos_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Z-'", "4, 'on' : SRV_SIGNAL_CHANNEL_TARGET_OFF, 'off' : SRV_SIGNAL_CHANNEL_TARGET_ON, }, } '''Configuration of the MM12", "MM12 returns when the script is running.''' MM12_SCRIPT_STOPPED = '\\x01' '''Byte value that", "{dir_channel} servo # set direction begin dup while {off} {step_channel} servo {{delay}} delay", "the image. **b** : int Image's height, number of rows in the array", "0.0: return True return False try: msg = 'Preparing to print an image", "interactive command line interface for the numerical control of the **printer73x** system. printerc", "``True``, perform translation in units of single low-to-high transitions sent to the stepper", "a single axis at a time. Parameters ---------- adm: str *adm* stands for", "routines that correspond to the translations across the :math:`X`, :math:`Y` and :math:`Z` axis,", "} '''Configuration of the MM12 channels for the servo and stepper motors outputs.'''", "'Y-P', 'i' : 'Z+', 'o' : 'Z-', } getch = Getch() while True:", "the routines that correspond to the translations across the :math:`X`, :math:`Y` and :math:`Z`", "for confirmation before any translation (default is ``False``). Notes ----- Let :math:`\\mathbf{A}` be", "TRANSITIONS_PER_STEP ============ ============ =============== connected connected 1 disconnected connected 2 connected disconnected 4", "returns when the script is running.''' MM12_SCRIPT_STOPPED = '\\x01' '''Byte value that the", "connect_printerm(commandport_id): '''Connect printerc with printerm through the MM12 command port. Parameters ---------- commandport_id", "direction begin dup while {off} {step_channel} servo {{delay}} delay {on} {step_channel} servo {{delay}}", "adm: str *adm* stands for Axis, Direction, Mode. Use the following table to", "servo # set direction {off} {step_channel} servo {{delay}} delay {on} {step_channel} servo {{delay}}", "(b > 0) and (w > 0) print 'Processing the image...' # only", "finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: '''Windows implementation of class ``Getch``.'''", "commandport_id : str or int Serial device name or port number number of", "- 1: break translate('Y+P', confirm) y += 1 print 'Returning to a_{{0, 0}}'.format(y)", "motor drivers (how much the tool is translated depends on the microstep format", "if y == b - 1: translate('Z-') break translate('Y+P', confirm) y += 1", "for the MM12 script subroutines that drive a stepper motor in units of", "script initialization.''' MM12_SUBROUTINES = { 'X-p' : { 'subroutine_id' : 0, 'subroutine_body' :", "want to perform (where :math:`n` is the number of pulses for the printerm", "{0}'.format(y) while True: report_position(x, y) print_img_pixel(x, y, confirm) if x == 0: break", "'Z' : { 'channel' : 4, 'on' : SRV_SIGNAL_CHANNEL_TARGET_OFF, 'off' : SRV_SIGNAL_CHANNEL_TARGET_ON, },", "constant: ============ ============ =============== MS1 MS2 TRANSITIONS_PER_STEP ============ ============ =============== connected connected 1", "subsystem) loads in its memory the routines that correspond to the translations across", "'''\\ {{servo_acceleration}} {servo_channel} acceleration {{servo_speed}} {servo_channel} speed '''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel']) '''MM12 script initialization.''' MM12_SUBROUTINES =", "translate('Z-', confirm) except IndexError as e: pass if x == w - 1:", "for the servo and stepper motors outputs.''' SUB_STEPPER_PIXEL_TEMPLATE = '''sub {name} {{{{ntransitions}}}} {dir}", "break translate('Y+P', confirm) y += 1 print 'Printing across the row {0}'.format(y) while", "msvcrt def __call__(self): import msvcrt return msvcrt.getch() def on_exit(): '''Actions to do on", "i in range(b): for j in range(w): if img[i][j] > 0.0: img[i][j] =", "dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y-p' : { 'subroutine_id' : 4, 'subroutine_body'", "non-interlaced. invert : boolean, optional Invert the image if ``True`` (default is ``False``).", "int, optional Number of low-to-high transitions to perform in the subroutines that performs", "disconnected connected 2 connected disconnected 4 disconnected disconnected 8 ============ ============ =============== ..", "s` that drives the stepper channels low.''' MM12_AXES_CHANNELS = { 'X' : {", ": SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_neg_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y+P' : {", "send 1 single pulse for negative translation across :math:`X`. ``X+p`` send 1 single", "need to translate 1 pixel across the :math:`X` or :math:`Y` axes.''' SRV_SIGNAL_CHANNEL_TARGET_OFF =", "jumpers in mcircuit). If ``False`` perform translation in units of pixels (default is", "# Same as **printer73x**. __version__ = '0.09' # GLOBAL CONSTANT names. *if main*", "HOME position. while True: # To the right. print 'Printing across the row", "False try: msg = 'Preparing to print an image with {0} rows and", "must confirm the translation by pressing Enter (default is ``False``). ''' # Start", "translation across :math:`Y`. ``Y-P`` send :math:`n` pulses for negative translation across :math:`Y`. ``Y+P``", "**b** : int Image's height, number of rows in the array representation. **w**", "is ``False``). show : boolean, optional Show the image if ``True`` (default is", "for i in range(len( MM12_SUBROUTINES)): subroutine_key = get_subroutine_key_by_id(i) subroutine_body = MM12_SUBROUTINES[subroutine_key]['subroutine_body'] if 'Z'", "system for available physical or virtual serial ports. Returns ------- available : list", "confirm) x += 1 if y == b - 1: break translate('Y+P', confirm)", "location where to save the script file. ntransitions : int, optional Number of", "the array representation. ''' global img, b, w print 'Loading ``{0}``...'.format(imgpath) img =", "file.''' INTRO_MSG = '''\\ **printerc** Welcome! ''' '''Welcome message for command line interface.'''", "the :math:`X` or :math:`Y` axes.''' TRANSITIONS_PER_PIXEL = STEPS_PER_PIXEL * TRANSITIONS_PER_STEP '''Number of low-to-high", "MM12 script is running or stopped. Returns ------- script_status : {``MM12_SCRIPT_RUNNING``, ``MM12_SCRIPT_STOPPED``} '''", "dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y+p' : { 'subroutine_id' : 5, 'subroutine_body' :", "import time # Related third party imports. import serial import IPython import numpy", "> 0 print 'Loaded ``{0}`` with {1} pixels, {2} of which have color'.format(", ":math:`Y` axes.''' SRV_SIGNAL_CHANNEL_TARGET_OFF = 940 ''':math:`Z` axis servo motor pulse width in units", "following table to set this constant: ============ ============ =============== MS1 MS2 TRANSITIONS_PER_STEP ============", "the tool to the off position (:math:`Z`). ``Z+`` move the tool to the", "== MM12_SCRIPT_RUNNING: pass translate(keys2translation[ch], confirm=False) def print_pixel(confirm=False): if confirm: raw_input() translate('Z+', confirm=False) translate('Z-',", "import matplotlib.image as mpimg import matplotlib.pyplot as plt import matplotlib.cm as cm #", "- 1: break translate('X+P', confirm) x += 1 print 'Returning to a_{{{0}, 0}}'.format(y)", "Notes ----- Directly copied from example from `pyserial <http://sourceforge.net/projects/pyserial/files/package>`_ project. ''' available =", "``False``). show : boolean, optional Show the image if ``True`` (default is ``False``).", "* TRANSITIONS_PER_STEP '''Number of low-to-high transitions the stepper motors need to translate 1", ": 4, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_neg_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y+p'", "translation in units of pixels through the stepper motor (default is ``TRANSITIONS_PER_PIXEL``). delay", "subroutine_id is value['subroutine_id']: return key for intarg in (ntransitions, delay, servo_acceleration, servo_speed): assert", "translate('X+P', confirm) x += 1 if y == b - 1: break translate('Y+P',", "'Y-p' : { 'subroutine_id' : 4, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_neg_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF,", "bottom sets global names too. # ========================================================================== # ========================================================================== LOGF = 'log.rst' '''Path", "printing (moves the tool up).''' STEPPER_CHANNELS_TARGET_ON = 6800 '''Target value in units of", "down).''' SRV_SIGNAL_CHANNEL_TARGET_ON = 2175 SRV_SIGNAL_CHANNEL_TARGET_ON = 1580 ''':math:`Z` axis servo motor pulse width", "Delay (in milliseconds) between each transition in the subroutines that perform translation through", "x -= 1 if y == b - 1: translate('Z-') break translate('Y+P', confirm)", "def prepare_img(imgpath, invert=False, show=False): '''Perform any necessary processing for the input image to", "script is running.''' MM12_SCRIPT_STOPPED = '\\x01' '''Byte value that the MM12 returns when", "# We are at HOME position. while True: # To the right. print", "precise but slow translation.''' SUB_SERVO_TEMPLATE = '''sub {name} {position} {channel} servo begin get_moving_state", "ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: '''Unix implementation of", "while True: if y == 0: break translate('Y-P', confirm) y -= 1 print", "show : boolean, optional Show the image if ``True`` (default is ``False``). Notes", "for i in range(b): for j in range(w): if img[i][j] > 0.0: nnotprints", "through ``{1}``'.format( PN, sp.port) for f in (logf, sys.stdout): print >>f, msg def", "subroutine_body.format(delay=delay) if 'P' in subroutine_key: subroutine_body = subroutine_body.format(ntransitions=ntransitions) print >>f, subroutine_body def prepare_img(imgpath,", "channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['on']*4) }, } '''Structure that builds and identifies the MM12 script subroutines.'''", "(default is ``False``). ''' # Start until script is not running. while mm12_script_status()", "subroutine_id]) if confirm: raw_input() assert sp.write(str2write) == 2 #if 'Z' in adm: #time.sleep(0.1)", "''' global sp sp = serial.Serial(port=commandport_id) assert sp.isOpen() print >>logf, '``{0}`` just opened", "can only perform translations across a single axis at a time. Parameters ----------", "adm: #time.sleep(0.1) def build_mm12_script(fpath, ntransitions=TRANSITIONS_PER_PIXEL, delay=1, servo_acceleration=0, servo_speed=100): '''Build a script to be", "}, 'Y-P' : { 'subroutine_id' : 6, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_neg_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'],", "2, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_neg_pixel', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'X+P'", "booleans 2-d array representation of the image. **b** : int Image's height, number", "y) if img[y][x] == 0.0: translate('Z+', confirm) try: if img[y][x+1] != 0.0: translate('Z-',", "grays. for i in range(b): for j in range(w): if img[i][j] < 0.9:", "SUB_STEPPER_PULSE_TEMPLATE.format( name='x_neg_pulse', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X+p' : { 'subroutine_id' :", "IndexError as e: pass if x == w - 1: translate('Z-') break translate('X+P',", "in (ntransitions, delay, servo_acceleration, servo_speed): assert isinstance(intarg, int) with open(fpath, 'w') as f:", "try: s = serial.Serial(i) available.append( (i, s.portstr)) s.close() except serial.SerialException: pass return available", "sets the following global names: **img** : array of booleans 2-d array representation", "for the printerm tool to translate a pixel unit across the respective axis).", "script file. ntransitions : int, optional Number of low-to-high transitions to perform in", "in subroutine_key: subroutine_body = subroutine_body.format(ntransitions=ntransitions) print >>f, subroutine_body def prepare_img(imgpath, invert=False, show=False): '''Perform", "e: pass if x == w - 1: translate('Z-') break translate('X+P', confirm) x", "}, 'Y-p' : { 'subroutine_id' : 4, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_neg_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'],", "translate('Z-', confirm=False) def print_image(confirm=False): def report_position(x, y): print 'At row {0}, column {1}'.format(y,", "servo {{delay}} delay quit ''' '''Template for the MM12 script subroutines that drive", "corresponds to the lower right corner of the input image. Starting from the", "the servo and stepper motors outputs.''' SUB_STEPPER_PIXEL_TEMPLATE = '''sub {name} {{{{ntransitions}}}} {dir} {dir_channel}", "''' global img, b, w print 'Loading ``{0}``...'.format(imgpath) img = mpimg.imread(fname=imgpath, format='png') b,", "axis at a time. Parameters ---------- adm: str *adm* stands for Axis, Direction,", "send :math:`n` pulses for positive translation across :math:`X`. ``Y-p`` send 1 single pulse", "return False try: msg = 'Preparing to print an image with {0} rows", "imports. from __future__ import division from pprint import pprint import sys import os", "positive translation across :math:`X`. ``X-P`` send :math:`n` pulses for negative translation across :math:`X`.", "'''Windows implementation of class ``Getch``.''' def __init__(self): import msvcrt def __call__(self): import msvcrt", "1 pixel across the :math:`X` or :math:`Y` axes.''' SRV_SIGNAL_CHANNEL_TARGET_OFF = 940 ''':math:`Z` axis", "input. Does not echo to the screen. References ========== .. [GETCHRECIPE] http://code.activestate.com/recipes/134892/ \"\"\"", "if confirm: raw_input() translate('Z+', confirm=False) translate('Z-', confirm=False) def print_image(confirm=False): def report_position(x, y): print", "direction {off} {step_channel} servo {{delay}} delay {on} {step_channel} servo {{delay}} delay quit '''", "def print_image_better(confirm=False): def report_position(x, y): print 'At row {0}, column {1}'.format(y, x) def", "name='x_neg_pixel', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'X+P' : { 'subroutine_id' :", "j in range(w): if img[i][j] > 0.0: img[i][j] = 0.0 else: img[i][j] =", "b - 1: translate('Z-') break translate('Y+P', confirm) y += 1 print 'Returning to", "2 '''The board sets the microstepping format with the jumpers *MS1* and *MS2*.", "the servo signal channel in units of (0.25 us)/(10 ms) (default is 100).", "value in units of quarter-:math:`\\\\mu s` that drives the stepper channels low.''' MM12_AXES_CHANNELS", "the **printer73x** system. printerc drives printerm through mcircuit; printerc stablishes a serial connection", "**printer73x**. __version__ = '0.09' # GLOBAL CONSTANT names. *if main* section at bottom", "units of pixels (default is True). ''' if precise: keys2translation = { 'h'", "-= 1 while True: if x == 0: break translate('X-P', confirm) x -=", "pulse for negative translation across :math:`Y`. ``Y+p`` send 1 single pulse for positive", "on=STEPPER_CHANNELS_TARGET_ON), }, 'X+p' : { 'subroutine_id' : 1, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_pos_pulse', dir=MM12_AXES_CHANNELS['X']['dir_positive'],", "============ ============ =============== connected connected 1 disconnected connected 2 connected disconnected 4 disconnected", "drives the stepper channels low.''' MM12_AXES_CHANNELS = { 'X' : { 'dir_channel' :", "servo and stepper motors outputs.''' SUB_STEPPER_PIXEL_TEMPLATE = '''sub {name} {{{{ntransitions}}}} {dir} {dir_channel} servo", "If ``nprints == 0`` then no pixel will be printed. assert nprints >", "image...' for i in range(b): for j in range(w): if img[i][j] > 0.0:", "an image with {0} rows and {1} columns'.format(b, w) print msg x =", "the respective axis). ======= ================================================================ *adm* translation ======= ================================================================ ``X-p`` send 1 single", "range(w): if img[i][j] > 0.0: nnotprints += 1 else: nprints += 1 assert", "{dir} {dir_channel} servo # set direction {off} {step_channel} servo {{delay}} delay {on} {step_channel}", "are at HOME position. while True: print 'Printing across the row {0}'.format(y) while", "----- This function sets the following global names: **img** : array of booleans", "(moves the tool up).''' STEPPER_CHANNELS_TARGET_ON = 6800 '''Target value in units of quarter-:math:`\\\\mu", "<EMAIL> '''Numerical controller for the printer73x system. **printerc** is an interactive command line", "the MM12 command port. Parameters ---------- commandport_id : str or int Serial device", "{ 'subroutine_id' : 9, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_on', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['on']*4) }, } '''Structure", "send :math:`n` pulses for negative translation across :math:`Y`. ``Y+P`` send :math:`n` pulses for", "except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' def print_image_better_better(confirm=False): '''Automatically print", "every element of the row from :math:`a_{0,0}` to :math:`a_{0,w-1}` then moves to the", "= get_subroutine_key_by_id(i) subroutine_body = MM12_SUBROUTINES[subroutine_key]['subroutine_body'] if 'Z' not in subroutine_key: subroutine_body = subroutine_body.format(delay=delay)", "*command port* ``{1}``'.format(PN, sp.port) msg = '``{0}`` is now connected to ``printerm`` through", "w - 1: translate('Z-') break translate('X+P', confirm) x += 1 if y ==", "without color. for i in range(b): for j in range(w): if img[i][j] >", "of the row from :math:`a_{0,0}` to :math:`a_{0,w-1}` then moves to the next row", "IPython import numpy as np # remove import matplotlib.image as mpimg import matplotlib.pyplot", "script subroutine that drives the servo motor.''' MM12_SCRIPT_INIT = '''\\ {{servo_acceleration}} {servo_channel} acceleration", "'Z+', 'o' : 'Z-', } getch = Getch() while True: ch = getch()", "as **printer73x**. __version__ = '0.09' # GLOBAL CONSTANT names. *if main* section at", ": { 'subroutine_id' : 3, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='x_pos_pixel', dir=MM12_AXES_CHANNELS['X']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'],", "'dir_positive' : STEPPER_CHANNELS_TARGET_OFF, 'dir_negative' : STEPPER_CHANNELS_TARGET_ON, 'step_channel': 1, }, 'Y' : { 'dir_channel'", "channels for the servo and stepper motors outputs.''' SUB_STEPPER_PIXEL_TEMPLATE = '''sub {name} {{{{ntransitions}}}}", "True: ch = getch() if ch not in keys2translation.keys(): break while mm12_script_status() ==", "correspond to the translations across the :math:`X`, :math:`Y` and :math:`Z` axis, and then", "serial.SerialException: pass return available def mm12_script_status(): '''Indicate whether the MM12 script is running", "'subroutine_id' : 5, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_pos_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), },", "y == b - 1: translate('Z-') break translate('Y+P', confirm) y += 1 #", "only perform translations across a single axis at a time. Parameters ---------- adm:", "{ 'X-p' : { 'subroutine_id' : 0, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_neg_pulse', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'],", "'X+P', 'j' : 'Y+P', 'k' : 'Y-P', 'i' : 'Z+', 'o' : 'Z-',", "on=STEPPER_CHANNELS_TARGET_ON), }, 'Y+p' : { 'subroutine_id' : 5, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_pos_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_positive'],", "step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y+p' : { 'subroutine_id' : 5, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='y_pos_pulse',", "(:math:`a_{1,w-1}`) and visits every element of the row from :math:`a_{1,w-1}` to :math:`a_{1,0}`, and", "report_position(x, y) if img[y][x] == 0.0: translate('Z+', confirm) if img[y][x-1] != 0.0: translate('Z-',", "print 'Processing the image...' # only total black and white, no grays. for", "*if main* section at bottom sets global names too. # ========================================================================== # ==========================================================================", "translation ======= ================================================================ ``X-p`` send 1 single pulse for negative translation across :math:`X`.", "= _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix:", "''' '''Template for the MM12 script subroutine that drives the servo motor.''' MM12_SCRIPT_INIT", "in the array representation. **w** : int Image's width, number of columns in", "print >>logf, 'Closing ``{0}`` *command port*'.format(sp.port) sp.close() except NameError: pass print >>logf, 'END'", "loaded on the MM12. Parameters ---------- fpath : str-like Path location where to", "In any position, if the corresponding pixel is black then the tool prints", "== \"__main__\": # program name from file name. PN = os.path.splitext(sys.argv[0])[0] logf =", "pulse for negative translation across :math:`X`. ``X+p`` send 1 single pulse for positive", "for key, value in MM12_SUBROUTINES.items(): if subroutine_id is value['subroutine_id']: return key for intarg", "and {1} columns'.format(b, w) print msg x = y = z = 0", "translate('Z-') break translate('Y+P', confirm) y += 1 # To the left. print 'Printing", "the printerm tool across the :math:`XY` plane. Parameters ---------- precise : boolean, optional", "when the script is stopped.''' # ========================================================================== # ========================================================================== # ========================================================================== class Getch:", "}, 'Z' : { 'channel' : 4, 'on' : SRV_SIGNAL_CHANNEL_TARGET_OFF, 'off' : SRV_SIGNAL_CHANNEL_TARGET_ON,", "import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch", "{1}'.format(y, x) def print_img_pixel(x, y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm) try: msg", "fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd,", "nprints += 1 assert (nnotprints + nprints) == npixels # If ``nprints ==", "sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd)", "opened *command port* ``{1}``'.format(PN, sp.port) msg = '``{0}`` is now connected to ``printerm``", "try: if img[y][x+1] != 0.0: translate('Z-', confirm) except IndexError as e: pass if", "# GLOBAL CONSTANT names. *if main* section at bottom sets global names too.", "the translations across the :math:`X`, :math:`Y` and :math:`Z` axis, and then printerc execute", "----- Directly copied from example from `pyserial <http://sourceforge.net/projects/pyserial/files/package>`_ project. ''' available = []", "has been printed' except KeyboardInterrupt: sp.flush() print 'Operation interrupted, flushing command port' def", "'subroutine_id' : 6, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format( name='y_neg_pixel', dir=MM12_AXES_CHANNELS['Y']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ),", "invert : boolean, optional Invert the image if ``True`` (default is ``False``). show", "s = serial.Serial(i) available.append( (i, s.portstr)) s.close() except serial.SerialException: pass return available def", "with and without color. for i in range(b): for j in range(w): if", "if __name__ == \"__main__\": # program name from file name. PN = os.path.splitext(sys.argv[0])[0]", "'dir_negative' : STEPPER_CHANNELS_TARGET_ON, 'step_channel': 1, }, 'Y' : { 'dir_channel' : 2, 'dir_positive'", "== b - 1: break translate('Y+P', confirm) y += 1 print 'Printing across", ":math:`X` or :math:`Y` axes.''' SRV_SIGNAL_CHANNEL_TARGET_OFF = 940 ''':math:`Z` axis servo motor pulse width", "SRV_SIGNAL_CHANNEL_TARGET_ON = 2175 SRV_SIGNAL_CHANNEL_TARGET_ON = 1580 ''':math:`Z` axis servo motor pulse width in", "'P' in subroutine_key: subroutine_body = subroutine_body.format(ntransitions=ntransitions) print >>f, subroutine_body def prepare_img(imgpath, invert=False, show=False):", "= { 'h' : 'X-p', 'l' : 'X+p', 'j' : 'Y+p', 'k' :", "== 0: break translate('X-P', confirm) x -= 1 print 'The image has been", "{step_channel} servo {{delay}} delay {on} {step_channel} servo {{delay}} delay 1 minus repeat quit", "step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'Y-p' : { 'subroutine_id' : 4, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format(", ": SRV_SIGNAL_CHANNEL_TARGET_ON, }, } '''Configuration of the MM12 channels for the servo and", "matplotlib.pyplot as plt import matplotlib.cm as cm # Same as **printer73x**. __version__ =", "imgpath, npixels, nprints) plt.close('all') if show: plt.imshow(img, cmap=cm.gray) plt.show() def connect_printerm(commandport_id): '''Connect printerc", "ms) (default is 100). ''' def get_subroutine_key_by_id(subroutine_id): for key, value in MM12_SUBROUTINES.items(): if", "sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch =", "= 0.0 else: img[i][j] = 1.0 if invert: print 'Inverting image...' for i", "step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON ), }, 'X+P' : { 'subroutine_id' : 3, 'subroutine_body' : SUB_STEPPER_PIXEL_TEMPLATE.format(", "loads in its memory the routines that correspond to the translations across the", "print 'Returning to a_{{0, 0}}'.format(y) while True: if y == 0: break translate('Y-P',", "across :math:`X`. ``Y-p`` send 1 single pulse for negative translation across :math:`Y`. ``Y+p``", "axis servo motor pulse width in units of quarter-:math:`\\\\mu s` that disables printing", "set direction begin dup while {off} {step_channel} servo {{delay}} delay {on} {step_channel} servo", "self.impl() class _GetchUnix: '''Unix implementation of class ``Getch``.''' def __init__(self): import tty, sys", "main* section at bottom sets global names too. # ========================================================================== # ========================================================================== LOGF", "from pprint import pprint import sys import os import atexit import gc import", "cmap=cm.gray) plt.show() def connect_printerm(commandport_id): '''Connect printerc with printerm through the MM12 command port.", "is now connected to ``printerm`` through ``{1}``'.format( PN, sp.port) for f in (logf,", "else: keys2translation = { 'h' : 'X-P', 'l' : 'X+P', 'j' : 'Y+P',", "mpimg import matplotlib.pyplot as plt import matplotlib.cm as cm # Same as **printer73x**.", ":math:`\\mathbf{A}` with the input image from a front perspective: #. :math:`a_{0,0}` corresponds to", "ch not in keys2translation.keys(): break while mm12_script_status() == MM12_SCRIPT_RUNNING: pass translate(keys2translation[ch], confirm=False) def", "'END' logf.close() print '\\nThanks for using ``printerc``!\\n' # Invoke the garbage collector. gc.collect()", "#if 'Z' in adm: #time.sleep(0.1) def build_mm12_script(fpath, ntransitions=TRANSITIONS_PER_PIXEL, delay=1, servo_acceleration=0, servo_speed=100): '''Build a", "assert sp.write(str2write) == 2 #if 'Z' in adm: #time.sleep(0.1) def build_mm12_script(fpath, ntransitions=TRANSITIONS_PER_PIXEL, delay=1,", "================================================================ confirm: boolean, optional If ``True``, the user must confirm the translation by", "def print_img_pixel(x, y, confirm=False): if img[y][x] == 0.0: print_pixel(confirm) try: msg = 'Preparing", "= 0 # We are at HOME position. while True: # To the", "# To the left. print 'Printing across the row {0}'.format(y) while True: report_position(x,", "rows in the array representation. **w** : int Image's width, number of columns", "channels low.''' MM12_AXES_CHANNELS = { 'X' : { 'dir_channel' : 0, 'dir_positive' :", "and identifies the MM12 script subroutines.''' MM12_SCRIPT_RUNNING = '\\x00' '''Byte value that the", "pressing Enter (default is ``False``). ''' # Start until script is not running.", "= serial.Serial(i) available.append( (i, s.portstr)) s.close() except serial.SerialException: pass return available def mm12_script_status():", "keys2translation.keys(): break while mm12_script_status() == MM12_SCRIPT_RUNNING: pass translate(keys2translation[ch], confirm=False) def print_pixel(confirm=False): if confirm:", "= 'log.rst' '''Path to the log file.''' INTRO_MSG = '''\\ **printerc** Welcome! '''", "in order to produce the trajectory of the tool printing the image. '''", "subroutine_key: subroutine_body = subroutine_body.format(delay=delay) if 'P' in subroutine_key: subroutine_body = subroutine_body.format(ntransitions=ntransitions) print >>f,", "name='y_pos_pulse', dir=MM12_AXES_CHANNELS['Y']['dir_positive'], dir_channel=MM12_AXES_CHANNELS['Y']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['Y']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'Y-P' : { 'subroutine_id' : 6,", "for i in range(256): try: s = serial.Serial(i) available.append( (i, s.portstr)) s.close() except", "def get_subroutine_key_by_id(subroutine_id): for key, value in MM12_SUBROUTINES.items(): if subroutine_id is value['subroutine_id']: return key", "print_pixel(confirm) try: msg = 'Preparing to print an image with {0} rows and", "== 1 return sp.read(1) def translate(adm, confirm=False): '''Translate the printerm tool across the", "do on exit.''' try: print >>logf, 'Closing ``{0}`` *command port*'.format(sp.port) sp.close() except NameError:", "SRV_SIGNAL_CHANNEL_TARGET_ON = 1580 ''':math:`Z` axis servo motor pulse width in units of quarter-:math:`\\\\mu", "the following global names: **img** : array of booleans 2-d array representation of", "translate('Z-', confirm) if x == 0: translate('Z-') break translate('X-P', confirm) x -= 1", "'Z-' : { 'subroutine_id' : 8, 'subroutine_body' : SUB_SERVO_TEMPLATE.format( name='z_position_off', channel=MM12_AXES_CHANNELS['Z']['channel'], position=MM12_AXES_CHANNELS['Z']['off']*4) },", "confirm: raw_input() translate('Z+', confirm=False) translate('Z-', confirm=False) def print_image(confirm=False): def report_position(x, y): print 'At", "motor needs to translate 1 pixel across the :math:`X` or :math:`Y` axes.''' TRANSITIONS_PER_PIXEL", "MM12 channels for the servo and stepper motors outputs.''' SUB_STEPPER_PIXEL_TEMPLATE = '''sub {name}", "there are no more rows to visit. In any position, if the corresponding", "'Y+p', 'k' : 'Y-p', 'i' : 'Z+', 'o' : 'Z-', } else: keys2translation", "in range(len( MM12_SUBROUTINES)): subroutine_key = get_subroutine_key_by_id(i) subroutine_body = MM12_SUBROUTINES[subroutine_key]['subroutine_body'] if 'Z' not in", "in the subroutines that perform translation through the stepper motors (default is 1).", "2-d array representation of the image. **b** : int Image's height, number of", "the input image. Parameters ---------- confirm : boolean, optional Wait for confirmation before", "the servo motor.''' MM12_SCRIPT_INIT = '''\\ {{servo_acceleration}} {servo_channel} acceleration {{servo_speed}} {servo_channel} speed '''.format(servo_channel=MM12_AXES_CHANNELS['Z']['channel'])", "``nprints == 0`` then no pixel will be printed. assert nprints > 0", "color_in_this_row(row): for pixel in row: if pixel == 0.0: return True return False", "---------- confirm : boolean, optional Wait for confirmation before any translation (default is", "coding=utf-8 # Author: <NAME> # Contact: <EMAIL> '''Numerical controller for the printer73x system.", "in adm: #time.sleep(0.1) def build_mm12_script(fpath, ntransitions=TRANSITIONS_PER_PIXEL, delay=1, servo_acceleration=0, servo_speed=100): '''Build a script to", "translation through the stepper motors (default is 1). servo_acceleration : int, optional Sets", "if 'P' in subroutine_key: subroutine_body = subroutine_body.format(ntransitions=ntransitions) print >>f, subroutine_body def prepare_img(imgpath, invert=False,", "= '\\x01' '''Byte value that the MM12 returns when the script is stopped.'''", "stepper channels low.''' MM12_AXES_CHANNELS = { 'X' : { 'dir_channel' : 0, 'dir_positive'", ": 0, 'subroutine_body' : SUB_STEPPER_PULSE_TEMPLATE.format( name='x_neg_pulse', dir=MM12_AXES_CHANNELS['X']['dir_negative'], dir_channel=MM12_AXES_CHANNELS['X']['dir_channel'], off=STEPPER_CHANNELS_TARGET_OFF, step_channel=MM12_AXES_CHANNELS['X']['step_channel'], on=STEPPER_CHANNELS_TARGET_ON), }, 'X+p'", "report_position(x, y) print_img_pixel(x, y, confirm) if x == 0: break translate('X-P', confirm) x", "w = img.shape npixels = b * w nprints = nnotprints = 0", "pass translate(keys2translation[ch], confirm=False) def print_pixel(confirm=False): if confirm: raw_input() translate('Z+', confirm=False) translate('Z-', confirm=False) def", "boolean, optional Wait for confirmation before any translation (default is ``False``). Notes -----", "running.''' MM12_SCRIPT_STOPPED = '\\x01' '''Byte value that the MM12 returns when the script", "translate('X+P', confirm) x += 1 if y == b - 1: translate('Z-') break", ":math:`X`. ``X-P`` send :math:`n` pulses for negative translation across :math:`X`. ``X+P`` send :math:`n`", ":math:`Y` axes.''' TRANSITIONS_PER_PIXEL = STEPS_PER_PIXEL * TRANSITIONS_PER_STEP '''Number of low-to-high transitions the stepper", "execute these routines in order to produce the trajectory of the tool printing", "motor in units of pixels,''' SUB_STEPPER_PULSE_TEMPLATE = '''sub {name} {dir} {dir_channel} servo #", "nnotprints = 0 assert (b > 0) and (w > 0) print 'Processing", "a front perspective: #. :math:`a_{0,0}` corresponds to the upper left corner of the", "the stepper motors need to translate 1 pixel across the :math:`X` or :math:`Y`", ":math:`X`. ``Y-p`` send 1 single pulse for negative translation across :math:`Y`. ``Y+p`` send", "MM12 script subroutine that drives the servo motor.''' MM12_SCRIPT_INIT = '''\\ {{servo_acceleration}} {servo_channel}", ":math:`a_{0,0}` to :math:`a_{0,w-1}` then moves to the next row (:math:`a_{1,w-1}`) and visits every", "img[i][j] > 0.0: img[i][j] = 0.0 else: img[i][j] = 1.0 # Check for", "image with {0} rows and {1} columns'.format(b, w) print msg x = y", "from :math:`a_{0,0}` to :math:`a_{0,w-1}` then moves to the next row (:math:`a_{1,w-1}`) and visits", "= [] for i in range(256): try: s = serial.Serial(i) available.append( (i, s.portstr))" ]
[ "from the initial lr set in the optimizer to 0, after a warmup", "def lr_lambda(current_step: int): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) return", "last_epoch=-1): \"\"\" Copied and **modified** from: https://github.com/huggingface/transformers Create a schedule with a learning", "augment_note_matrix(nmat, length, shift): \"\"\"Pitch shift a note matrix in R_base format.\"\"\" aug_nmat =", "optimizer: The optimizer for which to schedule the learning rate. :param num_warmup_steps: The", "which it increases linearly from 0 to the initial lr set in the", "note matrix in R_base format.\"\"\" aug_nmat = nmat.copy() aug_nmat[0: length, 1] += shift", "to the initial lr set in the optimizer. :param optimizer: The optimizer for", "= initial lr * final_lr_factor :param last_epoch: the index of the last epoch", "for which to schedule the learning rate. :param num_warmup_steps: The number of steps", "the index of the last epoch when resuming training. (defaults to -1) :return:", "from 0 to the initial lr set in the optimizer. :param optimizer: The", "resuming training. (defaults to -1) :return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. \"\"\" def", "/ float(max(1, num_training_steps - num_warmup_steps)) ) return LambdaLR(optimizer, lr_lambda, last_epoch) def augment_note_matrix(nmat, length,", "- num_warmup_steps)) ) return LambdaLR(optimizer, lr_lambda, last_epoch) def augment_note_matrix(nmat, length, shift): \"\"\"Pitch shift", "initial lr set in the optimizer to 0, after a warmup period during", ":return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. \"\"\" def lr_lambda(current_step: int): if current_step <", "< num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) return max( final_lr_factor, float(num_training_steps - current_step)", "max( final_lr_factor, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)) ) return LambdaLR(optimizer,", "lr set in the optimizer. :param optimizer: The optimizer for which to schedule", "steps for the warmup phase. :param num_training_steps: The total number of training steps.", "initial lr set in the optimizer. :param optimizer: The optimizer for which to", "steps. :param final_lr_factor: Final lr = initial lr * final_lr_factor :param last_epoch: the", "a learning rate that decreases linearly from the initial lr set in the", "decreases linearly from the initial lr set in the optimizer to 0, after", "from torch.optim.lr_scheduler import LambdaLR def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, final_lr_factor, last_epoch=-1): \"\"\" Copied and", "which to schedule the learning rate. :param num_warmup_steps: The number of steps for", "linearly from the initial lr set in the optimizer to 0, after a", "warmup phase. :param num_training_steps: The total number of training steps. :param final_lr_factor: Final", "lr_lambda(current_step: int): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) return max(", "num_training_steps: The total number of training steps. :param final_lr_factor: Final lr = initial", "-1) :return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. \"\"\" def lr_lambda(current_step: int): if current_step", "lr set in the optimizer to 0, after a warmup period during which", "num_training_steps, final_lr_factor, last_epoch=-1): \"\"\" Copied and **modified** from: https://github.com/huggingface/transformers Create a schedule with", "optimizer for which to schedule the learning rate. :param num_warmup_steps: The number of", "training steps. :param final_lr_factor: Final lr = initial lr * final_lr_factor :param last_epoch:", "number of steps for the warmup phase. :param num_training_steps: The total number of", "a schedule with a learning rate that decreases linearly from the initial lr", "initial lr * final_lr_factor :param last_epoch: the index of the last epoch when", "lr * final_lr_factor :param last_epoch: the index of the last epoch when resuming", "length, shift): \"\"\"Pitch shift a note matrix in R_base format.\"\"\" aug_nmat = nmat.copy()", "num_warmup_steps: The number of steps for the warmup phase. :param num_training_steps: The total", "/ float(max(1, num_warmup_steps)) return max( final_lr_factor, float(num_training_steps - current_step) / float(max(1, num_training_steps -", "to -1) :return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. \"\"\" def lr_lambda(current_step: int): if", "the appropriate schedule. \"\"\" def lr_lambda(current_step: int): if current_step < num_warmup_steps: return float(current_step)", "it increases linearly from 0 to the initial lr set in the optimizer.", "final_lr_factor: Final lr = initial lr * final_lr_factor :param last_epoch: the index of", "of steps for the warmup phase. :param num_training_steps: The total number of training", "The optimizer for which to schedule the learning rate. :param num_warmup_steps: The number", "num_warmup_steps)) ) return LambdaLR(optimizer, lr_lambda, last_epoch) def augment_note_matrix(nmat, length, shift): \"\"\"Pitch shift a", "num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) return max( final_lr_factor, float(num_training_steps - current_step) /", "https://github.com/huggingface/transformers Create a schedule with a learning rate that decreases linearly from the", "with a learning rate that decreases linearly from the initial lr set in", "learning rate that decreases linearly from the initial lr set in the optimizer", "number of training steps. :param final_lr_factor: Final lr = initial lr * final_lr_factor", "period during which it increases linearly from 0 to the initial lr set", "torch.optim.lr_scheduler import LambdaLR def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, final_lr_factor, last_epoch=-1): \"\"\" Copied and **modified**", "schedule. \"\"\" def lr_lambda(current_step: int): if current_step < num_warmup_steps: return float(current_step) / float(max(1,", ":param optimizer: The optimizer for which to schedule the learning rate. :param num_warmup_steps:", "current_step) / float(max(1, num_training_steps - num_warmup_steps)) ) return LambdaLR(optimizer, lr_lambda, last_epoch) def augment_note_matrix(nmat,", "LambdaLR def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, final_lr_factor, last_epoch=-1): \"\"\" Copied and **modified** from: https://github.com/huggingface/transformers", "learning rate. :param num_warmup_steps: The number of steps for the warmup phase. :param", "for the warmup phase. :param num_training_steps: The total number of training steps. :param", "set in the optimizer to 0, after a warmup period during which it", "the optimizer to 0, after a warmup period during which it increases linearly", "rate. :param num_warmup_steps: The number of steps for the warmup phase. :param num_training_steps:", "\"\"\"Pitch shift a note matrix in R_base format.\"\"\" aug_nmat = nmat.copy() aug_nmat[0: length,", "in R_base format.\"\"\" aug_nmat = nmat.copy() aug_nmat[0: length, 1] += shift return aug_nmat", "<reponame>wiaderwek/musebert<filename>utils.py from torch.optim.lr_scheduler import LambdaLR def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, final_lr_factor, last_epoch=-1): \"\"\" Copied", "float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)) ) return LambdaLR(optimizer, lr_lambda, last_epoch)", "\"\"\" Copied and **modified** from: https://github.com/huggingface/transformers Create a schedule with a learning rate", "num_warmup_steps, num_training_steps, final_lr_factor, last_epoch=-1): \"\"\" Copied and **modified** from: https://github.com/huggingface/transformers Create a schedule", "increases linearly from 0 to the initial lr set in the optimizer. :param", "(defaults to -1) :return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. \"\"\" def lr_lambda(current_step: int):", "and **modified** from: https://github.com/huggingface/transformers Create a schedule with a learning rate that decreases", "a warmup period during which it increases linearly from 0 to the initial", "LambdaLR(optimizer, lr_lambda, last_epoch) def augment_note_matrix(nmat, length, shift): \"\"\"Pitch shift a note matrix in", "final_lr_factor, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)) ) return LambdaLR(optimizer, lr_lambda,", "final_lr_factor, last_epoch=-1): \"\"\" Copied and **modified** from: https://github.com/huggingface/transformers Create a schedule with a", "from: https://github.com/huggingface/transformers Create a schedule with a learning rate that decreases linearly from", "0 to the initial lr set in the optimizer. :param optimizer: The optimizer", "set in the optimizer. :param optimizer: The optimizer for which to schedule the", "epoch when resuming training. (defaults to -1) :return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.", "return LambdaLR(optimizer, lr_lambda, last_epoch) def augment_note_matrix(nmat, length, shift): \"\"\"Pitch shift a note matrix", "the initial lr set in the optimizer to 0, after a warmup period", "last epoch when resuming training. (defaults to -1) :return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate", "optimizer. :param optimizer: The optimizer for which to schedule the learning rate. :param", "final_lr_factor :param last_epoch: the index of the last epoch when resuming training. (defaults", "* final_lr_factor :param last_epoch: the index of the last epoch when resuming training.", ") return LambdaLR(optimizer, lr_lambda, last_epoch) def augment_note_matrix(nmat, length, shift): \"\"\"Pitch shift a note", "with the appropriate schedule. \"\"\" def lr_lambda(current_step: int): if current_step < num_warmup_steps: return", "schedule the learning rate. :param num_warmup_steps: The number of steps for the warmup", "optimizer to 0, after a warmup period during which it increases linearly from", "rate that decreases linearly from the initial lr set in the optimizer to", "float(current_step) / float(max(1, num_warmup_steps)) return max( final_lr_factor, float(num_training_steps - current_step) / float(max(1, num_training_steps", ":param final_lr_factor: Final lr = initial lr * final_lr_factor :param last_epoch: the index", "float(max(1, num_training_steps - num_warmup_steps)) ) return LambdaLR(optimizer, lr_lambda, last_epoch) def augment_note_matrix(nmat, length, shift):", "warmup period during which it increases linearly from 0 to the initial lr", "`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. \"\"\" def lr_lambda(current_step: int): if current_step < num_warmup_steps:", "the warmup phase. :param num_training_steps: The total number of training steps. :param final_lr_factor:", "float(max(1, num_warmup_steps)) return max( final_lr_factor, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps))", "return max( final_lr_factor, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)) ) return", "total number of training steps. :param final_lr_factor: Final lr = initial lr *", "the initial lr set in the optimizer. :param optimizer: The optimizer for which", "num_training_steps - num_warmup_steps)) ) return LambdaLR(optimizer, lr_lambda, last_epoch) def augment_note_matrix(nmat, length, shift): \"\"\"Pitch", "schedule with a learning rate that decreases linearly from the initial lr set", "in the optimizer. :param optimizer: The optimizer for which to schedule the learning", "of training steps. :param final_lr_factor: Final lr = initial lr * final_lr_factor :param", "return float(current_step) / float(max(1, num_warmup_steps)) return max( final_lr_factor, float(num_training_steps - current_step) / float(max(1,", "The number of steps for the warmup phase. :param num_training_steps: The total number", "def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, final_lr_factor, last_epoch=-1): \"\"\" Copied and **modified** from: https://github.com/huggingface/transformers Create", "Copied and **modified** from: https://github.com/huggingface/transformers Create a schedule with a learning rate that", "last_epoch: the index of the last epoch when resuming training. (defaults to -1)", "Create a schedule with a learning rate that decreases linearly from the initial", "The total number of training steps. :param final_lr_factor: Final lr = initial lr", ":param last_epoch: the index of the last epoch when resuming training. (defaults to", "during which it increases linearly from 0 to the initial lr set in", ":param num_warmup_steps: The number of steps for the warmup phase. :param num_training_steps: The", "- current_step) / float(max(1, num_training_steps - num_warmup_steps)) ) return LambdaLR(optimizer, lr_lambda, last_epoch) def", "the last epoch when resuming training. (defaults to -1) :return: `torch.optim.lr_scheduler.LambdaLR` with the", "appropriate schedule. \"\"\" def lr_lambda(current_step: int): if current_step < num_warmup_steps: return float(current_step) /", "lr_lambda, last_epoch) def augment_note_matrix(nmat, length, shift): \"\"\"Pitch shift a note matrix in R_base", "after a warmup period during which it increases linearly from 0 to the", "lr = initial lr * final_lr_factor :param last_epoch: the index of the last", "**modified** from: https://github.com/huggingface/transformers Create a schedule with a learning rate that decreases linearly", "to schedule the learning rate. :param num_warmup_steps: The number of steps for the", "linearly from 0 to the initial lr set in the optimizer. :param optimizer:", "current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) return max( final_lr_factor, float(num_training_steps -", "last_epoch) def augment_note_matrix(nmat, length, shift): \"\"\"Pitch shift a note matrix in R_base format.\"\"\"", "matrix in R_base format.\"\"\" aug_nmat = nmat.copy() aug_nmat[0: length, 1] += shift return", "int): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) return max( final_lr_factor,", "Final lr = initial lr * final_lr_factor :param last_epoch: the index of the", "the learning rate. :param num_warmup_steps: The number of steps for the warmup phase.", "num_warmup_steps)) return max( final_lr_factor, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)) )", "the optimizer. :param optimizer: The optimizer for which to schedule the learning rate.", "def augment_note_matrix(nmat, length, shift): \"\"\"Pitch shift a note matrix in R_base format.\"\"\" aug_nmat", "in the optimizer to 0, after a warmup period during which it increases", "get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, final_lr_factor, last_epoch=-1): \"\"\" Copied and **modified** from: https://github.com/huggingface/transformers Create a", "shift a note matrix in R_base format.\"\"\" aug_nmat = nmat.copy() aug_nmat[0: length, 1]", "to 0, after a warmup period during which it increases linearly from 0", "of the last epoch when resuming training. (defaults to -1) :return: `torch.optim.lr_scheduler.LambdaLR` with", "\"\"\" def lr_lambda(current_step: int): if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps))", "a note matrix in R_base format.\"\"\" aug_nmat = nmat.copy() aug_nmat[0: length, 1] +=", "phase. :param num_training_steps: The total number of training steps. :param final_lr_factor: Final lr", "import LambdaLR def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, final_lr_factor, last_epoch=-1): \"\"\" Copied and **modified** from:", "index of the last epoch when resuming training. (defaults to -1) :return: `torch.optim.lr_scheduler.LambdaLR`", "when resuming training. (defaults to -1) :return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. \"\"\"", ":param num_training_steps: The total number of training steps. :param final_lr_factor: Final lr =", "shift): \"\"\"Pitch shift a note matrix in R_base format.\"\"\" aug_nmat = nmat.copy() aug_nmat[0:", "if current_step < num_warmup_steps: return float(current_step) / float(max(1, num_warmup_steps)) return max( final_lr_factor, float(num_training_steps", "training. (defaults to -1) :return: `torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule. \"\"\" def lr_lambda(current_step:", "0, after a warmup period during which it increases linearly from 0 to", "that decreases linearly from the initial lr set in the optimizer to 0," ]
[ ") coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_file_annotation_relative_endpoints_within_clip(self): clip_annotation =", "relative to the file. end_seconds: Ending of the test FileAnnotation relative to the", "examplegen.Annotation.parse_csv_row({'label': 'Mn'}) def test_round_trip_file_annotation(self): annotation = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=2.1), end=datetime.timedelta(seconds=3.1), ) coder =", "KIND, either express or implied. # See the License for the specific language", "don't overlap. \"\"\" file_start_utc = datetime.datetime(2012, 2, 3, 11, 45, 20, tzinfo=tz.UTC) start_relative_to_file", "Unless required by applicable law or agreed to in writing, software # distributed", "relative to a fixture clip. This is a modification of the FileAnnotation version", "test_file_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5, 2.5)) def test_file_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42, 45)) def test_file_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(19.5, 22.1)", "file. end_seconds: Ending of the test FileAnnotation relative to the file. Returns: Annotation", "clip. This is a modification of the FileAnnotation version to convert identical offset", "45, 20, tzinfo=tz.UTC) start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2,", "clip_annotation = relative_endpoints_to_utc_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) if __name__ == '__main__': unittest.main()", "label='Mn', begin=datetime.datetime(2008, 5, 6, 11, 24, 41, 268000, tzinfo=tz.UTC), end=datetime.datetime(2008, 5, 6, 11,", "6, 11, 24, 42, 472000, tzinfo=tz.UTC), ) self.assertEqual(expected, annotation) def test_file_endpoints_override_utc_endpoints(self): annotation =", "11:24:42.472000', }) expected = examplegen.UTCAnnotation( label='Mn', begin=datetime.datetime(2008, 5, 6, 11, 24, 41, 268000,", "label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_utc(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn',", "end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_missing_fields(self): with self.assertRaises(ValueError): examplegen.Annotation.parse_csv_row({'label': 'Mn'}) def test_round_trip_file_annotation(self): annotation", "test UTCAnnotation relative to the file. end_seconds: Ending of the test UTCAnnotation relative", "test FileAnnotation relative to the file. end_seconds: Ending of the test FileAnnotation relative", "the specific language governing permissions and # limitations under the License. import datetime", "this file except in compliance with the License. # You may obtain a", "Beginning of the test FileAnnotation relative to the file. end_seconds: Ending of the", "}) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_utc(self): annotation", "# Copyright 2022 Google LLC # # Licensed under the Apache License, Version", "governing permissions and # limitations under the License. import datetime from typing import", "UTCAnnotation relative to the file. Returns: Annotation over the restriction of the given", "end_seconds: Ending of the test UTCAnnotation relative to the file. Returns: Annotation over", "the file. Returns: Annotation over the restriction of the given time interval to", "self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42, 45)) def test_file_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) def", "label='Mn', begin=datetime.timedelta(seconds=2.1), end=datetime.timedelta(seconds=3.1), ) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def", "ANY KIND, either express or implied. # See the License for the specific", "def test_utc_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42, 45)) def test_utc_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1),", "test_utc_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42, 45)) def test_utc_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end)", "def test_round_trip_utc_annotation(self): begin = datetime.datetime(2012, 2, 3, 11, 45, 15, tzinfo=tz.UTC) end =", "start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=file_start_utc +", "3, 11, 45, 20, tzinfo=tz.UTC) start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000,", "hard-coded fixture file_start_utc. The fixture clip covers the time interval [10s, 20s] relative", "clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=file_start_utc + start_relative_to_file, ) annotation", "test_utc_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_utc_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5, 2.5))", "= examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=file_start_utc + start_relative_to_file, ) annotation =", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "arguments (relative to the start of the file) to the corresponding UTC times,", "return annotation.make_relative(clip_metadata) def relative_endpoints_to_utc_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing UTCAnnotations", "= datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=file_start_utc + start_relative_to_file,", "fixture clip. This is a modification of the FileAnnotation version to convert identical", "(relative to the start of the file) to the corresponding UTC times, based", "examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.UTCAnnotation(", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "don't overlap. \"\"\" start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2,", "tzinfo=tz.UTC) end = begin + datetime.timedelta(seconds=1.7) annotation = examplegen.UTCAnnotation(label='Mn', begin=begin, end=end) coder =", "OF ANY KIND, either express or implied. # See the License for the", "of the test FileAnnotation relative to the file. end_seconds: Ending of the test", "'label': 'Mn', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.UTCAnnotation( label='Mn',", "2.5)) def test_utc_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42, 45)) def test_utc_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin)", "Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0", "= examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06", "file_start_utc = datetime.datetime(2012, 2, 3, 11, 45, 20, tzinfo=tz.UTC) start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata", "encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_file_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin)", "examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_utc(self): annotation = examplegen.Annotation.parse_csv_row({ 'label':", "float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing UTCAnnotations relative to a fixture clip.", "the test FileAnnotation relative to the file. end_seconds: Ending of the test FileAnnotation", "to a fixture clip. This is a modification of the FileAnnotation version to", "datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) class TestAnnotations(unittest.TestCase): def test_parse_annotation_rel_file(self): annotation = examplegen.Annotation.parse_csv_row({ 'label':", "label='Oo', ) return annotation.make_relative(clip_metadata) class TestAnnotations(unittest.TestCase): def test_parse_annotation_rel_file(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn',", "'Mn', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.UTCAnnotation( label='Mn', begin=datetime.datetime(2008,", "float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing FileAnnotations relative to a fixture clip. The fixture", "to the corresponding UTC times, based on a hard-coded fixture file_start_utc. The fixture", "start_utc=file_start_utc + start_relative_to_file, ) annotation = examplegen.UTCAnnotation( begin=file_start_utc + datetime.timedelta(seconds=begin_seconds), end=file_start_utc + datetime.timedelta(seconds=end_seconds),", "end=datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) def relative_endpoints_to_utc_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]:", "'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8),", "'label': 'Mn', 'begin': '1.2', 'end': '1.8', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8),", "coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_utc_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end)", "def test_file_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) def test_round_trip_utc_annotation(self): begin", "LLC # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc':", "limitations under the License. import datetime from typing import Optional, Tuple import unittest", "clip_annotation.end) def test_file_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5, 2.5)) def test_file_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42, 45)) def test_file_annotation_relative_endpoints_overlap_begin(self): clip_annotation =", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "5, 6, 11, 24, 42, 472000, tzinfo=tz.UTC), ) self.assertEqual(expected, annotation) def test_file_endpoints_override_utc_endpoints(self): annotation", "'end': '1.8', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def", "fixture file_start_utc. The fixture clip covers the time interval [10s, 20s] relative to", "= beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_file_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(22, 23.2)", ") self.assertEqual(expected, annotation) def test_file_endpoints_override_utc_endpoints(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end':", "45)) def test_utc_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) if __name__", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "'1.8', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2),", "self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_utc_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5, 2.5)) def test_utc_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42, 45)) def", "permissions and # limitations under the License. import datetime from typing import Optional,", "\"\"\" file_start_utc = datetime.datetime(2012, 2, 3, 11, 45, 20, tzinfo=tz.UTC) start_relative_to_file = datetime.timedelta(seconds=20)", "'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation)", "restriction of the given time interval to the fixture clip or None if", "to the fixture clip or None if they don't overlap. \"\"\" start_relative_to_file =", "clip. The fixture clip covers the time interval [10s, 20s] relative to the", "'Mn', 'begin': '1.2', 'end': '1.8', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected", ") self.assertEqual(expected, annotation) def test_parse_annotation_missing_fields(self): with self.assertRaises(ValueError): examplegen.Annotation.parse_csv_row({'label': 'Mn'}) def test_round_trip_file_annotation(self): annotation =", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=None, ) annotation = examplegen.FileAnnotation( begin=datetime.timedelta(seconds=begin_seconds), end=datetime.timedelta(seconds=end_seconds), label='Oo', ) return", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "modification of the FileAnnotation version to convert identical offset arguments (relative to the", "annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "the given time interval to the fixture clip or None if they don't", "datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=file_start_utc + start_relative_to_file, )", "45)) def test_file_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) def test_round_trip_utc_annotation(self):", "examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000',", "required by applicable law or agreed to in writing, software # distributed under", "of the given time interval to the fixture clip or None if they", "'begin': '1.2', 'end': '1.8', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected =", "applicable law or agreed to in writing, software # distributed under the License", "= examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_missing_fields(self): with self.assertRaises(ValueError): examplegen.Annotation.parse_csv_row({'label':", "45, 15, tzinfo=tz.UTC) end = begin + datetime.timedelta(seconds=1.7) annotation = examplegen.UTCAnnotation(label='Mn', begin=begin, end=end)", "}) expected = examplegen.UTCAnnotation( label='Mn', begin=datetime.datetime(2008, 5, 6, 11, 24, 41, 268000, tzinfo=tz.UTC),", "test_parse_annotation_rel_file(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8', }) expected =", "fixture clip or None if they don't overlap. \"\"\" file_start_utc = datetime.datetime(2012, 2,", "or agreed to in writing, software # distributed under the License is distributed", "label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_missing_fields(self): with self.assertRaises(ValueError): examplegen.Annotation.parse_csv_row({'label': 'Mn'}) def", "based on a hard-coded fixture file_start_utc. The fixture clip covers the time interval", "= datetime.datetime(2012, 2, 3, 11, 45, 20, tzinfo=tz.UTC) start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata =", "'2008-05-06 11:24:42.472000', }) expected = examplegen.UTCAnnotation( label='Mn', begin=datetime.datetime(2008, 5, 6, 11, 24, 41,", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "def test_file_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_file_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5,", "index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=file_start_utc + start_relative_to_file, ) annotation = examplegen.UTCAnnotation( begin=file_start_utc + datetime.timedelta(seconds=begin_seconds), end=file_start_utc", ") return annotation.make_relative(clip_metadata) def relative_endpoints_to_utc_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing", "to the file. Returns: Annotation over the restriction of the given time interval", "start of the file) to the corresponding UTC times, based on a hard-coded", "datetime from typing import Optional, Tuple import unittest import apache_beam as beam from", "to a fixture clip. The fixture clip covers the time interval [10s, 20s]", "test UTCAnnotation relative to the file. Returns: Annotation over the restriction of the", "None if they don't overlap. \"\"\" start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav',", "'1.2', 'end': '1.8', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation)", "tzinfo=tz.UTC) start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=file_start_utc", "begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing FileAnnotations relative to a fixture", "examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=file_start_utc + start_relative_to_file, ) annotation = examplegen.UTCAnnotation(", "the start of the file) to the corresponding UTC times, based on a", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "convert identical offset arguments (relative to the start of the file) to the", "writing, software # distributed under the License is distributed on an \"AS IS\"", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_file_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5, 2.5)) def test_file_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42, 45))", "def test_file_endpoints_override_utc_endpoints(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8', 'begin_utc': '2008-05-06", "License. # You may obtain a copy of the License at # #", "-> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing FileAnnotations relative to a fixture clip. The fixture clip", "def test_utc_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5, 2.5)) def test_utc_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42, 45)) def test_utc_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(19.5,", "annotation.make_relative(clip_metadata) class TestAnnotations(unittest.TestCase): def test_parse_annotation_rel_file(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end':", "= relative_endpoints_to_utc_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_utc_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5, 2.5)) def test_utc_annotation_relative_endpoints_after_clip(self):", "filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=None, ) annotation = examplegen.FileAnnotation( begin=datetime.timedelta(seconds=begin_seconds), end=datetime.timedelta(seconds=end_seconds), label='Oo',", "test_file_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_file_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5, 2.5))", "self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42, 45)) def test_utc_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) if", "a fixture clip. This is a modification of the FileAnnotation version to convert", "compliance with the License. # You may obtain a copy of the License", "sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=file_start_utc + start_relative_to_file, ) annotation = examplegen.UTCAnnotation( begin=file_start_utc +", "the file) to the corresponding UTC times, based on a hard-coded fixture file_start_utc.", "end=file_start_utc + datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) class TestAnnotations(unittest.TestCase): def test_parse_annotation_rel_file(self): annotation =", "the fixture clip or None if they don't overlap. \"\"\" start_relative_to_file = datetime.timedelta(seconds=20)", "filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=file_start_utc + start_relative_to_file, ) annotation = examplegen.UTCAnnotation( begin=file_start_utc", "for the specific language governing permissions and # limitations under the License. import", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "datetime.timedelta(seconds=1.7) annotation = examplegen.UTCAnnotation(label='Mn', begin=begin, end=end) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation,", "TestAnnotations(unittest.TestCase): def test_parse_annotation_rel_file(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8', })", "examplegen.UTCAnnotation(label='Mn', begin=begin, end=end) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_utc_annotation_relative_endpoints_within_clip(self):", "on a hard-coded fixture file_start_utc. The fixture clip covers the time interval [10s,", "a hard-coded fixture file_start_utc. The fixture clip covers the time interval [10s, 20s]", "of the test FileAnnotation relative to the file. Returns: Annotation over the restriction", "5, 6, 11, 24, 41, 268000, tzinfo=tz.UTC), end=datetime.datetime(2008, 5, 6, 11, 24, 42,", "Args: begin_seconds: Beginning of the test UTCAnnotation relative to the file. end_seconds: Ending", "begin_seconds: Beginning of the test FileAnnotation relative to the file. end_seconds: Ending of", "test_parse_annotation_missing_fields(self): with self.assertRaises(ValueError): examplegen.Annotation.parse_csv_row({'label': 'Mn'}) def test_round_trip_file_annotation(self): annotation = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=2.1), end=datetime.timedelta(seconds=3.1),", "beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_file_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2),", "time interval to the fixture clip or None if they don't overlap. \"\"\"", "not use this file except in compliance with the License. # You may", "encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_utc_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin)", "datetime.datetime(2012, 2, 3, 11, 45, 20, tzinfo=tz.UTC) start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata(", "self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_utc_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5, 2.5)) def test_utc_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42, 45)) def test_utc_annotation_relative_endpoints_overlap_begin(self): clip_annotation", "UTCAnnotations relative to a fixture clip. This is a modification of the FileAnnotation", "start_relative_to_file, ) annotation = examplegen.UTCAnnotation( begin=file_start_utc + datetime.timedelta(seconds=begin_seconds), end=file_start_utc + datetime.timedelta(seconds=end_seconds), label='Oo', )", "[10s, 20s] relative to the file. Args: begin_seconds: Beginning of the test FileAnnotation", "License, Version 2.0 (the \"License\"); # you may not use this file except", "examplegen.FileAnnotation( begin=datetime.timedelta(seconds=begin_seconds), end=datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) def relative_endpoints_to_utc_annotation_fixture( begin_seconds: float, end_seconds: float)", "def test_utc_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) if __name__ ==", "is a modification of the FileAnnotation version to convert identical offset arguments (relative", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "overlap. \"\"\" start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file,", "end=end) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_utc_annotation_relative_endpoints_within_clip(self): clip_annotation =", "examplegen.UTCAnnotation( label='Mn', begin=datetime.datetime(2008, 5, 6, 11, 24, 41, 268000, tzinfo=tz.UTC), end=datetime.datetime(2008, 5, 6,", "annotation) def test_file_endpoints_override_utc_endpoints(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8', 'begin_utc':", "License. import datetime from typing import Optional, Tuple import unittest import apache_beam as", "interval to the fixture clip or None if they don't overlap. \"\"\" start_relative_to_file", "examplegen.UTCAnnotation( begin=file_start_utc + datetime.timedelta(seconds=begin_seconds), end=file_start_utc + datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) class TestAnnotations(unittest.TestCase):", "472000, tzinfo=tz.UTC), ) self.assertEqual(expected, annotation) def test_file_endpoints_override_utc_endpoints(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin':", "# you may not use this file except in compliance with the License.", "'end': '1.8', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.FileAnnotation( label='Mn',", "annotation.make_relative(clip_metadata) def relative_endpoints_to_utc_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing UTCAnnotations relative", "agreed to in writing, software # distributed under the License is distributed on", "'begin': '1.2', 'end': '1.8', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected,", "(the \"License\"); # you may not use this file except in compliance with", "22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) def test_round_trip_utc_annotation(self): begin = datetime.datetime(2012, 2, 3, 11,", "annotation = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=2.1), end=datetime.timedelta(seconds=3.1), ) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation)", "sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=None, ) annotation = examplegen.FileAnnotation( begin=datetime.timedelta(seconds=begin_seconds), end=datetime.timedelta(seconds=end_seconds), label='Oo', )", "return annotation.make_relative(clip_metadata) class TestAnnotations(unittest.TestCase): def test_parse_annotation_rel_file(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2',", "clip or None if they don't overlap. \"\"\" start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata =", "beam from dateutil import tz from multispecies_whale_detection import examplegen def relative_endpoints_to_file_annotation_fixture( begin_seconds: float,", "# Unless required by applicable law or agreed to in writing, software #", "by applicable law or agreed to in writing, software # distributed under the", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "file. end_seconds: Ending of the test UTCAnnotation relative to the file. Returns: Annotation", "if they don't overlap. \"\"\" file_start_utc = datetime.datetime(2012, 2, 3, 11, 45, 20,", "under the License. import datetime from typing import Optional, Tuple import unittest import", "Optional, Tuple import unittest import apache_beam as beam from dateutil import tz from", "expected = examplegen.UTCAnnotation( label='Mn', begin=datetime.datetime(2008, 5, 6, 11, 24, 41, 268000, tzinfo=tz.UTC), end=datetime.datetime(2008,", "begin=datetime.timedelta(seconds=2.1), end=datetime.timedelta(seconds=3.1), ) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_file_annotation_relative_endpoints_within_clip(self):", "self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5, 2.5)) def test_utc_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42, 45)) def test_utc_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0),", "relative_endpoints_to_utc_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_utc_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5, 2.5)) def test_utc_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42,", "relative_endpoints_to_file_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing FileAnnotations relative to a", "index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=None, ) annotation = examplegen.FileAnnotation( begin=datetime.timedelta(seconds=begin_seconds), end=datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata)", "relative_endpoints_to_utc_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing UTCAnnotations relative to a", "class TestAnnotations(unittest.TestCase): def test_parse_annotation_rel_file(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8',", "'label': 'Mn', 'begin': '1.2', 'end': '1.8', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', })", "file except in compliance with the License. # You may obtain a copy", "as beam from dateutil import tz from multispecies_whale_detection import examplegen def relative_endpoints_to_file_annotation_fixture( begin_seconds:", "-> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing UTCAnnotations relative to a fixture clip. This is a", "= examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_utc(self): annotation = examplegen.Annotation.parse_csv_row({", "coder.decode(encoded)) def test_file_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_file_annotation_relative_endpoints_before_clip(self):", "License for the specific language governing permissions and # limitations under the License.", "\"\"\"Template testing FileAnnotations relative to a fixture clip. The fixture clip covers the", "corresponding UTC times, based on a hard-coded fixture file_start_utc. The fixture clip covers", "= datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=None, ) annotation", "typing import Optional, Tuple import unittest import apache_beam as beam from dateutil import", ") self.assertEqual(expected, annotation) def test_parse_annotation_utc(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin_utc': '2008-05-06 11:24:41.268000',", "to in writing, software # distributed under the License is distributed on an", "= begin + datetime.timedelta(seconds=1.7) annotation = examplegen.UTCAnnotation(label='Mn', begin=begin, end=end) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded", "file. Args: begin_seconds: Beginning of the test UTCAnnotation relative to the file. end_seconds:", "implied. # See the License for the specific language governing permissions and #", "\"License\"); # you may not use this file except in compliance with the", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=file_start_utc + start_relative_to_file, ) annotation = examplegen.UTCAnnotation( begin=file_start_utc + datetime.timedelta(seconds=begin_seconds),", "11:24:42.472000', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_missing_fields(self):", "coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_file_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end)", "2, 3, 11, 45, 20, tzinfo=tz.UTC) start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav',", "self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5, 2.5)) def test_file_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42, 45)) def test_file_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0),", "unittest import apache_beam as beam from dateutil import tz from multispecies_whale_detection import examplegen", "from dateutil import tz from multispecies_whale_detection import examplegen def relative_endpoints_to_file_annotation_fixture( begin_seconds: float, end_seconds:", "or None if they don't overlap. \"\"\" file_start_utc = datetime.datetime(2012, 2, 3, 11,", "= examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=None, ) annotation = examplegen.FileAnnotation( begin=datetime.timedelta(seconds=begin_seconds),", "end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_utc(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin_utc': '2008-05-06", "\"\"\"Template testing UTCAnnotations relative to a fixture clip. This is a modification of", "file. Returns: Annotation over the restriction of the given time interval to the", "or implied. # See the License for the specific language governing permissions and", "coder.decode(encoded)) def test_utc_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_utc_annotation_relative_endpoints_before_clip(self):", "def test_round_trip_file_annotation(self): annotation = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=2.1), end=datetime.timedelta(seconds=3.1), ) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded", "end=datetime.datetime(2008, 5, 6, 11, 24, 42, 472000, tzinfo=tz.UTC), ) self.assertEqual(expected, annotation) def test_file_endpoints_override_utc_endpoints(self):", "= examplegen.UTCAnnotation( label='Mn', begin=datetime.datetime(2008, 5, 6, 11, 24, 41, 268000, tzinfo=tz.UTC), end=datetime.datetime(2008, 5,", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "to convert identical offset arguments (relative to the start of the file) to", "FileAnnotation relative to the file. end_seconds: Ending of the test FileAnnotation relative to", "Optional[examplegen.ClipAnnotation]: \"\"\"Template testing FileAnnotations relative to a fixture clip. The fixture clip covers", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "to the file. Args: begin_seconds: Beginning of the test FileAnnotation relative to the", "self.assertRaises(ValueError): examplegen.Annotation.parse_csv_row({'label': 'Mn'}) def test_round_trip_file_annotation(self): annotation = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=2.1), end=datetime.timedelta(seconds=3.1), ) coder", "def relative_endpoints_to_utc_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing UTCAnnotations relative to", "= examplegen.FileAnnotation( begin=datetime.timedelta(seconds=begin_seconds), end=datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) def relative_endpoints_to_utc_annotation_fixture( begin_seconds: float, end_seconds:", "given time interval to the fixture clip or None if they don't overlap.", "identical offset arguments (relative to the start of the file) to the corresponding", "examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_missing_fields(self): with self.assertRaises(ValueError): examplegen.Annotation.parse_csv_row({'label': 'Mn'})", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "language governing permissions and # limitations under the License. import datetime from typing", "datetime.timedelta(seconds=begin_seconds), end=file_start_utc + datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) class TestAnnotations(unittest.TestCase): def test_parse_annotation_rel_file(self): annotation", "the FileAnnotation version to convert identical offset arguments (relative to the start of", "import Optional, Tuple import unittest import apache_beam as beam from dateutil import tz", "of the test UTCAnnotation relative to the file. Returns: Annotation over the restriction", "begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_missing_fields(self): with self.assertRaises(ValueError): examplegen.Annotation.parse_csv_row({'label': 'Mn'}) def test_round_trip_file_annotation(self):", "they don't overlap. \"\"\" file_start_utc = datetime.datetime(2012, 2, 3, 11, 45, 20, tzinfo=tz.UTC)", "self.assertEqual(annotation, coder.decode(encoded)) def test_file_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def", "if they don't overlap. \"\"\" start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000,", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_file_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(22,", "you may not use this file except in compliance with the License. #", "examplegen def relative_endpoints_to_file_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing FileAnnotations relative", ") annotation = examplegen.FileAnnotation( begin=datetime.timedelta(seconds=begin_seconds), end=datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) def relative_endpoints_to_utc_annotation_fixture( begin_seconds:", "clip_annotation.end) def test_round_trip_utc_annotation(self): begin = datetime.datetime(2012, 2, 3, 11, 45, 15, tzinfo=tz.UTC) end", "begin = datetime.datetime(2012, 2, 3, 11, 45, 15, tzinfo=tz.UTC) end = begin +", "'1.8', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_utc(self):", "begin=begin, end=end) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_utc_annotation_relative_endpoints_within_clip(self): clip_annotation", "'1.2', 'end': '1.8', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.FileAnnotation(", "dateutil import tz from multispecies_whale_detection import examplegen def relative_endpoints_to_file_annotation_fixture( begin_seconds: float, end_seconds: float)", "interval to the fixture clip or None if they don't overlap. \"\"\" file_start_utc", "Google LLC # # Licensed under the Apache License, Version 2.0 (the \"License\");", "and # limitations under the License. import datetime from typing import Optional, Tuple", "start_relative_to_file=start_relative_to_file, start_utc=file_start_utc + start_relative_to_file, ) annotation = examplegen.UTCAnnotation( begin=file_start_utc + datetime.timedelta(seconds=begin_seconds), end=file_start_utc +", "relative_endpoints_to_file_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) def test_round_trip_utc_annotation(self): begin = datetime.datetime(2012, 2, 3,", "annotation) def test_parse_annotation_utc(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06", "+ start_relative_to_file, ) annotation = examplegen.UTCAnnotation( begin=file_start_utc + datetime.timedelta(seconds=begin_seconds), end=file_start_utc + datetime.timedelta(seconds=end_seconds), label='Oo',", "start_relative_to_file=start_relative_to_file, start_utc=None, ) annotation = examplegen.FileAnnotation( begin=datetime.timedelta(seconds=begin_seconds), end=datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) def", "test_file_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) def test_round_trip_utc_annotation(self): begin =", "use this file except in compliance with the License. # You may obtain", "clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) def test_round_trip_utc_annotation(self): begin = datetime.datetime(2012, 2, 3, 11, 45, 15,", "= datetime.datetime(2012, 2, 3, 11, 45, 15, tzinfo=tz.UTC) end = begin + datetime.timedelta(seconds=1.7)", "= examplegen.UTCAnnotation( begin=file_start_utc + datetime.timedelta(seconds=begin_seconds), end=file_start_utc + datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) class", "examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=None, ) annotation = examplegen.FileAnnotation( begin=datetime.timedelta(seconds=begin_seconds), end=datetime.timedelta(seconds=end_seconds),", "24, 41, 268000, tzinfo=tz.UTC), end=datetime.datetime(2008, 5, 6, 11, 24, 42, 472000, tzinfo=tz.UTC), )", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "test_file_endpoints_override_utc_endpoints(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8', 'begin_utc': '2008-05-06 11:24:41.268000',", "\"\"\" start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=None,", "version to convert identical offset arguments (relative to the start of the file)", "FileAnnotation version to convert identical offset arguments (relative to the start of the", "+ datetime.timedelta(seconds=1.7) annotation = examplegen.UTCAnnotation(label='Mn', begin=begin, end=end) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation)", "begin=datetime.timedelta(seconds=begin_seconds), end=datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) def relative_endpoints_to_utc_annotation_fixture( begin_seconds: float, end_seconds: float) ->", "with self.assertRaises(ValueError): examplegen.Annotation.parse_csv_row({'label': 'Mn'}) def test_round_trip_file_annotation(self): annotation = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=2.1), end=datetime.timedelta(seconds=3.1), )", "datetime.datetime(2012, 2, 3, 11, 45, 15, tzinfo=tz.UTC) end = begin + datetime.timedelta(seconds=1.7) annotation", "2.0 (the \"License\"); # you may not use this file except in compliance", "the file. Args: begin_seconds: Beginning of the test FileAnnotation relative to the file.", "'2008-05-06 11:24:42.472000', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def", "begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_utc(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin_utc':", "+ datetime.timedelta(seconds=begin_seconds), end=file_start_utc + datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) class TestAnnotations(unittest.TestCase): def test_parse_annotation_rel_file(self):", "the test UTCAnnotation relative to the file. Returns: Annotation over the restriction of", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "def test_utc_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_utc_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5,", "offset arguments (relative to the start of the file) to the corresponding UTC", "clip_annotation = relative_endpoints_to_file_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) def test_round_trip_utc_annotation(self): begin = datetime.datetime(2012,", "# # Unless required by applicable law or agreed to in writing, software", "float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing UTCAnnotations relative to a fixture clip. This is", "file. Args: begin_seconds: Beginning of the test FileAnnotation relative to the file. end_seconds:", "express or implied. # See the License for the specific language governing permissions", "annotation = examplegen.UTCAnnotation(label='Mn', begin=begin, end=end) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded))", "test_utc_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) if __name__ == '__main__':", "the test FileAnnotation relative to the file. Returns: Annotation over the restriction of", "42, 472000, tzinfo=tz.UTC), ) self.assertEqual(expected, annotation) def test_file_endpoints_override_utc_endpoints(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn',", "'2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), )", "interval [10s, 20s] relative to the file. Args: begin_seconds: Beginning of the test", "= beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_utc_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(22, 23.2)", "either express or implied. # See the License for the specific language governing", "tzinfo=tz.UTC), ) self.assertEqual(expected, annotation) def test_file_endpoints_override_utc_endpoints(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2',", "the restriction of the given time interval to the fixture clip or None", "Beginning of the test UTCAnnotation relative to the file. end_seconds: Ending of the", "start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=None, )", "UTC times, based on a hard-coded fixture file_start_utc. The fixture clip covers the", "relative to the file. Args: begin_seconds: Beginning of the test UTCAnnotation relative to", "begin=datetime.datetime(2008, 5, 6, 11, 24, 41, 268000, tzinfo=tz.UTC), end=datetime.datetime(2008, 5, 6, 11, 24,", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "test_parse_annotation_utc(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', })", "import examplegen def relative_endpoints_to_file_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing FileAnnotations", "covers the time interval [10s, 20s] relative to the file. Args: begin_seconds: Beginning", "clip_annotation = relative_endpoints_to_utc_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_utc_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5, 2.5)) def", "20s] relative to the file. Args: begin_seconds: Beginning of the test FileAnnotation relative", "'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.UTCAnnotation( label='Mn', begin=datetime.datetime(2008, 5,", "clip covers the time interval [10s, 20s] relative to the file. Args: begin_seconds:", "times, based on a hard-coded fixture file_start_utc. The fixture clip covers the time", "to the start of the file) to the corresponding UTC times, based on", "= examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8', }) expected = examplegen.FileAnnotation( label='Mn',", "self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_file_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5, 2.5)) def test_file_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42, 45)) def test_file_annotation_relative_endpoints_overlap_begin(self): clip_annotation", "float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing FileAnnotations relative to a fixture clip.", "2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the", "datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=None, ) annotation =", "from typing import Optional, Tuple import unittest import apache_beam as beam from dateutil", "expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_utc(self): annotation =", "self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_file_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5, 2.5)) def test_file_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42, 45)) def", "'Mn', 'begin': '1.2', 'end': '1.8', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), )", "tzinfo=tz.UTC), end=datetime.datetime(2008, 5, 6, 11, 24, 42, 472000, tzinfo=tz.UTC), ) self.assertEqual(expected, annotation) def", "= examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=2.1), end=datetime.timedelta(seconds=3.1), ) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation,", "the License. # You may obtain a copy of the License at #", "def test_parse_annotation_missing_fields(self): with self.assertRaises(ValueError): examplegen.Annotation.parse_csv_row({'label': 'Mn'}) def test_round_trip_file_annotation(self): annotation = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=2.1),", "= coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_file_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2),", "clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_file_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5, 2.5)) def test_file_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42, 45)) def test_file_annotation_relative_endpoints_overlap_begin(self):", "self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) def test_round_trip_utc_annotation(self): begin = datetime.datetime(2012, 2, 3, 11, 45, 15, tzinfo=tz.UTC)", "= coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_utc_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2),", "label='Oo', ) return annotation.make_relative(clip_metadata) def relative_endpoints_to_utc_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template", "def test_file_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5, 2.5)) def test_file_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42, 45)) def test_file_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(19.5,", "3, 11, 45, 15, tzinfo=tz.UTC) end = begin + datetime.timedelta(seconds=1.7) annotation = examplegen.UTCAnnotation(label='Mn',", "of the test UTCAnnotation relative to the file. end_seconds: Ending of the test", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing UTCAnnotations relative to a fixture", "def test_file_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42, 45)) def test_file_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1),", "Optional[examplegen.ClipAnnotation]: \"\"\"Template testing UTCAnnotations relative to a fixture clip. This is a modification", "Tuple import unittest import apache_beam as beam from dateutil import tz from multispecies_whale_detection", "apache_beam as beam from dateutil import tz from multispecies_whale_detection import examplegen def relative_endpoints_to_file_annotation_fixture(", "of the file) to the corresponding UTC times, based on a hard-coded fixture", "FileAnnotations relative to a fixture clip. The fixture clip covers the time interval", "15, tzinfo=tz.UTC) end = begin + datetime.timedelta(seconds=1.7) annotation = examplegen.UTCAnnotation(label='Mn', begin=begin, end=end) coder", "expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_missing_fields(self): with self.assertRaises(ValueError):", "test_file_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42, 45)) def test_file_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end)", "This is a modification of the FileAnnotation version to convert identical offset arguments", "begin_seconds: Beginning of the test UTCAnnotation relative to the file. end_seconds: Ending of", "testing UTCAnnotations relative to a fixture clip. This is a modification of the", "relative to the file. Args: begin_seconds: Beginning of the test FileAnnotation relative to", "end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing UTCAnnotations relative to a fixture clip. This", "with the License. # You may obtain a copy of the License at", ") annotation = examplegen.UTCAnnotation( begin=file_start_utc + datetime.timedelta(seconds=begin_seconds), end=file_start_utc + datetime.timedelta(seconds=end_seconds), label='Oo', ) return", "11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected,", "[10s, 20s] relative to the file. Args: begin_seconds: Beginning of the test UTCAnnotation", "23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_utc_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5, 2.5)) def test_utc_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42, 45))", "to the file. end_seconds: Ending of the test FileAnnotation relative to the file.", "2, 3, 11, 45, 15, tzinfo=tz.UTC) end = begin + datetime.timedelta(seconds=1.7) annotation =", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "'2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.UTCAnnotation( label='Mn', begin=datetime.datetime(2008, 5, 6,", "Returns: Annotation over the restriction of the given time interval to the fixture", "overlap. \"\"\" file_start_utc = datetime.datetime(2012, 2, 3, 11, 45, 20, tzinfo=tz.UTC) start_relative_to_file =", "= examplegen.UTCAnnotation(label='Mn', begin=begin, end=end) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def", "begin=file_start_utc + datetime.timedelta(seconds=begin_seconds), end=file_start_utc + datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) class TestAnnotations(unittest.TestCase): def", "test_utc_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5, 2.5)) def test_utc_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42, 45)) def test_utc_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(19.5, 22.1)", "Args: begin_seconds: Beginning of the test FileAnnotation relative to the file. end_seconds: Ending", "6, 11, 24, 41, 268000, tzinfo=tz.UTC), end=datetime.datetime(2008, 5, 6, 11, 24, 42, 472000,", "The fixture clip covers the time interval [10s, 20s] relative to the file.", "law or agreed to in writing, software # distributed under the License is", "= examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected =", "clip_annotation.end) def test_utc_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5, 2.5)) def test_utc_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42, 45)) def test_utc_annotation_relative_endpoints_overlap_begin(self): clip_annotation =", "the License for the specific language governing permissions and # limitations under the", "testing FileAnnotations relative to a fixture clip. The fixture clip covers the time", "a fixture clip. The fixture clip covers the time interval [10s, 20s] relative", "annotation = examplegen.FileAnnotation( begin=datetime.timedelta(seconds=begin_seconds), end=datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) def relative_endpoints_to_utc_annotation_fixture( begin_seconds: float,", "'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.UTCAnnotation( label='Mn', begin=datetime.datetime(2008, 5, 6, 11, 24,", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "= relative_endpoints_to_file_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_file_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5, 2.5)) def test_file_annotation_relative_endpoints_after_clip(self):", "<gh_stars>1-10 # Copyright 2022 Google LLC # # Licensed under the Apache License,", "relative to the file. end_seconds: Ending of the test UTCAnnotation relative to the", "test_round_trip_file_annotation(self): annotation = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=2.1), end=datetime.timedelta(seconds=3.1), ) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded =", "annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8', }) expected = examplegen.FileAnnotation(", "'Mn'}) def test_round_trip_file_annotation(self): annotation = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=2.1), end=datetime.timedelta(seconds=3.1), ) coder = beam.coders.registry.get_coder(examplegen.Annotation)", "import unittest import apache_beam as beam from dateutil import tz from multispecies_whale_detection import", "relative_endpoints_to_file_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_file_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5, 2.5)) def test_file_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42,", "to the file. end_seconds: Ending of the test UTCAnnotation relative to the file.", "FileAnnotation relative to the file. Returns: Annotation over the restriction of the given", "import apache_beam as beam from dateutil import tz from multispecies_whale_detection import examplegen def", "in compliance with the License. # You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "multispecies_whale_detection import examplegen def relative_endpoints_to_file_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing", "the time interval [10s, 20s] relative to the file. Args: begin_seconds: Beginning of", "the file. Args: begin_seconds: Beginning of the test UTCAnnotation relative to the file.", "See the License for the specific language governing permissions and # limitations under", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "file) to the corresponding UTC times, based on a hard-coded fixture file_start_utc. The", "self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) def test_round_trip_utc_annotation(self): begin = datetime.datetime(2012, 2, 3, 11, 45,", "11, 45, 15, tzinfo=tz.UTC) end = begin + datetime.timedelta(seconds=1.7) annotation = examplegen.UTCAnnotation(label='Mn', begin=begin,", "they don't overlap. \"\"\" start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10),", "Annotation over the restriction of the given time interval to the fixture clip", "def relative_endpoints_to_file_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing FileAnnotations relative to", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "the file. end_seconds: Ending of the test FileAnnotation relative to the file. Returns:", "11, 24, 42, 472000, tzinfo=tz.UTC), ) self.assertEqual(expected, annotation) def test_file_endpoints_override_utc_endpoints(self): annotation = examplegen.Annotation.parse_csv_row({", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "def test_parse_annotation_utc(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000',", "the test UTCAnnotation relative to the file. end_seconds: Ending of the test UTCAnnotation", "None if they don't overlap. \"\"\" file_start_utc = datetime.datetime(2012, 2, 3, 11, 45,", "= relative_endpoints_to_file_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=2.1), clip_annotation.end) def test_round_trip_utc_annotation(self): begin = datetime.datetime(2012, 2,", "self.assertEqual(expected, annotation) def test_file_endpoints_override_utc_endpoints(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8',", "self.assertEqual(annotation, coder.decode(encoded)) def test_utc_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def", ") return annotation.make_relative(clip_metadata) class TestAnnotations(unittest.TestCase): def test_parse_annotation_rel_file(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin':", "24, 42, 472000, tzinfo=tz.UTC), ) self.assertEqual(expected, annotation) def test_file_endpoints_override_utc_endpoints(self): annotation = examplegen.Annotation.parse_csv_row({ 'label':", "examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=2.1), end=datetime.timedelta(seconds=3.1), ) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded))", "2.5)) def test_file_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(42, 45)) def test_file_annotation_relative_endpoints_overlap_begin(self): clip_annotation = relative_endpoints_to_file_annotation_fixture(19.5, 22.1) self.assertEqual(datetime.timedelta(seconds=0), clip_annotation.begin)", "file_start_utc. The fixture clip covers the time interval [10s, 20s] relative to the", "the file. end_seconds: Ending of the test UTCAnnotation relative to the file. Returns:", "11:24:41.268000', 'end_utc': '2008-05-06 11:24:42.472000', }) expected = examplegen.UTCAnnotation( label='Mn', begin=datetime.datetime(2008, 5, 6, 11,", "clip or None if they don't overlap. \"\"\" file_start_utc = datetime.datetime(2012, 2, 3,", "# limitations under the License. import datetime from typing import Optional, Tuple import", "20s] relative to the file. Args: begin_seconds: Beginning of the test UTCAnnotation relative", "}) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2), end=datetime.timedelta(seconds=1.8), ) self.assertEqual(expected, annotation) def test_parse_annotation_missing_fields(self): with", "to the fixture clip or None if they don't overlap. \"\"\" file_start_utc =", "20, tzinfo=tz.UTC) start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file,", "relative to a fixture clip. The fixture clip covers the time interval [10s,", "clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_utc_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(1.5, 2.5)) def test_utc_annotation_relative_endpoints_after_clip(self): self.assertIsNone(relative_endpoints_to_utc_annotation_fixture(42, 45)) def test_utc_annotation_relative_endpoints_overlap_begin(self):", "end = begin + datetime.timedelta(seconds=1.7) annotation = examplegen.UTCAnnotation(label='Mn', begin=begin, end=end) coder = beam.coders.registry.get_coder(examplegen.Annotation)", "Version 2.0 (the \"License\"); # you may not use this file except in", "Ending of the test UTCAnnotation relative to the file. Returns: Annotation over the", "annotation = examplegen.UTCAnnotation( begin=file_start_utc + datetime.timedelta(seconds=begin_seconds), end=file_start_utc + datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata)", "except in compliance with the License. # You may obtain a copy of", "relative to the file. Returns: Annotation over the restriction of the given time", "def test_parse_annotation_rel_file(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8', }) expected", "268000, tzinfo=tz.UTC), end=datetime.datetime(2008, 5, 6, 11, 24, 42, 472000, tzinfo=tz.UTC), ) self.assertEqual(expected, annotation)", "specific language governing permissions and # limitations under the License. import datetime from", "of the FileAnnotation version to convert identical offset arguments (relative to the start", "to the file. Args: begin_seconds: Beginning of the test UTCAnnotation relative to the", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Ending of the test FileAnnotation relative to the file. Returns: Annotation over the", "the corresponding UTC times, based on a hard-coded fixture file_start_utc. The fixture clip", "begin + datetime.timedelta(seconds=1.7) annotation = examplegen.UTCAnnotation(label='Mn', begin=begin, end=end) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded =", "test FileAnnotation relative to the file. Returns: Annotation over the restriction of the", "end=datetime.timedelta(seconds=3.1), ) coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_file_annotation_relative_endpoints_within_clip(self): clip_annotation", "import tz from multispecies_whale_detection import examplegen def relative_endpoints_to_file_annotation_fixture( begin_seconds: float, end_seconds: float) ->", "UTCAnnotation relative to the file. end_seconds: Ending of the test UTCAnnotation relative to", "time interval [10s, 20s] relative to the file. Args: begin_seconds: Beginning of the", "examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin': '1.2', 'end': '1.8', }) expected = examplegen.FileAnnotation( label='Mn', begin=datetime.timedelta(seconds=1.2),", "41, 268000, tzinfo=tz.UTC), end=datetime.datetime(2008, 5, 6, 11, 24, 42, 472000, tzinfo=tz.UTC), ) self.assertEqual(expected,", "annotation) def test_parse_annotation_missing_fields(self): with self.assertRaises(ValueError): examplegen.Annotation.parse_csv_row({'label': 'Mn'}) def test_round_trip_file_annotation(self): annotation = examplegen.FileAnnotation( label='Mn',", "start_utc=None, ) annotation = examplegen.FileAnnotation( begin=datetime.timedelta(seconds=begin_seconds), end=datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) def relative_endpoints_to_utc_annotation_fixture(", "self.assertEqual(expected, annotation) def test_parse_annotation_utc(self): annotation = examplegen.Annotation.parse_csv_row({ 'label': 'Mn', 'begin_utc': '2008-05-06 11:24:41.268000', 'end_utc':", "the fixture clip or None if they don't overlap. \"\"\" file_start_utc = datetime.datetime(2012,", "self.assertEqual(expected, annotation) def test_parse_annotation_missing_fields(self): with self.assertRaises(ValueError): examplegen.Annotation.parse_csv_row({'label': 'Mn'}) def test_round_trip_file_annotation(self): annotation = examplegen.FileAnnotation(", "import datetime from typing import Optional, Tuple import unittest import apache_beam as beam", "over the restriction of the given time interval to the fixture clip or", "+ datetime.timedelta(seconds=end_seconds), label='Oo', ) return annotation.make_relative(clip_metadata) class TestAnnotations(unittest.TestCase): def test_parse_annotation_rel_file(self): annotation = examplegen.Annotation.parse_csv_row({", "end_seconds: Ending of the test FileAnnotation relative to the file. Returns: Annotation over", "from multispecies_whale_detection import examplegen def relative_endpoints_to_file_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template", "11, 45, 20, tzinfo=tz.UTC) start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10),", "end_seconds: float) -> Optional[examplegen.ClipAnnotation]: \"\"\"Template testing FileAnnotations relative to a fixture clip. The", "coder = beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_utc_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(22,", "the License. import datetime from typing import Optional, Tuple import unittest import apache_beam", "fixture clip or None if they don't overlap. \"\"\" start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata", "beam.coders.registry.get_coder(examplegen.Annotation) encoded = coder.encode(annotation) self.assertEqual(annotation, coder.decode(encoded)) def test_utc_annotation_relative_endpoints_within_clip(self): clip_annotation = relative_endpoints_to_utc_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2),", "11, 24, 41, 268000, tzinfo=tz.UTC), end=datetime.datetime(2008, 5, 6, 11, 24, 42, 472000, tzinfo=tz.UTC),", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "fixture clip covers the time interval [10s, 20s] relative to the file. Args:", "test_round_trip_utc_annotation(self): begin = datetime.datetime(2012, 2, 3, 11, 45, 15, tzinfo=tz.UTC) end = begin", "tz from multispecies_whale_detection import examplegen def relative_endpoints_to_file_annotation_fixture( begin_seconds: float, end_seconds: float) -> Optional[examplegen.ClipAnnotation]:", "a modification of the FileAnnotation version to convert identical offset arguments (relative to", "fixture clip. The fixture clip covers the time interval [10s, 20s] relative to", "or None if they don't overlap. \"\"\" start_relative_to_file = datetime.timedelta(seconds=20) clip_metadata = examplegen.ClipMetadata(", "clip_metadata = examplegen.ClipMetadata( filename='test.wav', sample_rate=10000, duration=datetime.timedelta(seconds=10), index_in_file=2, start_relative_to_file=start_relative_to_file, start_utc=None, ) annotation = examplegen.FileAnnotation(", "clip_annotation = relative_endpoints_to_file_annotation_fixture(22, 23.2) self.assertEqual(datetime.timedelta(seconds=2), clip_annotation.begin) self.assertEqual(datetime.timedelta(seconds=3.2), clip_annotation.end) def test_file_annotation_relative_endpoints_before_clip(self): self.assertIsNone(relative_endpoints_to_file_annotation_fixture(1.5, 2.5)) def" ]
[ "version 2 of the License, or # (at your option) any later version.", "distributed in the hope that it will be useful, # but WITHOUT ANY", "gui.widgetlib.cairoscroller import CairoScroller from gui.widgetlib.floatingwindow import FloatingWindow from gui.widgetlib.srceditor import SourceEditor from gui.widgetlib.trayicon", "import FontCombo # EVOGTK database widgets from gui.widgetlib.dbentry import DBEntry from gui.widgetlib.dbspinbutton import", "PURPOSE. See the # GNU General Public License for more details. # #", "USA. ############################################################################### # widgets # EVOGTK Custom Widgets ############################################################################### # EVOGTK base widgets", "import AppIndicator from gui.widgetlib.webbrowser import WebBrowser from gui.widgetlib.datepicker import DatePicker from gui.widgetlib.regexpentry import", "AppIndicator from gui.widgetlib.webbrowser import WebBrowser from gui.widgetlib.datepicker import DatePicker from gui.widgetlib.regexpentry import RegExpEntry", "import DBComboBox from gui.widgetlib.dbcheckbutton import DBCheckButton from gui.widgetlib.dbdatepicker import DBDatePicker from gui.widgetlib.dbcalendar import", "# (at your option) any later version. # # This program is distributed", "program; if not, write to the Free Software Foundation, Inc., # 51 Franklin", "Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ############################################################################### # widgets # EVOGTK", "DBCheckButton from gui.widgetlib.dbdatepicker import DBDatePicker from gui.widgetlib.dbcalendar import DBCalendar from gui.widgetlib.dbregexpentry import DBRegExpEntry", "it and/or modify # it under the terms of the GNU General Public", "from gui.widgetlib.floatingwindow import FloatingWindow from gui.widgetlib.srceditor import SourceEditor from gui.widgetlib.trayicon import TrayIcon from", "gui.widgetlib.dbcheckbutton import DBCheckButton from gui.widgetlib.dbdatepicker import DBDatePicker from gui.widgetlib.dbcalendar import DBCalendar from gui.widgetlib.dbregexpentry", "any later version. # # This program is distributed in the hope that", "FloatingWindow from gui.widgetlib.srceditor import SourceEditor from gui.widgetlib.trayicon import TrayIcon from gui.widgetlib.trayicon import AppIndicator", "gui.widgetlib.dbspinbutton import DBSpinButton from gui.widgetlib.dbcombobox import DBComboBox from gui.widgetlib.dbcheckbutton import DBCheckButton from gui.widgetlib.dbdatepicker", "# it under the terms of the GNU General Public License as published", "terms of the GNU General Public License as published by # the Free", "Widgets ############################################################################### # EVOGTK base widgets from gui.widgetlib.cairocanvas import CairoCanvas from gui.widgetlib.cairoscroller import", "it under the terms of the GNU General Public License as published by", "with this program; if not, write to the Free Software Foundation, Inc., #", "License for more details. # # You should have received a copy of", "gui.widgetlib.datepicker import DatePicker from gui.widgetlib.regexpentry import RegExpEntry from gui.widgetlib.colorpicker import ColorPicker from gui.widgetlib.fontcombo", "you can redistribute it and/or modify # it under the terms of the", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General", "License, or # (at your option) any later version. # # This program", "of the GNU General Public License as published by # the Free Software", "# the Free Software Foundation; either version 2 of the License, or #", "EVOGTK database widgets from gui.widgetlib.dbentry import DBEntry from gui.widgetlib.dbspinbutton import DBSpinButton from gui.widgetlib.dbcombobox", "MA 02110-1301 USA. ############################################################################### # widgets # EVOGTK Custom Widgets ############################################################################### # EVOGTK", "import SourceEditor from gui.widgetlib.trayicon import TrayIcon from gui.widgetlib.trayicon import AppIndicator from gui.widgetlib.webbrowser import", "redistribute it and/or modify # it under the terms of the GNU General", "from gui.widgetlib.colorpicker import ColorPicker from gui.widgetlib.fontcombo import FontCombo # EVOGTK database widgets from", "Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301", "modify # it under the terms of the GNU General Public License as", "have received a copy of the GNU General Public License along # with", "of the License, or # (at your option) any later version. # #", "is free software; you can redistribute it and/or modify # it under the", "Copyright (C) 2008 EVO Sistemas Libres <<EMAIL>> # This program is free software;", "PARTICULAR PURPOSE. See the # GNU General Public License for more details. #", "# Copyright (C) 2008 EVO Sistemas Libres <<EMAIL>> # This program is free", "the GNU General Public License as published by # the Free Software Foundation;", "to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston,", "coding: utf-8 -*- ############################################################################### # Copyright (C) 2008 EVO Sistemas Libres <<EMAIL>> #", "without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "a copy of the GNU General Public License along # with this program;", "Software Foundation; either version 2 of the License, or # (at your option)", "from gui.widgetlib.dbcombobox import DBComboBox from gui.widgetlib.dbcheckbutton import DBCheckButton from gui.widgetlib.dbdatepicker import DBDatePicker from", "hope that it will be useful, # but WITHOUT ANY WARRANTY; without even", "from gui.widgetlib.dbspinbutton import DBSpinButton from gui.widgetlib.dbcombobox import DBComboBox from gui.widgetlib.dbcheckbutton import DBCheckButton from", "Sistemas Libres <<EMAIL>> # This program is free software; you can redistribute it", "ColorPicker from gui.widgetlib.fontcombo import FontCombo # EVOGTK database widgets from gui.widgetlib.dbentry import DBEntry", "FontCombo # EVOGTK database widgets from gui.widgetlib.dbentry import DBEntry from gui.widgetlib.dbspinbutton import DBSpinButton", "import WebBrowser from gui.widgetlib.datepicker import DatePicker from gui.widgetlib.regexpentry import RegExpEntry from gui.widgetlib.colorpicker import", "the GNU General Public License along # with this program; if not, write", "51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ############################################################################### # widgets #", "############################################################################### # widgets # EVOGTK Custom Widgets ############################################################################### # EVOGTK base widgets from", "Free Software Foundation; either version 2 of the License, or # (at your", "Boston, MA 02110-1301 USA. ############################################################################### # widgets # EVOGTK Custom Widgets ############################################################################### #", "import FloatingWindow from gui.widgetlib.srceditor import SourceEditor from gui.widgetlib.trayicon import TrayIcon from gui.widgetlib.trayicon import", "Public License as published by # the Free Software Foundation; either version 2", "Custom Widgets ############################################################################### # EVOGTK base widgets from gui.widgetlib.cairocanvas import CairoCanvas from gui.widgetlib.cairoscroller", "DBSpinButton from gui.widgetlib.dbcombobox import DBComboBox from gui.widgetlib.dbcheckbutton import DBCheckButton from gui.widgetlib.dbdatepicker import DBDatePicker", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #", "free software; you can redistribute it and/or modify # it under the terms", "gui.widgetlib.regexpentry import RegExpEntry from gui.widgetlib.colorpicker import ColorPicker from gui.widgetlib.fontcombo import FontCombo # EVOGTK", "Public License along # with this program; if not, write to the Free", "See the # GNU General Public License for more details. # # You", "License along # with this program; if not, write to the Free Software", "Libres <<EMAIL>> # This program is free software; you can redistribute it and/or", "GNU General Public License along # with this program; if not, write to", "import CairoScroller from gui.widgetlib.floatingwindow import FloatingWindow from gui.widgetlib.srceditor import SourceEditor from gui.widgetlib.trayicon import", "Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.", "############################################################################### # Copyright (C) 2008 EVO Sistemas Libres <<EMAIL>> # This program is", "gui.widgetlib.trayicon import AppIndicator from gui.widgetlib.webbrowser import WebBrowser from gui.widgetlib.datepicker import DatePicker from gui.widgetlib.regexpentry", "(at your option) any later version. # # This program is distributed in", "This program is distributed in the hope that it will be useful, #", "software; you can redistribute it and/or modify # it under the terms of", "details. # # You should have received a copy of the GNU General", "along # with this program; if not, write to the Free Software Foundation,", "this program; if not, write to the Free Software Foundation, Inc., # 51", "import DBCheckButton from gui.widgetlib.dbdatepicker import DBDatePicker from gui.widgetlib.dbcalendar import DBCalendar from gui.widgetlib.dbregexpentry import", "import CairoCanvas from gui.widgetlib.cairoscroller import CairoScroller from gui.widgetlib.floatingwindow import FloatingWindow from gui.widgetlib.srceditor import", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "should have received a copy of the GNU General Public License along #", "02110-1301 USA. ############################################################################### # widgets # EVOGTK Custom Widgets ############################################################################### # EVOGTK base", "from gui.widgetlib.trayicon import TrayIcon from gui.widgetlib.trayicon import AppIndicator from gui.widgetlib.webbrowser import WebBrowser from", "useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #", "that it will be useful, # but WITHOUT ANY WARRANTY; without even the", "General Public License as published by # the Free Software Foundation; either version", "the License, or # (at your option) any later version. # # This", "# -*- coding: utf-8 -*- ############################################################################### # Copyright (C) 2008 EVO Sistemas Libres", "your option) any later version. # # This program is distributed in the", "as published by # the Free Software Foundation; either version 2 of the", "widgets from gui.widgetlib.cairocanvas import CairoCanvas from gui.widgetlib.cairoscroller import CairoScroller from gui.widgetlib.floatingwindow import FloatingWindow", "# EVOGTK database widgets from gui.widgetlib.dbentry import DBEntry from gui.widgetlib.dbspinbutton import DBSpinButton from", "from gui.widgetlib.webbrowser import WebBrowser from gui.widgetlib.datepicker import DatePicker from gui.widgetlib.regexpentry import RegExpEntry from", "the terms of the GNU General Public License as published by # the", "write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor,", "widgets # EVOGTK Custom Widgets ############################################################################### # EVOGTK base widgets from gui.widgetlib.cairocanvas import", "DBEntry from gui.widgetlib.dbspinbutton import DBSpinButton from gui.widgetlib.dbcombobox import DBComboBox from gui.widgetlib.dbcheckbutton import DBCheckButton", "import DBEntry from gui.widgetlib.dbspinbutton import DBSpinButton from gui.widgetlib.dbcombobox import DBComboBox from gui.widgetlib.dbcheckbutton import", "if not, write to the Free Software Foundation, Inc., # 51 Franklin Street,", "import DatePicker from gui.widgetlib.regexpentry import RegExpEntry from gui.widgetlib.colorpicker import ColorPicker from gui.widgetlib.fontcombo import", "from gui.widgetlib.dbcheckbutton import DBCheckButton from gui.widgetlib.dbdatepicker import DBDatePicker from gui.widgetlib.dbcalendar import DBCalendar from", "from gui.widgetlib.datepicker import DatePicker from gui.widgetlib.regexpentry import RegExpEntry from gui.widgetlib.colorpicker import ColorPicker from", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "from gui.widgetlib.cairocanvas import CairoCanvas from gui.widgetlib.cairoscroller import CairoScroller from gui.widgetlib.floatingwindow import FloatingWindow from", "database widgets from gui.widgetlib.dbentry import DBEntry from gui.widgetlib.dbspinbutton import DBSpinButton from gui.widgetlib.dbcombobox import", "-*- ############################################################################### # Copyright (C) 2008 EVO Sistemas Libres <<EMAIL>> # This program", "EVO Sistemas Libres <<EMAIL>> # This program is free software; you can redistribute", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ###############################################################################", "EVOGTK Custom Widgets ############################################################################### # EVOGTK base widgets from gui.widgetlib.cairocanvas import CairoCanvas from", "import DBSpinButton from gui.widgetlib.dbcombobox import DBComboBox from gui.widgetlib.dbcheckbutton import DBCheckButton from gui.widgetlib.dbdatepicker import", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "later version. # # This program is distributed in the hope that it", "2008 EVO Sistemas Libres <<EMAIL>> # This program is free software; you can", "not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth", "gui.widgetlib.fontcombo import FontCombo # EVOGTK database widgets from gui.widgetlib.dbentry import DBEntry from gui.widgetlib.dbspinbutton", "gui.widgetlib.floatingwindow import FloatingWindow from gui.widgetlib.srceditor import SourceEditor from gui.widgetlib.trayicon import TrayIcon from gui.widgetlib.trayicon", "it will be useful, # but WITHOUT ANY WARRANTY; without even the implied", "# # This program is distributed in the hope that it will be", "# This program is free software; you can redistribute it and/or modify #", "WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS", "the hope that it will be useful, # but WITHOUT ANY WARRANTY; without", "# # You should have received a copy of the GNU General Public", "DatePicker from gui.widgetlib.regexpentry import RegExpEntry from gui.widgetlib.colorpicker import ColorPicker from gui.widgetlib.fontcombo import FontCombo", "<<EMAIL>> # This program is free software; you can redistribute it and/or modify", "You should have received a copy of the GNU General Public License along", "License as published by # the Free Software Foundation; either version 2 of", "CairoScroller from gui.widgetlib.floatingwindow import FloatingWindow from gui.widgetlib.srceditor import SourceEditor from gui.widgetlib.trayicon import TrayIcon", "General Public License for more details. # # You should have received a", "base widgets from gui.widgetlib.cairocanvas import CairoCanvas from gui.widgetlib.cairoscroller import CairoScroller from gui.widgetlib.floatingwindow import", "received a copy of the GNU General Public License along # with this", "FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more", "(C) 2008 EVO Sistemas Libres <<EMAIL>> # This program is free software; you", "# EVOGTK Custom Widgets ############################################################################### # EVOGTK base widgets from gui.widgetlib.cairocanvas import CairoCanvas", "from gui.widgetlib.srceditor import SourceEditor from gui.widgetlib.trayicon import TrayIcon from gui.widgetlib.trayicon import AppIndicator from", "import TrayIcon from gui.widgetlib.trayicon import AppIndicator from gui.widgetlib.webbrowser import WebBrowser from gui.widgetlib.datepicker import", "import ColorPicker from gui.widgetlib.fontcombo import FontCombo # EVOGTK database widgets from gui.widgetlib.dbentry import", "RegExpEntry from gui.widgetlib.colorpicker import ColorPicker from gui.widgetlib.fontcombo import FontCombo # EVOGTK database widgets", "be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of", "widgets from gui.widgetlib.dbentry import DBEntry from gui.widgetlib.dbspinbutton import DBSpinButton from gui.widgetlib.dbcombobox import DBComboBox", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "EVOGTK base widgets from gui.widgetlib.cairocanvas import CairoCanvas from gui.widgetlib.cairoscroller import CairoScroller from gui.widgetlib.floatingwindow", "published by # the Free Software Foundation; either version 2 of the License,", "Street, Fifth Floor, Boston, MA 02110-1301 USA. ############################################################################### # widgets # EVOGTK Custom", "from gui.widgetlib.cairoscroller import CairoScroller from gui.widgetlib.floatingwindow import FloatingWindow from gui.widgetlib.srceditor import SourceEditor from", "gui.widgetlib.srceditor import SourceEditor from gui.widgetlib.trayicon import TrayIcon from gui.widgetlib.trayicon import AppIndicator from gui.widgetlib.webbrowser", "# You should have received a copy of the GNU General Public License", "Public License for more details. # # You should have received a copy", "gui.widgetlib.trayicon import TrayIcon from gui.widgetlib.trayicon import AppIndicator from gui.widgetlib.webbrowser import WebBrowser from gui.widgetlib.datepicker", "import RegExpEntry from gui.widgetlib.colorpicker import ColorPicker from gui.widgetlib.fontcombo import FontCombo # EVOGTK database", "CairoCanvas from gui.widgetlib.cairoscroller import CairoScroller from gui.widgetlib.floatingwindow import FloatingWindow from gui.widgetlib.srceditor import SourceEditor", "is distributed in the hope that it will be useful, # but WITHOUT", "General Public License along # with this program; if not, write to the", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public", "Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ############################################################################### #", "DBComboBox from gui.widgetlib.dbcheckbutton import DBCheckButton from gui.widgetlib.dbdatepicker import DBDatePicker from gui.widgetlib.dbcalendar import DBCalendar", "in the hope that it will be useful, # but WITHOUT ANY WARRANTY;", "############################################################################### # EVOGTK base widgets from gui.widgetlib.cairocanvas import CairoCanvas from gui.widgetlib.cairoscroller import CairoScroller", "the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA", "Fifth Floor, Boston, MA 02110-1301 USA. ############################################################################### # widgets # EVOGTK Custom Widgets", "version. # # This program is distributed in the hope that it will", "# with this program; if not, write to the Free Software Foundation, Inc.,", "FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for", "gui.widgetlib.colorpicker import ColorPicker from gui.widgetlib.fontcombo import FontCombo # EVOGTK database widgets from gui.widgetlib.dbentry", "from gui.widgetlib.fontcombo import FontCombo # EVOGTK database widgets from gui.widgetlib.dbentry import DBEntry from", "gui.widgetlib.webbrowser import WebBrowser from gui.widgetlib.datepicker import DatePicker from gui.widgetlib.regexpentry import RegExpEntry from gui.widgetlib.colorpicker", "by # the Free Software Foundation; either version 2 of the License, or", "2 of the License, or # (at your option) any later version. #", "and/or modify # it under the terms of the GNU General Public License", "# widgets # EVOGTK Custom Widgets ############################################################################### # EVOGTK base widgets from gui.widgetlib.cairocanvas", "the # GNU General Public License for more details. # # You should", "-*- coding: utf-8 -*- ############################################################################### # Copyright (C) 2008 EVO Sistemas Libres <<EMAIL>>", "A PARTICULAR PURPOSE. See the # GNU General Public License for more details.", "or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License", "for more details. # # You should have received a copy of the", "Floor, Boston, MA 02110-1301 USA. ############################################################################### # widgets # EVOGTK Custom Widgets ###############################################################################", "utf-8 -*- ############################################################################### # Copyright (C) 2008 EVO Sistemas Libres <<EMAIL>> # This", "gui.widgetlib.cairocanvas import CairoCanvas from gui.widgetlib.cairoscroller import CairoScroller from gui.widgetlib.floatingwindow import FloatingWindow from gui.widgetlib.srceditor", "gui.widgetlib.dbentry import DBEntry from gui.widgetlib.dbspinbutton import DBSpinButton from gui.widgetlib.dbcombobox import DBComboBox from gui.widgetlib.dbcheckbutton", "program is free software; you can redistribute it and/or modify # it under", "# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ############################################################################### # widgets", "This program is free software; you can redistribute it and/or modify # it", "gui.widgetlib.dbcombobox import DBComboBox from gui.widgetlib.dbcheckbutton import DBCheckButton from gui.widgetlib.dbdatepicker import DBDatePicker from gui.widgetlib.dbcalendar", "# EVOGTK base widgets from gui.widgetlib.cairocanvas import CairoCanvas from gui.widgetlib.cairoscroller import CairoScroller from", "GNU General Public License as published by # the Free Software Foundation; either", "will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty", "from gui.widgetlib.trayicon import AppIndicator from gui.widgetlib.webbrowser import WebBrowser from gui.widgetlib.datepicker import DatePicker from", "either version 2 of the License, or # (at your option) any later", "SourceEditor from gui.widgetlib.trayicon import TrayIcon from gui.widgetlib.trayicon import AppIndicator from gui.widgetlib.webbrowser import WebBrowser", "copy of the GNU General Public License along # with this program; if", "or # (at your option) any later version. # # This program is", "more details. # # You should have received a copy of the GNU", "of the GNU General Public License along # with this program; if not,", "from gui.widgetlib.regexpentry import RegExpEntry from gui.widgetlib.colorpicker import ColorPicker from gui.widgetlib.fontcombo import FontCombo #", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU", "TrayIcon from gui.widgetlib.trayicon import AppIndicator from gui.widgetlib.webbrowser import WebBrowser from gui.widgetlib.datepicker import DatePicker", "GNU General Public License for more details. # # You should have received", "the Free Software Foundation; either version 2 of the License, or # (at", "WebBrowser from gui.widgetlib.datepicker import DatePicker from gui.widgetlib.regexpentry import RegExpEntry from gui.widgetlib.colorpicker import ColorPicker", "under the terms of the GNU General Public License as published by #", "# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "option) any later version. # # This program is distributed in the hope", "# GNU General Public License for more details. # # You should have", "from gui.widgetlib.dbentry import DBEntry from gui.widgetlib.dbspinbutton import DBSpinButton from gui.widgetlib.dbcombobox import DBComboBox from", "Foundation; either version 2 of the License, or # (at your option) any", "can redistribute it and/or modify # it under the terms of the GNU", "program is distributed in the hope that it will be useful, # but", "# This program is distributed in the hope that it will be useful,", "but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or" ]
[ "d1, c = s.geometry, s.vertices, s.dimensions, s.constraints s.setPrimaryObject(option=SUPERIMPOSE) p = mdb.models['Model-1'].parts['Part-1'] p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES)", "p.edges #side1Edges = s.getSequenceFromMask(mask=('[#1 ]', ), ) #p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #e", "name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #e = p.edges #edges = s.getSequenceFromMask(mask=('[#4 ]', ), )", "= mdb.models['Model-1'].parts['Part-1'] f, e, d = p.faces, p.edges, p.datums t = p.MakeSketchTransform(sketchPlane=f[0], sketchPlaneSide=SIDE1,", "d = p.faces, p.edges, p.datums t = p.MakeSketchTransform(sketchPlane=f[0], sketchPlaneSide=SIDE1, origin=(0.0, 0.0, 0.0)) s", "of the fine area p = mdb.models['Model-1'].parts['Part-1'] f = p.faces pickedFaces = f.getSequenceFromMask(mask=('[#1", "s.vertices, s.dimensions, s.constraints s.setPrimaryObject(option=SUPERIMPOSE) p = mdb.models['Model-1'].parts['Part-1'] p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES) s.rectangle(point1=(0.0, 0.0), point2=(3*indent_width, -4*indent_depth))#", "e1, d2 = p.edges, p.datums p.PartitionFaceBySketch(faces=pickedFaces, sketch=s) s.unsetPrimaryObject() del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1']", "= f.getSequenceFromMask(mask=('[#1 ]', ), ) e1, d2 = p.edges, p.datums p.PartitionFaceBySketch(faces=pickedFaces, sketch=s) s.unsetPrimaryObject()", "c = s.geometry, s.vertices, s.dimensions, s.constraints s.setPrimaryObject(option=SUPERIMPOSE) p = mdb.models['Model-1'].parts['Part-1'] p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES) s.rectangle(point1=(0.0,", ") #p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #e = p.edges #edges = s.getSequenceFromMask(mask=('[#4 ]',", "#s = p.edges #side1Edges = s.getSequenceFromMask(mask=('[#1 ]', ), ) #p.Surface(side1Edges=side1Edges, name='Surf-spec') #p =", "#p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #e = p.edges #edges = s.getSequenceFromMask(mask=('[#4 ]', ),", "p = mdb.models['Model-1'].parts['Part-1'] f, e, d = p.faces, p.edges, p.datums t = p.MakeSketchTransform(sketchPlane=f[0],", "), ) p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #s = p.edges #side1Edges = s.getSequenceFromMask(mask=('[#1", "0.0), point2=(35*indent_width, -t)) p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=AXISYMMETRIC, type=DEFORMABLE_BODY) p = mdb.models['Model-1'].parts['Part-1'] p.BaseShell(sketch=s) s.unsetPrimaryObject()", "s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0)) s.FixedConstraint(entity=g[2]) s.rectangle(point1=(0.0, 0.0), point2=(35*indent_width, -t)) p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=AXISYMMETRIC,", "e, d = p.faces, p.edges, p.datums t = p.MakeSketchTransform(sketchPlane=f[0], sketchPlaneSide=SIDE1, origin=(0.0, 0.0, 0.0))", "= mdb.models['Model-1'].parts['Part-1'] p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES) s.rectangle(point1=(0.0, 0.0), point2=(3*indent_width, -4*indent_depth))# size of the fine area", "p.edges, p.datums t = p.MakeSketchTransform(sketchPlane=f[0], sketchPlaneSide=SIDE1, origin=(0.0, 0.0, 0.0)) s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=181.1,", "s.getSequenceFromMask(mask=('[#60 ]', ), ) p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #s = p.edges #side1Edges", "p.datums p.PartitionFaceBySketch(faces=pickedFaces, sketch=s) s.unsetPrimaryObject() del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] s = p.edges side1Edges", "p.datums t = p.MakeSketchTransform(sketchPlane=f[0], sketchPlaneSide=SIDE1, origin=(0.0, 0.0, 0.0)) s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=181.1, gridSpacing=4.52,", "the fine area p = mdb.models['Model-1'].parts['Part-1'] f = p.faces pickedFaces = f.getSequenceFromMask(mask=('[#1 ]',", "), ) e1, d2 = p.edges, p.datums p.PartitionFaceBySketch(faces=pickedFaces, sketch=s) s.unsetPrimaryObject() del mdb.models['Model-1'].sketches['__profile__'] p", "s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=200.0) g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints", "= mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=200.0) g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints s.sketchOptions.setValues(viewStyle=AXISYM)", "mdb.models['Model-1'].parts['Part-1'] f = p.faces pickedFaces = f.getSequenceFromMask(mask=('[#1 ]', ), ) e1, d2 =", "s.rectangle(point1=(0.0, 0.0), point2=(35*indent_width, -t)) p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=AXISYMMETRIC, type=DEFORMABLE_BODY) p = mdb.models['Model-1'].parts['Part-1'] p.BaseShell(sketch=s)", "#p = mdb.models['Model-1'].parts['Part-1'] #s = p.edges #side1Edges = s.getSequenceFromMask(mask=('[#1 ]', ), ) #p.Surface(side1Edges=side1Edges,", "p.faces pickedFaces = f.getSequenceFromMask(mask=('[#1 ]', ), ) e1, d2 = p.edges, p.datums p.PartitionFaceBySketch(faces=pickedFaces,", "s = p.edges side1Edges = s.getSequenceFromMask(mask=('[#60 ]', ), ) p.Surface(side1Edges=side1Edges, name='Surf-spec') #p =", "point2=(3*indent_width, -4*indent_depth))# size of the fine area p = mdb.models['Model-1'].parts['Part-1'] f = p.faces", "= p.MakeSketchTransform(sketchPlane=f[0], sketchPlaneSide=SIDE1, origin=(0.0, 0.0, 0.0)) s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=181.1, gridSpacing=4.52, transform=t) g,", "1'].setValues(displayedObject=p) del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] f, e, d = p.faces, p.edges, p.datums", "s.setPrimaryObject(option=STANDALONE) s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0)) s.FixedConstraint(entity=g[2]) s.rectangle(point1=(0.0, 0.0), point2=(35*indent_width, -t)) p = mdb.models['Model-1'].Part(name='Part-1',", "mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=181.1, gridSpacing=4.52, transform=t) g, v, d1, c = s.geometry, s.vertices, s.dimensions, s.constraints", "v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints s.sketchOptions.setValues(viewStyle=AXISYM) s.setPrimaryObject(option=STANDALONE) s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0,", "gridSpacing=4.52, transform=t) g, v, d1, c = s.geometry, s.vertices, s.dimensions, s.constraints s.setPrimaryObject(option=SUPERIMPOSE) p", "dimensionality=AXISYMMETRIC, type=DEFORMABLE_BODY) p = mdb.models['Model-1'].parts['Part-1'] p.BaseShell(sketch=s) s.unsetPrimaryObject() p = mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport: 1'].setValues(displayedObject=p) del", "]', ), ) p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #s = p.edges #side1Edges =", "del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] s = p.edges side1Edges = s.getSequenceFromMask(mask=('[#60 ]', ),", "= p.faces pickedFaces = f.getSequenceFromMask(mask=('[#1 ]', ), ) e1, d2 = p.edges, p.datums", "pickedFaces = f.getSequenceFromMask(mask=('[#1 ]', ), ) e1, d2 = p.edges, p.datums p.PartitionFaceBySketch(faces=pickedFaces, sketch=s)", "s.rectangle(point1=(0.0, 0.0), point2=(3*indent_width, -4*indent_depth))# size of the fine area p = mdb.models['Model-1'].parts['Part-1'] f", "= mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport: 1'].setValues(displayedObject=p) del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] f, e, d =", "size of the fine area p = mdb.models['Model-1'].parts['Part-1'] f = p.faces pickedFaces =", "sketch=s) s.unsetPrimaryObject() del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] s = p.edges side1Edges = s.getSequenceFromMask(mask=('[#60", "0.0, 0.0)) s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=181.1, gridSpacing=4.52, transform=t) g, v, d1, c =", "#p = mdb.models['Model-1'].parts['Part-1'] #e = p.edges #edges = s.getSequenceFromMask(mask=('[#4 ]', ), ) #p.Set(edges=edges,", "s.dimensions, s.constraints s.setPrimaryObject(option=SUPERIMPOSE) p = mdb.models['Model-1'].parts['Part-1'] p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES) s.rectangle(point1=(0.0, 0.0), point2=(3*indent_width, -4*indent_depth))# size", "filter=COPLANAR_EDGES) s.rectangle(point1=(0.0, 0.0), point2=(3*indent_width, -4*indent_depth))# size of the fine area p = mdb.models['Model-1'].parts['Part-1']", "= mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=181.1, gridSpacing=4.52, transform=t) g, v, d1, c = s.geometry, s.vertices, s.dimensions,", "s.dimensions, s.constraints s.sketchOptions.setValues(viewStyle=AXISYM) s.setPrimaryObject(option=STANDALONE) s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0)) s.FixedConstraint(entity=g[2]) s.rectangle(point1=(0.0, 0.0), point2=(35*indent_width, -t))", "-t)) p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=AXISYMMETRIC, type=DEFORMABLE_BODY) p = mdb.models['Model-1'].parts['Part-1'] p.BaseShell(sketch=s) s.unsetPrimaryObject() p =", "]', ), ) e1, d2 = p.edges, p.datums p.PartitionFaceBySketch(faces=pickedFaces, sketch=s) s.unsetPrimaryObject() del mdb.models['Model-1'].sketches['__profile__']", "= mdb.models['Model-1'].parts['Part-1'] #s = p.edges #side1Edges = s.getSequenceFromMask(mask=('[#1 ]', ), ) #p.Surface(side1Edges=side1Edges, name='Surf-spec')", "session.viewports['Viewport: 1'].setValues(displayedObject=p) del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] f, e, d = p.faces, p.edges,", "p = mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport: 1'].setValues(displayedObject=p) del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] f, e, d", "= mdb.models['Model-1'].Part(name='Part-1', dimensionality=AXISYMMETRIC, type=DEFORMABLE_BODY) p = mdb.models['Model-1'].parts['Part-1'] p.BaseShell(sketch=s) s.unsetPrimaryObject() p = mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport:", "p.BaseShell(sketch=s) s.unsetPrimaryObject() p = mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport: 1'].setValues(displayedObject=p) del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] f,", "area p = mdb.models['Model-1'].parts['Part-1'] f = p.faces pickedFaces = f.getSequenceFromMask(mask=('[#1 ]', ), )", "s.unsetPrimaryObject() p = mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport: 1'].setValues(displayedObject=p) del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] f, e,", "s.geometry, s.vertices, s.dimensions, s.constraints s.sketchOptions.setValues(viewStyle=AXISYM) s.setPrimaryObject(option=STANDALONE) s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0)) s.FixedConstraint(entity=g[2]) s.rectangle(point1=(0.0, 0.0),", "fine area p = mdb.models['Model-1'].parts['Part-1'] f = p.faces pickedFaces = f.getSequenceFromMask(mask=('[#1 ]', ),", "f.getSequenceFromMask(mask=('[#1 ]', ), ) e1, d2 = p.edges, p.datums p.PartitionFaceBySketch(faces=pickedFaces, sketch=s) s.unsetPrimaryObject() del", "transform=t) g, v, d1, c = s.geometry, s.vertices, s.dimensions, s.constraints s.setPrimaryObject(option=SUPERIMPOSE) p =", "p.edges, p.datums p.PartitionFaceBySketch(faces=pickedFaces, sketch=s) s.unsetPrimaryObject() del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] s = p.edges", "mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=200.0) g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints s.sketchOptions.setValues(viewStyle=AXISYM) s.setPrimaryObject(option=STANDALONE)", "= s.geometry, s.vertices, s.dimensions, s.constraints s.sketchOptions.setValues(viewStyle=AXISYM) s.setPrimaryObject(option=STANDALONE) s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0)) s.FixedConstraint(entity=g[2]) s.rectangle(point1=(0.0,", "p = mdb.models['Model-1'].parts['Part-1'] p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES) s.rectangle(point1=(0.0, 0.0), point2=(3*indent_width, -4*indent_depth))# size of the fine", "mdb.models['Model-1'].parts['Part-1'] p.BaseShell(sketch=s) s.unsetPrimaryObject() p = mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport: 1'].setValues(displayedObject=p) del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1']", "mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] f, e, d = p.faces, p.edges, p.datums t =", "s.unsetPrimaryObject() del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] s = p.edges side1Edges = s.getSequenceFromMask(mask=('[#60 ]',", "sheetSize=200.0) g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints s.sketchOptions.setValues(viewStyle=AXISYM) s.setPrimaryObject(option=STANDALONE) s.ConstructionLine(point1=(0.0,", "-100.0), point2=(0.0, 100.0)) s.FixedConstraint(entity=g[2]) s.rectangle(point1=(0.0, 0.0), point2=(35*indent_width, -t)) p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=AXISYMMETRIC, type=DEFORMABLE_BODY)", "c = s.geometry, s.vertices, s.dimensions, s.constraints s.sketchOptions.setValues(viewStyle=AXISYM) s.setPrimaryObject(option=STANDALONE) s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0)) s.FixedConstraint(entity=g[2])", "100.0)) s.FixedConstraint(entity=g[2]) s.rectangle(point1=(0.0, 0.0), point2=(35*indent_width, -t)) p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=AXISYMMETRIC, type=DEFORMABLE_BODY) p =", "= mdb.models['Model-1'].parts['Part-1'] f = p.faces pickedFaces = f.getSequenceFromMask(mask=('[#1 ]', ), ) e1, d2", "= p.edges side1Edges = s.getSequenceFromMask(mask=('[#60 ]', ), ) p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1']", "mdb.models['Model-1'].parts['Part-1'] s = p.edges side1Edges = s.getSequenceFromMask(mask=('[#60 ]', ), ) p.Surface(side1Edges=side1Edges, name='Surf-spec') #p", "= p.edges, p.datums p.PartitionFaceBySketch(faces=pickedFaces, sketch=s) s.unsetPrimaryObject() del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] s =", "s.setPrimaryObject(option=SUPERIMPOSE) p = mdb.models['Model-1'].parts['Part-1'] p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES) s.rectangle(point1=(0.0, 0.0), point2=(3*indent_width, -4*indent_depth))# size of the", "p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=AXISYMMETRIC, type=DEFORMABLE_BODY) p = mdb.models['Model-1'].parts['Part-1'] p.BaseShell(sketch=s) s.unsetPrimaryObject() p = mdb.models['Model-1'].parts['Part-1']", "mdb.models['Model-1'].Part(name='Part-1', dimensionality=AXISYMMETRIC, type=DEFORMABLE_BODY) p = mdb.models['Model-1'].parts['Part-1'] p.BaseShell(sketch=s) s.unsetPrimaryObject() p = mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport: 1'].setValues(displayedObject=p)", "mdb.models['Model-1'].parts['Part-1'] #s = p.edges #side1Edges = s.getSequenceFromMask(mask=('[#1 ]', ), ) #p.Surface(side1Edges=side1Edges, name='Surf-spec') #p", ") e1, d2 = p.edges, p.datums p.PartitionFaceBySketch(faces=pickedFaces, sketch=s) s.unsetPrimaryObject() del mdb.models['Model-1'].sketches['__profile__'] p =", "t = p.MakeSketchTransform(sketchPlane=f[0], sketchPlaneSide=SIDE1, origin=(0.0, 0.0, 0.0)) s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=181.1, gridSpacing=4.52, transform=t)", "= mdb.models['Model-1'].parts['Part-1'] #e = p.edges #edges = s.getSequenceFromMask(mask=('[#4 ]', ), ) #p.Set(edges=edges, name='Set-spec')", ") p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #s = p.edges #side1Edges = s.getSequenceFromMask(mask=('[#1 ]',", "p = mdb.models['Model-1'].parts['Part-1'] f = p.faces pickedFaces = f.getSequenceFromMask(mask=('[#1 ]', ), ) e1,", "g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints s.sketchOptions.setValues(viewStyle=AXISYM) s.setPrimaryObject(option=STANDALONE) s.ConstructionLine(point1=(0.0, -100.0),", "d2 = p.edges, p.datums p.PartitionFaceBySketch(faces=pickedFaces, sketch=s) s.unsetPrimaryObject() del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] s", "s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=181.1, gridSpacing=4.52, transform=t) g, v, d1, c = s.geometry, s.vertices,", "p.edges side1Edges = s.getSequenceFromMask(mask=('[#60 ]', ), ) p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #s", "p.faces, p.edges, p.datums t = p.MakeSketchTransform(sketchPlane=f[0], sketchPlaneSide=SIDE1, origin=(0.0, 0.0, 0.0)) s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__',", "sheetSize=181.1, gridSpacing=4.52, transform=t) g, v, d1, c = s.geometry, s.vertices, s.dimensions, s.constraints s.setPrimaryObject(option=SUPERIMPOSE)", "f = p.faces pickedFaces = f.getSequenceFromMask(mask=('[#1 ]', ), ) e1, d2 = p.edges,", "origin=(0.0, 0.0, 0.0)) s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=181.1, gridSpacing=4.52, transform=t) g, v, d1, c", "= s.getSequenceFromMask(mask=('[#60 ]', ), ) p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #s = p.edges", "p.PartitionFaceBySketch(faces=pickedFaces, sketch=s) s.unsetPrimaryObject() del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] s = p.edges side1Edges =", "p = mdb.models['Model-1'].parts['Part-1'] p.BaseShell(sketch=s) s.unsetPrimaryObject() p = mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport: 1'].setValues(displayedObject=p) del mdb.models['Model-1'].sketches['__profile__'] p", "p.MakeSketchTransform(sketchPlane=f[0], sketchPlaneSide=SIDE1, origin=(0.0, 0.0, 0.0)) s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=181.1, gridSpacing=4.52, transform=t) g, v,", "]', ), ) #p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #e = p.edges #edges =", "p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #s = p.edges #side1Edges = s.getSequenceFromMask(mask=('[#1 ]', ),", "s.constraints s.setPrimaryObject(option=SUPERIMPOSE) p = mdb.models['Model-1'].parts['Part-1'] p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES) s.rectangle(point1=(0.0, 0.0), point2=(3*indent_width, -4*indent_depth))# size of", "p = mdb.models['Model-1'].parts['Part-1'] s = p.edges side1Edges = s.getSequenceFromMask(mask=('[#60 ]', ), ) p.Surface(side1Edges=side1Edges,", "= s.getSequenceFromMask(mask=('[#1 ]', ), ) #p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #e = p.edges", "= s.geometry, s.vertices, s.dimensions, s.constraints s.setPrimaryObject(option=SUPERIMPOSE) p = mdb.models['Model-1'].parts['Part-1'] p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES) s.rectangle(point1=(0.0, 0.0),", "s.constraints s.sketchOptions.setValues(viewStyle=AXISYM) s.setPrimaryObject(option=STANDALONE) s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0)) s.FixedConstraint(entity=g[2]) s.rectangle(point1=(0.0, 0.0), point2=(35*indent_width, -t)) p", "s.getSequenceFromMask(mask=('[#1 ]', ), ) #p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #e = p.edges #edges", "s.geometry, s.vertices, s.dimensions, s.constraints s.setPrimaryObject(option=SUPERIMPOSE) p = mdb.models['Model-1'].parts['Part-1'] p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES) s.rectangle(point1=(0.0, 0.0), point2=(3*indent_width,", "p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES) s.rectangle(point1=(0.0, 0.0), point2=(3*indent_width, -4*indent_depth))# size of the fine area p =", "#side1Edges = s.getSequenceFromMask(mask=('[#1 ]', ), ) #p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #e =", "-4*indent_depth))# size of the fine area p = mdb.models['Model-1'].parts['Part-1'] f = p.faces pickedFaces", "point2=(35*indent_width, -t)) p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=AXISYMMETRIC, type=DEFORMABLE_BODY) p = mdb.models['Model-1'].parts['Part-1'] p.BaseShell(sketch=s) s.unsetPrimaryObject() p", "mdb.models['Model-1'].parts['Part-1'] f, e, d = p.faces, p.edges, p.datums t = p.MakeSketchTransform(sketchPlane=f[0], sketchPlaneSide=SIDE1, origin=(0.0,", "= p.faces, p.edges, p.datums t = p.MakeSketchTransform(sketchPlane=f[0], sketchPlaneSide=SIDE1, origin=(0.0, 0.0, 0.0)) s =", "0.0), point2=(3*indent_width, -4*indent_depth))# size of the fine area p = mdb.models['Model-1'].parts['Part-1'] f =", "= mdb.models['Model-1'].parts['Part-1'] p.BaseShell(sketch=s) s.unsetPrimaryObject() p = mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport: 1'].setValues(displayedObject=p) del mdb.models['Model-1'].sketches['__profile__'] p =", "= p.edges #side1Edges = s.getSequenceFromMask(mask=('[#1 ]', ), ) #p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1']", "s.vertices, s.dimensions, s.constraints s.sketchOptions.setValues(viewStyle=AXISYM) s.setPrimaryObject(option=STANDALONE) s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0)) s.FixedConstraint(entity=g[2]) s.rectangle(point1=(0.0, 0.0), point2=(35*indent_width,", "s.sketchOptions.setValues(viewStyle=AXISYM) s.setPrimaryObject(option=STANDALONE) s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0)) s.FixedConstraint(entity=g[2]) s.rectangle(point1=(0.0, 0.0), point2=(35*indent_width, -t)) p =", "type=DEFORMABLE_BODY) p = mdb.models['Model-1'].parts['Part-1'] p.BaseShell(sketch=s) s.unsetPrimaryObject() p = mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport: 1'].setValues(displayedObject=p) del mdb.models['Model-1'].sketches['__profile__']", "mdb.models['Model-1'].parts['Part-1'] session.viewports['Viewport: 1'].setValues(displayedObject=p) del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] f, e, d = p.faces,", "= mdb.models['Model-1'].parts['Part-1'] s = p.edges side1Edges = s.getSequenceFromMask(mask=('[#60 ]', ), ) p.Surface(side1Edges=side1Edges, name='Surf-spec')", "mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] s = p.edges side1Edges = s.getSequenceFromMask(mask=('[#60 ]', ), )", "s.FixedConstraint(entity=g[2]) s.rectangle(point1=(0.0, 0.0), point2=(35*indent_width, -t)) p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=AXISYMMETRIC, type=DEFORMABLE_BODY) p = mdb.models['Model-1'].parts['Part-1']", "side1Edges = s.getSequenceFromMask(mask=('[#60 ]', ), ) p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #s =", "v, d1, c = s.geometry, s.vertices, s.dimensions, s.constraints s.setPrimaryObject(option=SUPERIMPOSE) p = mdb.models['Model-1'].parts['Part-1'] p.projectReferencesOntoSketch(sketch=s,", "sketchPlaneSide=SIDE1, origin=(0.0, 0.0, 0.0)) s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=181.1, gridSpacing=4.52, transform=t) g, v, d1,", "del mdb.models['Model-1'].sketches['__profile__'] p = mdb.models['Model-1'].parts['Part-1'] f, e, d = p.faces, p.edges, p.datums t", "g, v, d1, c = s.geometry, s.vertices, s.dimensions, s.constraints s.setPrimaryObject(option=SUPERIMPOSE) p = mdb.models['Model-1'].parts['Part-1']", "d, c = s.geometry, s.vertices, s.dimensions, s.constraints s.sketchOptions.setValues(viewStyle=AXISYM) s.setPrimaryObject(option=STANDALONE) s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0))", "mdb.models['Model-1'].parts['Part-1'] p.projectReferencesOntoSketch(sketch=s, filter=COPLANAR_EDGES) s.rectangle(point1=(0.0, 0.0), point2=(3*indent_width, -4*indent_depth))# size of the fine area p", "name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #s = p.edges #side1Edges = s.getSequenceFromMask(mask=('[#1 ]', ), )", "), ) #p.Surface(side1Edges=side1Edges, name='Surf-spec') #p = mdb.models['Model-1'].parts['Part-1'] #e = p.edges #edges = s.getSequenceFromMask(mask=('[#4", "f, e, d = p.faces, p.edges, p.datums t = p.MakeSketchTransform(sketchPlane=f[0], sketchPlaneSide=SIDE1, origin=(0.0, 0.0,", "point2=(0.0, 100.0)) s.FixedConstraint(entity=g[2]) s.rectangle(point1=(0.0, 0.0), point2=(35*indent_width, -t)) p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=AXISYMMETRIC, type=DEFORMABLE_BODY) p", "0.0)) s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=181.1, gridSpacing=4.52, transform=t) g, v, d1, c = s.geometry," ]
[ "= response.json() raise Exception(json[\"message\"]) def _release_lease(lease_id): _validate_response(requests.post(\"http://localhost:3000/leases/release\", json={\"leaseId\": lease_id})).json() def _create_lease(media_id): lease =", "return drives @contextmanager def lease_first_drive_path(): drives = _get_usb_drives() if len(drives) == 0: yield", "def _validate_response(response): if response.status_code == 200: return response json = response.json() raise Exception(json[\"message\"])", "def _create_lease(media_id): lease = _validate_response(requests.post(\"http://localhost:3000/leases/create\", json={\"mediaId\": media_id})).json() if lease[\"success\"] is False: raise Exception(lease[\"message\"])", "200: return response json = response.json() raise Exception(json[\"message\"]) def _release_lease(lease_id): _validate_response(requests.post(\"http://localhost:3000/leases/release\", json={\"leaseId\": lease_id})).json()", "for media in result: if media[\"provider\"] == \"udisks\": drives.append(media) return drives @contextmanager def", "response.status_code == 200: return response json = response.json() raise Exception(json[\"message\"]) def _release_lease(lease_id): _validate_response(requests.post(\"http://localhost:3000/leases/release\",", "json = response.json() raise Exception(json[\"message\"]) def _release_lease(lease_id): _validate_response(requests.post(\"http://localhost:3000/leases/release\", json={\"leaseId\": lease_id})).json() def _create_lease(media_id): lease", "lease def _get_usb_drives(): drives = [] result = _validate_response(requests.get(\"http://localhost:3000/media\")).json() for media in result:", "media_id})).json() if lease[\"success\"] is False: raise Exception(lease[\"message\"]) return lease def _get_usb_drives(): drives =", "= _validate_response(requests.post(\"http://localhost:3000/leases/create\", json={\"mediaId\": media_id})).json() if lease[\"success\"] is False: raise Exception(lease[\"message\"]) return lease def", "if len(drives) == 0: yield return lease = _create_lease(drives[0][\"id\"]) mount_path = lease[\"mountPath\"] try:", "def _release_lease(lease_id): _validate_response(requests.post(\"http://localhost:3000/leases/release\", json={\"leaseId\": lease_id})).json() def _create_lease(media_id): lease = _validate_response(requests.post(\"http://localhost:3000/leases/create\", json={\"mediaId\": media_id})).json() if", "_release_lease(lease_id): _validate_response(requests.post(\"http://localhost:3000/leases/release\", json={\"leaseId\": lease_id})).json() def _create_lease(media_id): lease = _validate_response(requests.post(\"http://localhost:3000/leases/create\", json={\"mediaId\": media_id})).json() if lease[\"success\"]", "_get_usb_drives() if len(drives) == 0: yield return lease = _create_lease(drives[0][\"id\"]) mount_path = lease[\"mountPath\"]", "\"udisks\": drives.append(media) return drives @contextmanager def lease_first_drive_path(): drives = _get_usb_drives() if len(drives) ==", "json={\"leaseId\": lease_id})).json() def _create_lease(media_id): lease = _validate_response(requests.post(\"http://localhost:3000/leases/create\", json={\"mediaId\": media_id})).json() if lease[\"success\"] is False:", "Exception(lease[\"message\"]) return lease def _get_usb_drives(): drives = [] result = _validate_response(requests.get(\"http://localhost:3000/media\")).json() for media", "drives = [] result = _validate_response(requests.get(\"http://localhost:3000/media\")).json() for media in result: if media[\"provider\"] ==", "response.json() raise Exception(json[\"message\"]) def _release_lease(lease_id): _validate_response(requests.post(\"http://localhost:3000/leases/release\", json={\"leaseId\": lease_id})).json() def _create_lease(media_id): lease = _validate_response(requests.post(\"http://localhost:3000/leases/create\",", "media[\"provider\"] == \"udisks\": drives.append(media) return drives @contextmanager def lease_first_drive_path(): drives = _get_usb_drives() if", "= _get_usb_drives() if len(drives) == 0: yield return lease = _create_lease(drives[0][\"id\"]) mount_path =", "raise Exception(lease[\"message\"]) return lease def _get_usb_drives(): drives = [] result = _validate_response(requests.get(\"http://localhost:3000/media\")).json() for", "== \"udisks\": drives.append(media) return drives @contextmanager def lease_first_drive_path(): drives = _get_usb_drives() if len(drives)", "drives.append(media) return drives @contextmanager def lease_first_drive_path(): drives = _get_usb_drives() if len(drives) == 0:", "_validate_response(requests.post(\"http://localhost:3000/leases/release\", json={\"leaseId\": lease_id})).json() def _create_lease(media_id): lease = _validate_response(requests.post(\"http://localhost:3000/leases/create\", json={\"mediaId\": media_id})).json() if lease[\"success\"] is", "media in result: if media[\"provider\"] == \"udisks\": drives.append(media) return drives @contextmanager def lease_first_drive_path():", "_create_lease(media_id): lease = _validate_response(requests.post(\"http://localhost:3000/leases/create\", json={\"mediaId\": media_id})).json() if lease[\"success\"] is False: raise Exception(lease[\"message\"]) return", "_validate_response(requests.get(\"http://localhost:3000/media\")).json() for media in result: if media[\"provider\"] == \"udisks\": drives.append(media) return drives @contextmanager", "Exception(json[\"message\"]) def _release_lease(lease_id): _validate_response(requests.post(\"http://localhost:3000/leases/release\", json={\"leaseId\": lease_id})).json() def _create_lease(media_id): lease = _validate_response(requests.post(\"http://localhost:3000/leases/create\", json={\"mediaId\": media_id})).json()", "yield return lease = _create_lease(drives[0][\"id\"]) mount_path = lease[\"mountPath\"] try: yield mount_path finally: _release_lease(lease[\"leaseId\"])", "is False: raise Exception(lease[\"message\"]) return lease def _get_usb_drives(): drives = [] result =", "if media[\"provider\"] == \"udisks\": drives.append(media) return drives @contextmanager def lease_first_drive_path(): drives = _get_usb_drives()", "[] result = _validate_response(requests.get(\"http://localhost:3000/media\")).json() for media in result: if media[\"provider\"] == \"udisks\": drives.append(media)", "return lease def _get_usb_drives(): drives = [] result = _validate_response(requests.get(\"http://localhost:3000/media\")).json() for media in", "if lease[\"success\"] is False: raise Exception(lease[\"message\"]) return lease def _get_usb_drives(): drives = []", "= [] result = _validate_response(requests.get(\"http://localhost:3000/media\")).json() for media in result: if media[\"provider\"] == \"udisks\":", "result = _validate_response(requests.get(\"http://localhost:3000/media\")).json() for media in result: if media[\"provider\"] == \"udisks\": drives.append(media) return", "lease_id})).json() def _create_lease(media_id): lease = _validate_response(requests.post(\"http://localhost:3000/leases/create\", json={\"mediaId\": media_id})).json() if lease[\"success\"] is False: raise", "= _validate_response(requests.get(\"http://localhost:3000/media\")).json() for media in result: if media[\"provider\"] == \"udisks\": drives.append(media) return drives", "drives = _get_usb_drives() if len(drives) == 0: yield return lease = _create_lease(drives[0][\"id\"]) mount_path", "def _get_usb_drives(): drives = [] result = _validate_response(requests.get(\"http://localhost:3000/media\")).json() for media in result: if", "contextlib import contextmanager import requests def _validate_response(response): if response.status_code == 200: return response", "== 200: return response json = response.json() raise Exception(json[\"message\"]) def _release_lease(lease_id): _validate_response(requests.post(\"http://localhost:3000/leases/release\", json={\"leaseId\":", "def lease_first_drive_path(): drives = _get_usb_drives() if len(drives) == 0: yield return lease =", "contextmanager import requests def _validate_response(response): if response.status_code == 200: return response json =", "lease_first_drive_path(): drives = _get_usb_drives() if len(drives) == 0: yield return lease = _create_lease(drives[0][\"id\"])", "json={\"mediaId\": media_id})).json() if lease[\"success\"] is False: raise Exception(lease[\"message\"]) return lease def _get_usb_drives(): drives", "@contextmanager def lease_first_drive_path(): drives = _get_usb_drives() if len(drives) == 0: yield return lease", "from contextlib import contextmanager import requests def _validate_response(response): if response.status_code == 200: return", "lease = _validate_response(requests.post(\"http://localhost:3000/leases/create\", json={\"mediaId\": media_id})).json() if lease[\"success\"] is False: raise Exception(lease[\"message\"]) return lease", "import contextmanager import requests def _validate_response(response): if response.status_code == 200: return response json", "False: raise Exception(lease[\"message\"]) return lease def _get_usb_drives(): drives = [] result = _validate_response(requests.get(\"http://localhost:3000/media\")).json()", "result: if media[\"provider\"] == \"udisks\": drives.append(media) return drives @contextmanager def lease_first_drive_path(): drives =", "lease[\"success\"] is False: raise Exception(lease[\"message\"]) return lease def _get_usb_drives(): drives = [] result", "_validate_response(requests.post(\"http://localhost:3000/leases/create\", json={\"mediaId\": media_id})).json() if lease[\"success\"] is False: raise Exception(lease[\"message\"]) return lease def _get_usb_drives():", "in result: if media[\"provider\"] == \"udisks\": drives.append(media) return drives @contextmanager def lease_first_drive_path(): drives", "drives @contextmanager def lease_first_drive_path(): drives = _get_usb_drives() if len(drives) == 0: yield return", "requests def _validate_response(response): if response.status_code == 200: return response json = response.json() raise", "raise Exception(json[\"message\"]) def _release_lease(lease_id): _validate_response(requests.post(\"http://localhost:3000/leases/release\", json={\"leaseId\": lease_id})).json() def _create_lease(media_id): lease = _validate_response(requests.post(\"http://localhost:3000/leases/create\", json={\"mediaId\":", "_get_usb_drives(): drives = [] result = _validate_response(requests.get(\"http://localhost:3000/media\")).json() for media in result: if media[\"provider\"]", "len(drives) == 0: yield return lease = _create_lease(drives[0][\"id\"]) mount_path = lease[\"mountPath\"] try: yield", "return response json = response.json() raise Exception(json[\"message\"]) def _release_lease(lease_id): _validate_response(requests.post(\"http://localhost:3000/leases/release\", json={\"leaseId\": lease_id})).json() def", "== 0: yield return lease = _create_lease(drives[0][\"id\"]) mount_path = lease[\"mountPath\"] try: yield mount_path", "0: yield return lease = _create_lease(drives[0][\"id\"]) mount_path = lease[\"mountPath\"] try: yield mount_path finally:", "if response.status_code == 200: return response json = response.json() raise Exception(json[\"message\"]) def _release_lease(lease_id):", "import requests def _validate_response(response): if response.status_code == 200: return response json = response.json()", "response json = response.json() raise Exception(json[\"message\"]) def _release_lease(lease_id): _validate_response(requests.post(\"http://localhost:3000/leases/release\", json={\"leaseId\": lease_id})).json() def _create_lease(media_id):", "_validate_response(response): if response.status_code == 200: return response json = response.json() raise Exception(json[\"message\"]) def" ]
[ "s.split(\".\"), items) self.__add_edge_to(result, node1, node2) each_line = self.file.readline() return result @classmethod def __add_edge_to(cls,", "self.partition.borders: shortest_paths = single_source_shortest_path_length(initial_graph, each_node - 1) for each_other_node in self.partition.borders: if each_other_node", "self.get_inner_nodes() print(\"Partition %d\" % self.pid) print(\"\\tInner nodes = %d = %s\" % (len(inners),", "x: int, y: int, weight: int): self.x = x self.y = y self.weight", "edge: Edge): self.edges.append(edge) self.__add_node_from_edge_if_in(edge.x, edge.y) self.__add_node_from_edge_if_in(edge.y, edge.x) def __add_node_from_edge_if_in(self, x: Node, edge_peer: Node):", "self.x = x self.y = y self.weight = weight class TraversalGraphBuilder: def __init__(self,", "def get_initial_graph(self) -> coo_matrix: return CooMatrixBuilder(self.all_nodes).execute() class FragmentProcessor: \"\"\" Assuming that a fragment", "Node: def __init__(self, partition: int, index: int): self.partition = partition self.index = index", "return self class Main: def __init__(self, configuration: ProgramConfiguration): self.configuration = configuration def execute(self):", "self.args = args def input_basename(self) -> str: return self.args[1] def nr_fragments(self) -> int:", "for each_fragment_id in range(0, self.configuration.nr_fragments()): with open(\"%s_%d.txt\" % (self.configuration.input_basename(), each_fragment_id), \"rt\") as f:", "self.__add_edge_to(result, node1, node2) each_line = self.file.readline() return result @classmethod def __add_edge_to(cls, d: PartitionDescriptor,", "for each_edge in weighted_edges: f.write(\"%d %d %d\\n\" % (each_edge.x, each_edge.y, each_edge.weight)) # ================================================================================", "result @classmethod def __add_edge_to(cls, d: PartitionDescriptor, x: (str, str), y: (str, str)): nx", "__str__(self) -> str: return \"%d.%d\" % (self.partition, self.index) class Edge: def __init__(self, node1:", "def __add_node_from_edge_if_in(self, x: Node, edge_peer: Node): if x.partition == self.pid: self.all_nodes.add(x.index) if edge_peer.partition", "self.borders)) print(\"\\tQ%% = %d\" % (100.0 * self.q())) def get_initial_graph(self) -> coo_matrix: return", "\"\"\"User arguments Verifies that the program is supplied enough arguments and provides one", "is supplied enough arguments and provides one function for each argument type. \"\"\"", "v = [] nodes = sorted(self.nodes) for each_node in nodes: for each_other_node in", "def __add_edge_to(cls, d: PartitionDescriptor, x: (str, str), y: (str, str)): nx = Node(int(x[0]),", "1) j.append(each_other_node - 1) v.append(1) npi = np.array(i) npj = np.array(j) npv =", "= [] nodes = sorted(self.nodes) for each_node in nodes: for each_other_node in nodes:", "self.__add_node_from_edge_if_in(edge.x, edge.y) self.__add_node_from_edge_if_in(edge.y, edge.x) def __add_node_from_edge_if_in(self, x: Node, edge_peer: Node): if x.partition ==", "\"%d.%d\" % (self.partition, self.index) class Edge: def __init__(self, node1: Node, node2: Node): self.x", "to this program are: * The base name of fragment files * The", "node2 def __str__(self) -> str: return \"(%s):(%s)\" % (self.x, self.y) class CooMatrixBuilder: def", "PartitionDescriptor, x: (str, str), y: (str, str)): nx = Node(int(x[0]), int(x[1])) ny =", "CooMatrixBuilder(self.all_nodes).execute() class FragmentProcessor: \"\"\" Assuming that a fragment name is <basename>_<n>.txt, creates the", "% (nr_nodes, nr_nodes, len(weighted_edges))) for each_edge in weighted_edges: f.write(\"%d %d %d\\n\" % (each_edge.x,", "int, weight: int): self.x = x self.y = y self.weight = weight class", "in self.all_nodes: if each_node not in self.borders: result.add(each_node) return result else: return self.inner_nodes", "= %s\" % (len(inners), inners)) print(\"\\tBorders = %d = %s\" % (len(self.borders), self.borders))", "\"\"\" Reads a collection of partitions, created by BuildFragments, to produce their traversal", "j.append(each_other_node - 1) v.append(1) npi = np.array(i) npj = np.array(j) npv = np.array(v)", "self.pid: self.all_nodes.add(x.index) if edge_peer.partition != self.pid: self.borders.add(x.index) def get_inner_nodes(self) -> Set[int]: if len(self.inner_nodes)", "shape=(nr_nodes, nr_nodes)) class PartitionDescriptor: def __init__(self, partition_id: int): self.pid = partition_id self.borders: Set[int]", "self.borders.add(x.index) def get_inner_nodes(self) -> Set[int]: if len(self.inner_nodes) == 0: result = set() for", "(npi, npj)), shape=(nr_nodes, nr_nodes)) class PartitionDescriptor: def __init__(self, partition_id: int): self.pid = partition_id", "%d = %s\" % (len(self.borders), self.borders)) print(\"\\tQ%% = %d\" % (100.0 * self.q()))", "PartitionDescriptor(self.pid) each_line = self.file.readline() while each_line: items = each_line.replace(\"(\", \"\").replace(\")\", \"\").split(\":\") if len(items)", "%d\\n\" % (nr_nodes, nr_nodes, len(weighted_edges))) for each_edge in weighted_edges: f.write(\"%d %d %d\\n\" %", "return CooMatrixBuilder(self.all_nodes).execute() class FragmentProcessor: \"\"\" Assuming that a fragment name is <basename>_<n>.txt, creates", "of fragment files * The number of fragments to process Output is a", "self.file.readline() while each_line: items = each_line.replace(\"(\", \"\").replace(\")\", \"\").split(\":\") if len(items) == 2: (node1,", "each argument type. \"\"\" def __init__(self, args: List[str]): if len(args) != 3: print(\"Usage:", "return coo_matrix((npv, (npi, npj)), shape=(nr_nodes, nr_nodes)) class PartitionDescriptor: def __init__(self, partition_id: int): self.pid", "each_line = self.file.readline() return result @classmethod def __add_edge_to(cls, d: PartitionDescriptor, x: (str, str),", "partition_id: int): self.pid = partition_id self.borders: Set[int] = set() self.all_nodes: Set[int] = set()", "a collection of mtx files, with the same base name, suffixed by the", "each_node in self.all_nodes: if each_node not in self.borders: result.add(each_node) return result else: return", "matrix coordinate pattern symmetric\\n\") f.write(\"%d %d %d\\n\" % (nr_nodes, nr_nodes, len(weighted_edges))) for each_edge", "from scipy.sparse import coo_matrix from sklearn.utils.graph import single_source_shortest_path_length class ProgramConfiguration: \"\"\"User arguments Verifies", "% (len(self.borders), self.borders)) print(\"\\tQ%% = %d\" % (100.0 * self.q())) def get_initial_graph(self) ->", "scipy.sparse import coo_matrix from sklearn.utils.graph import single_source_shortest_path_length class ProgramConfiguration: \"\"\"User arguments Verifies that", "%s\" % (len(inners), inners)) print(\"\\tBorders = %d = %s\" % (len(self.borders), self.borders)) print(\"\\tQ%%", "creates the associated fragment information. \"\"\" def __init__(self, fragment_file: TextIO, partition_id: int): self.file", "shortest_distance) self.edges.append(edge) if each_node > self.max_node: self.max_node = each_node return self class Main:", "add_edge(self, edge: Edge): self.edges.append(edge) self.__add_node_from_edge_if_in(edge.x, edge.y) self.__add_node_from_edge_if_in(edge.y, edge.x) def __add_node_from_edge_if_in(self, x: Node, edge_peer:", "self.edges.append(edge) if each_node > self.max_node: self.max_node = each_node return self class Main: def", "in nodes: for each_other_node in nodes: if each_other_node > each_node: i.append(each_node - 1)", "def __init__(self, partition_id: int): self.pid = partition_id self.borders: Set[int] = set() self.all_nodes: Set[int]", "weight: int): self.x = x self.y = y self.weight = weight class TraversalGraphBuilder:", "int: return int(self.args[2]) class Node: def __init__(self, partition: int, index: int): self.partition =", "class Node: def __init__(self, partition: int, index: int): self.partition = partition self.index =", "f.write(\"%d %d %d\\n\" % (nr_nodes, nr_nodes, len(weighted_edges))) for each_edge in weighted_edges: f.write(\"%d %d", "List[WeightedEdge]): with open(file_name, \"wt\") as f: f.write(\"%%MatrixMarket matrix coordinate pattern symmetric\\n\") f.write(\"%d %d", "self.pid = partition_id self.borders: Set[int] = set() self.all_nodes: Set[int] = set() self.inner_nodes: Set[int]", "function for each argument type. \"\"\" def __init__(self, args: List[str]): if len(args) !=", "self.max_node = each_node return self class Main: def __init__(self, configuration: ProgramConfiguration): self.configuration =", "(self.partition, self.index) class Edge: def __init__(self, node1: Node, node2: Node): self.x = node1", "__add_edge_to(cls, d: PartitionDescriptor, x: (str, str), y: (str, str)): nx = Node(int(x[0]), int(x[1]))", "nodes: Set[int]): self.nodes = nodes def execute(self) -> coo_matrix: i = [] j", "pattern symmetric\\n\") f.write(\"%d %d %d\\n\" % (nr_nodes, nr_nodes, len(weighted_edges))) for each_edge in weighted_edges:", "node1: Node, node2: Node): self.x = node1 self.y = node2 def __str__(self) ->", "each_other_node, shortest_distance) self.edges.append(edge) if each_node > self.max_node: self.max_node = each_node return self class", "type. \"\"\" def __init__(self, args: List[str]): if len(args) != 3: print(\"Usage: %s <fragments", "= np.array(i) npj = np.array(j) npv = np.array(v) nr_nodes = nodes[-1] return coo_matrix((npv,", "open(\"%s_%d.txt\" % (self.configuration.input_basename(), each_fragment_id), \"rt\") as f: descriptor = FragmentProcessor(f, each_fragment_id).get_descriptor() descriptor.summarize() tg", "x self.y = y self.weight = weight class TraversalGraphBuilder: def __init__(self, partition: PartitionDescriptor):", "by BuildFragments, to produce their traversal graphs. Input to this program are: *", "self.max_node: self.max_node = each_node return self class Main: def __init__(self, configuration: ProgramConfiguration): self.configuration", "def __write_graph_into(self, file_name: str, nr_nodes: int, weighted_edges: List[WeightedEdge]): with open(file_name, \"wt\") as f:", "class Edge: def __init__(self, node1: Node, node2: Node): self.x = node1 self.y =", "with open(file_name, \"wt\") as f: f.write(\"%%MatrixMarket matrix coordinate pattern symmetric\\n\") f.write(\"%d %d %d\\n\"", "(nr_nodes, nr_nodes, len(weighted_edges))) for each_edge in weighted_edges: f.write(\"%d %d %d\\n\" % (each_edge.x, each_edge.y,", "[] def add_edge(self, edge: Edge): self.edges.append(edge) self.__add_node_from_edge_if_in(edge.x, edge.y) self.__add_node_from_edge_if_in(edge.y, edge.x) def __add_node_from_edge_if_in(self, x:", "class PartitionDescriptor: def __init__(self, partition_id: int): self.pid = partition_id self.borders: Set[int] = set()", "argument type. \"\"\" def __init__(self, args: List[str]): if len(args) != 3: print(\"Usage: %s", "program is supplied enough arguments and provides one function for each argument type.", "PartitionDescriptor: result = PartitionDescriptor(self.pid) each_line = self.file.readline() while each_line: items = each_line.replace(\"(\", \"\").replace(\")\",", "partition: PartitionDescriptor): self.partition = partition self.max_node = 0 self.edges: List[WeightedEdge] = [] def", "return \"%d.%d\" % (self.partition, self.index) class Edge: def __init__(self, node1: Node, node2: Node):", "nr_nodes)) class PartitionDescriptor: def __init__(self, partition_id: int): self.pid = partition_id self.borders: Set[int] =", "[] v = [] nodes = sorted(self.nodes) for each_node in nodes: for each_other_node", "each_fragment_id in range(0, self.configuration.nr_fragments()): with open(\"%s_%d.txt\" % (self.configuration.input_basename(), each_fragment_id), \"rt\") as f: descriptor", "(str, str)): nx = Node(int(x[0]), int(x[1])) ny = Node(int(y[0]), int(y[1])) d.add_edge(Edge(nx, ny)) class", "> each_node: i.append(each_node - 1) j.append(each_other_node - 1) v.append(1) npi = np.array(i) npj", "f.write(\"%%MatrixMarket matrix coordinate pattern symmetric\\n\") f.write(\"%d %d %d\\n\" % (nr_nodes, nr_nodes, len(weighted_edges))) for", "self class Main: def __init__(self, configuration: ProgramConfiguration): self.configuration = configuration def execute(self): for", "def __init__(self, configuration: ProgramConfiguration): self.configuration = configuration def execute(self): for each_fragment_id in range(0,", "def __init__(self, partition: int, index: int): self.partition = partition self.index = index def", "open(file_name, \"wt\") as f: f.write(\"%%MatrixMarket matrix coordinate pattern symmetric\\n\") f.write(\"%d %d %d\\n\" %", "each_node in nodes: for each_other_node in nodes: if each_other_node > each_node: i.append(each_node -", "self.edges.append(edge) self.__add_node_from_edge_if_in(edge.x, edge.y) self.__add_node_from_edge_if_in(edge.y, edge.x) def __add_node_from_edge_if_in(self, x: Node, edge_peer: Node): if x.partition", "= TraversalGraphBuilder(descriptor).create_graph() self.__write_graph_into(\"%s_%dT.mtx\" % (self.configuration.input_basename(), each_fragment_id), tg.max_node, tg.edges) @classmethod def __write_graph_into(self, file_name: str,", "return self.args[1] def nr_fragments(self) -> int: return int(self.args[2]) class Node: def __init__(self, partition:", "WeightedEdge: def __init__(self, x: int, y: int, weight: int): self.x = x self.y", "== 0: result = set() for each_node in self.all_nodes: if each_node not in", "exit(1) self.args = args def input_basename(self) -> str: return self.args[1] def nr_fragments(self) ->", "0: result = set() for each_node in self.all_nodes: if each_node not in self.borders:", "ProgramConfiguration: \"\"\"User arguments Verifies that the program is supplied enough arguments and provides", "= each_line.replace(\"(\", \"\").replace(\")\", \"\").split(\":\") if len(items) == 2: (node1, node2) = map(lambda s:", "each_node: i.append(each_node - 1) j.append(each_other_node - 1) v.append(1) npi = np.array(i) npj =", "result else: return self.inner_nodes def q(self) -> float: return float(len(self.borders)) / float(len(self.all_nodes)) def", "np.array(j) npv = np.array(v) nr_nodes = nodes[-1] return coo_matrix((npv, (npi, npj)), shape=(nr_nodes, nr_nodes))", "coo_matrix from sklearn.utils.graph import single_source_shortest_path_length class ProgramConfiguration: \"\"\"User arguments Verifies that the program", "- 1) for each_other_node in self.partition.borders: if each_other_node > each_node: shortest_distance = shortest_paths[each_other_node", "= set() self.inner_nodes: Set[int] = set() self.edges = [] def add_edge(self, edge: Edge):", "files, with the same base name, suffixed by the fragment number and a", "Edge: def __init__(self, node1: Node, node2: Node): self.x = node1 self.y = node2", "as f: f.write(\"%%MatrixMarket matrix coordinate pattern symmetric\\n\") f.write(\"%d %d %d\\n\" % (nr_nodes, nr_nodes,", "that a fragment name is <basename>_<n>.txt, creates the associated fragment information. \"\"\" def", "are: * The base name of fragment files * The number of fragments", "get_initial_graph(self) -> coo_matrix: return CooMatrixBuilder(self.all_nodes).execute() class FragmentProcessor: \"\"\" Assuming that a fragment name", "a fragment name is <basename>_<n>.txt, creates the associated fragment information. \"\"\" def __init__(self,", "create_graph(self): initial_graph = self.partition.get_initial_graph() for each_node in self.partition.borders: shortest_paths = single_source_shortest_path_length(initial_graph, each_node -", "WeightedEdge(each_node, each_other_node, shortest_distance) self.edges.append(edge) if each_node > self.max_node: self.max_node = each_node return self", "self.inner_nodes: Set[int] = set() self.edges = [] def add_edge(self, edge: Edge): self.edges.append(edge) self.__add_node_from_edge_if_in(edge.x,", "coordinate pattern symmetric\\n\") f.write(\"%d %d %d\\n\" % (nr_nodes, nr_nodes, len(weighted_edges))) for each_edge in", "(len(self.borders), self.borders)) print(\"\\tQ%% = %d\" % (100.0 * self.q())) def get_initial_graph(self) -> coo_matrix:", "= [] def create_graph(self): initial_graph = self.partition.get_initial_graph() for each_node in self.partition.borders: shortest_paths =", "y: int, weight: int): self.x = x self.y = y self.weight = weight", "= fragment_file self.pid = partition_id def get_descriptor(self) -> PartitionDescriptor: result = PartitionDescriptor(self.pid) each_line", "i = [] j = [] v = [] nodes = sorted(self.nodes) for", "each_line: items = each_line.replace(\"(\", \"\").replace(\")\", \"\").split(\":\") if len(items) == 2: (node1, node2) =", "name of fragment files * The number of fragments to process Output is", "-> float: return float(len(self.borders)) / float(len(self.all_nodes)) def summarize(self): inners = self.get_inner_nodes() print(\"Partition %d\"", "int(self.args[2]) class Node: def __init__(self, partition: int, index: int): self.partition = partition self.index", "each_node return self class Main: def __init__(self, configuration: ProgramConfiguration): self.configuration = configuration def", "weighted_edges: List[WeightedEdge]): with open(file_name, \"wt\") as f: f.write(\"%%MatrixMarket matrix coordinate pattern symmetric\\n\") f.write(\"%d", "self.y = node2 def __str__(self) -> str: return \"(%s):(%s)\" % (self.x, self.y) class", "= x self.y = y self.weight = weight class TraversalGraphBuilder: def __init__(self, partition:", "3: print(\"Usage: %s <fragments base name> <number of fragments>\" % args[0]) exit(1) self.args", "T. \"\"\" from sys import argv from typing import List, TextIO, Set import", "with open(\"%s_%d.txt\" % (self.configuration.input_basename(), each_fragment_id), \"rt\") as f: descriptor = FragmentProcessor(f, each_fragment_id).get_descriptor() descriptor.summarize()", "= nodes def execute(self) -> coo_matrix: i = [] j = [] v", "TraversalGraphBuilder(descriptor).create_graph() self.__write_graph_into(\"%s_%dT.mtx\" % (self.configuration.input_basename(), each_fragment_id), tg.max_node, tg.edges) @classmethod def __write_graph_into(self, file_name: str, nr_nodes:", "len(weighted_edges))) for each_edge in weighted_edges: f.write(\"%d %d %d\\n\" % (each_edge.x, each_edge.y, each_edge.weight)) #", "input_basename(self) -> str: return self.args[1] def nr_fragments(self) -> int: return int(self.args[2]) class Node:", "str: return \"%d.%d\" % (self.partition, self.index) class Edge: def __init__(self, node1: Node, node2:", "= %d = %s\" % (len(self.borders), self.borders)) print(\"\\tQ%% = %d\" % (100.0 *", "print(\"\\tQ%% = %d\" % (100.0 * self.q())) def get_initial_graph(self) -> coo_matrix: return CooMatrixBuilder(self.all_nodes).execute()", "by the fragment number and a capital T. \"\"\" from sys import argv", "= each_node return self class Main: def __init__(self, configuration: ProgramConfiguration): self.configuration = configuration", "from typing import List, TextIO, Set import numpy as np from scipy.sparse import", "same base name, suffixed by the fragment number and a capital T. \"\"\"", "* self.q())) def get_initial_graph(self) -> coo_matrix: return CooMatrixBuilder(self.all_nodes).execute() class FragmentProcessor: \"\"\" Assuming that", "number of fragments to process Output is a collection of mtx files, with", "(self.configuration.input_basename(), each_fragment_id), tg.max_node, tg.edges) @classmethod def __write_graph_into(self, file_name: str, nr_nodes: int, weighted_edges: List[WeightedEdge]):", "return self.inner_nodes def q(self) -> float: return float(len(self.borders)) / float(len(self.all_nodes)) def summarize(self): inners", "= PartitionDescriptor(self.pid) each_line = self.file.readline() while each_line: items = each_line.replace(\"(\", \"\").replace(\")\", \"\").split(\":\") if", "each_fragment_id).get_descriptor() descriptor.summarize() tg = TraversalGraphBuilder(descriptor).create_graph() self.__write_graph_into(\"%s_%dT.mtx\" % (self.configuration.input_basename(), each_fragment_id), tg.max_node, tg.edges) @classmethod def", "class WeightedEdge: def __init__(self, x: int, y: int, weight: int): self.x = x", "self.partition = partition self.max_node = 0 self.edges: List[WeightedEdge] = [] def create_graph(self): initial_graph", "fragment files * The number of fragments to process Output is a collection", "f: descriptor = FragmentProcessor(f, each_fragment_id).get_descriptor() descriptor.summarize() tg = TraversalGraphBuilder(descriptor).create_graph() self.__write_graph_into(\"%s_%dT.mtx\" % (self.configuration.input_basename(), each_fragment_id),", "coo_matrix: return CooMatrixBuilder(self.all_nodes).execute() class FragmentProcessor: \"\"\" Assuming that a fragment name is <basename>_<n>.txt,", "nr_fragments(self) -> int: return int(self.args[2]) class Node: def __init__(self, partition: int, index: int):", "= [] j = [] v = [] nodes = sorted(self.nodes) for each_node", "Node): if x.partition == self.pid: self.all_nodes.add(x.index) if edge_peer.partition != self.pid: self.borders.add(x.index) def get_inner_nodes(self)", "\"\"\" def __init__(self, args: List[str]): if len(args) != 3: print(\"Usage: %s <fragments base", "Reads a collection of partitions, created by BuildFragments, to produce their traversal graphs.", "Node(int(x[0]), int(x[1])) ny = Node(int(y[0]), int(y[1])) d.add_edge(Edge(nx, ny)) class WeightedEdge: def __init__(self, x:", "@classmethod def __write_graph_into(self, file_name: str, nr_nodes: int, weighted_edges: List[WeightedEdge]): with open(file_name, \"wt\") as", "numpy as np from scipy.sparse import coo_matrix from sklearn.utils.graph import single_source_shortest_path_length class ProgramConfiguration:", "FragmentProcessor(f, each_fragment_id).get_descriptor() descriptor.summarize() tg = TraversalGraphBuilder(descriptor).create_graph() self.__write_graph_into(\"%s_%dT.mtx\" % (self.configuration.input_basename(), each_fragment_id), tg.max_node, tg.edges) @classmethod", "tg.edges) @classmethod def __write_graph_into(self, file_name: str, nr_nodes: int, weighted_edges: List[WeightedEdge]): with open(file_name, \"wt\")", "float(len(self.borders)) / float(len(self.all_nodes)) def summarize(self): inners = self.get_inner_nodes() print(\"Partition %d\" % self.pid) print(\"\\tInner", "Output is a collection of mtx files, with the same base name, suffixed", "Set[int] = set() self.all_nodes: Set[int] = set() self.inner_nodes: Set[int] = set() self.edges =", "npj = np.array(j) npv = np.array(v) nr_nodes = nodes[-1] return coo_matrix((npv, (npi, npj)),", "the program is supplied enough arguments and provides one function for each argument", "nodes[-1] return coo_matrix((npv, (npi, npj)), shape=(nr_nodes, nr_nodes)) class PartitionDescriptor: def __init__(self, partition_id: int):", "<fragments base name> <number of fragments>\" % args[0]) exit(1) self.args = args def", "self.borders: result.add(each_node) return result else: return self.inner_nodes def q(self) -> float: return float(len(self.borders))", "each_line = self.file.readline() while each_line: items = each_line.replace(\"(\", \"\").replace(\")\", \"\").split(\":\") if len(items) ==", "def __str__(self) -> str: return \"%d.%d\" % (self.partition, self.index) class Edge: def __init__(self,", "(self.configuration.input_basename(), each_fragment_id), \"rt\") as f: descriptor = FragmentProcessor(f, each_fragment_id).get_descriptor() descriptor.summarize() tg = TraversalGraphBuilder(descriptor).create_graph()", "(str, str), y: (str, str)): nx = Node(int(x[0]), int(x[1])) ny = Node(int(y[0]), int(y[1]))", "= Node(int(x[0]), int(x[1])) ny = Node(int(y[0]), int(y[1])) d.add_edge(Edge(nx, ny)) class WeightedEdge: def __init__(self,", "__add_node_from_edge_if_in(self, x: Node, edge_peer: Node): if x.partition == self.pid: self.all_nodes.add(x.index) if edge_peer.partition !=", "this program are: * The base name of fragment files * The number", "= FragmentProcessor(f, each_fragment_id).get_descriptor() descriptor.summarize() tg = TraversalGraphBuilder(descriptor).create_graph() self.__write_graph_into(\"%s_%dT.mtx\" % (self.configuration.input_basename(), each_fragment_id), tg.max_node, tg.edges)", "def __init__(self, x: int, y: int, weight: int): self.x = x self.y =", "as f: descriptor = FragmentProcessor(f, each_fragment_id).get_descriptor() descriptor.summarize() tg = TraversalGraphBuilder(descriptor).create_graph() self.__write_graph_into(\"%s_%dT.mtx\" % (self.configuration.input_basename(),", "PartitionDescriptor: def __init__(self, partition_id: int): self.pid = partition_id self.borders: Set[int] = set() self.all_nodes:", "!= 3: print(\"Usage: %s <fragments base name> <number of fragments>\" % args[0]) exit(1)", "and provides one function for each argument type. \"\"\" def __init__(self, args: List[str]):", "base name, suffixed by the fragment number and a capital T. \"\"\" from", "= partition_id self.borders: Set[int] = set() self.all_nodes: Set[int] = set() self.inner_nodes: Set[int] =", "file_name: str, nr_nodes: int, weighted_edges: List[WeightedEdge]): with open(file_name, \"wt\") as f: f.write(\"%%MatrixMarket matrix", "edge.x) def __add_node_from_edge_if_in(self, x: Node, edge_peer: Node): if x.partition == self.pid: self.all_nodes.add(x.index) if", "List, TextIO, Set import numpy as np from scipy.sparse import coo_matrix from sklearn.utils.graph", "nodes: if each_other_node > each_node: i.append(each_node - 1) j.append(each_other_node - 1) v.append(1) npi", "npv = np.array(v) nr_nodes = nodes[-1] return coo_matrix((npv, (npi, npj)), shape=(nr_nodes, nr_nodes)) class", "d: PartitionDescriptor, x: (str, str), y: (str, str)): nx = Node(int(x[0]), int(x[1])) ny", "self.all_nodes: if each_node not in self.borders: result.add(each_node) return result else: return self.inner_nodes def", "self.args[1] def nr_fragments(self) -> int: return int(self.args[2]) class Node: def __init__(self, partition: int,", "the associated fragment information. \"\"\" def __init__(self, fragment_file: TextIO, partition_id: int): self.file =", "0 self.edges: List[WeightedEdge] = [] def create_graph(self): initial_graph = self.partition.get_initial_graph() for each_node in", "a capital T. \"\"\" from sys import argv from typing import List, TextIO,", "fragment name is <basename>_<n>.txt, creates the associated fragment information. \"\"\" def __init__(self, fragment_file:", "1] edge = WeightedEdge(each_node, each_other_node, shortest_distance) self.edges.append(edge) if each_node > self.max_node: self.max_node =", "% args[0]) exit(1) self.args = args def input_basename(self) -> str: return self.args[1] def", "__str__(self) -> str: return \"(%s):(%s)\" % (self.x, self.y) class CooMatrixBuilder: def __init__(self, nodes:", "= set() for each_node in self.all_nodes: if each_node not in self.borders: result.add(each_node) return", "suffixed by the fragment number and a capital T. \"\"\" from sys import", "def __init__(self, args: List[str]): if len(args) != 3: print(\"Usage: %s <fragments base name>", "self.partition = partition self.index = index def __str__(self) -> str: return \"%d.%d\" %", "__init__(self, node1: Node, node2: Node): self.x = node1 self.y = node2 def __str__(self)", "each_other_node in self.partition.borders: if each_other_node > each_node: shortest_distance = shortest_paths[each_other_node - 1] edge", "descriptor.summarize() tg = TraversalGraphBuilder(descriptor).create_graph() self.__write_graph_into(\"%s_%dT.mtx\" % (self.configuration.input_basename(), each_fragment_id), tg.max_node, tg.edges) @classmethod def __write_graph_into(self,", "str), y: (str, str)): nx = Node(int(x[0]), int(x[1])) ny = Node(int(y[0]), int(y[1])) d.add_edge(Edge(nx,", "Set import numpy as np from scipy.sparse import coo_matrix from sklearn.utils.graph import single_source_shortest_path_length", "The number of fragments to process Output is a collection of mtx files,", "% (self.x, self.y) class CooMatrixBuilder: def __init__(self, nodes: Set[int]): self.nodes = nodes def", "[] j = [] v = [] nodes = sorted(self.nodes) for each_node in", "of partitions, created by BuildFragments, to produce their traversal graphs. Input to this", "associated fragment information. \"\"\" def __init__(self, fragment_file: TextIO, partition_id: int): self.file = fragment_file", "List[str]): if len(args) != 3: print(\"Usage: %s <fragments base name> <number of fragments>\"", "\"(%s):(%s)\" % (self.x, self.y) class CooMatrixBuilder: def __init__(self, nodes: Set[int]): self.nodes = nodes", "def __init__(self, fragment_file: TextIO, partition_id: int): self.file = fragment_file self.pid = partition_id def", "\"\"\" def __init__(self, fragment_file: TextIO, partition_id: int): self.file = fragment_file self.pid = partition_id", "= np.array(v) nr_nodes = nodes[-1] return coo_matrix((npv, (npi, npj)), shape=(nr_nodes, nr_nodes)) class PartitionDescriptor:", "s: s.split(\".\"), items) self.__add_edge_to(result, node1, node2) each_line = self.file.readline() return result @classmethod def", "def __init__(self, nodes: Set[int]): self.nodes = nodes def execute(self) -> coo_matrix: i =", "-> Set[int]: if len(self.inner_nodes) == 0: result = set() for each_node in self.all_nodes:", "configuration def execute(self): for each_fragment_id in range(0, self.configuration.nr_fragments()): with open(\"%s_%d.txt\" % (self.configuration.input_basename(), each_fragment_id),", "- 1] edge = WeightedEdge(each_node, each_other_node, shortest_distance) self.edges.append(edge) if each_node > self.max_node: self.max_node", "provides one function for each argument type. \"\"\" def __init__(self, args: List[str]): if", "and a capital T. \"\"\" from sys import argv from typing import List,", "self.file.readline() return result @classmethod def __add_edge_to(cls, d: PartitionDescriptor, x: (str, str), y: (str,", "return result @classmethod def __add_edge_to(cls, d: PartitionDescriptor, x: (str, str), y: (str, str)):", "y: (str, str)): nx = Node(int(x[0]), int(x[1])) ny = Node(int(y[0]), int(y[1])) d.add_edge(Edge(nx, ny))", "self.pid) print(\"\\tInner nodes = %d = %s\" % (len(inners), inners)) print(\"\\tBorders = %d", "fragments to process Output is a collection of mtx files, with the same", "each_fragment_id), \"rt\") as f: descriptor = FragmentProcessor(f, each_fragment_id).get_descriptor() descriptor.summarize() tg = TraversalGraphBuilder(descriptor).create_graph() self.__write_graph_into(\"%s_%dT.mtx\"", "information. \"\"\" def __init__(self, fragment_file: TextIO, partition_id: int): self.file = fragment_file self.pid =", "each_other_node > each_node: shortest_distance = shortest_paths[each_other_node - 1] edge = WeightedEdge(each_node, each_other_node, shortest_distance)", "name> <number of fragments>\" % args[0]) exit(1) self.args = args def input_basename(self) ->", "= [] v = [] nodes = sorted(self.nodes) for each_node in nodes: for", "set() self.all_nodes: Set[int] = set() self.inner_nodes: Set[int] = set() self.edges = [] def", "__init__(self, partition_id: int): self.pid = partition_id self.borders: Set[int] = set() self.all_nodes: Set[int] =", "is a collection of mtx files, with the same base name, suffixed by", "self.pid: self.borders.add(x.index) def get_inner_nodes(self) -> Set[int]: if len(self.inner_nodes) == 0: result = set()", "Set[int]): self.nodes = nodes def execute(self) -> coo_matrix: i = [] j =", "node2) each_line = self.file.readline() return result @classmethod def __add_edge_to(cls, d: PartitionDescriptor, x: (str,", "__init__(self, fragment_file: TextIO, partition_id: int): self.file = fragment_file self.pid = partition_id def get_descriptor(self)", "self.partition.get_initial_graph() for each_node in self.partition.borders: shortest_paths = single_source_shortest_path_length(initial_graph, each_node - 1) for each_other_node", "len(self.inner_nodes) == 0: result = set() for each_node in self.all_nodes: if each_node not", "\"\"\" Assuming that a fragment name is <basename>_<n>.txt, creates the associated fragment information.", "import single_source_shortest_path_length class ProgramConfiguration: \"\"\"User arguments Verifies that the program is supplied enough", "TraversalGraphBuilder: def __init__(self, partition: PartitionDescriptor): self.partition = partition self.max_node = 0 self.edges: List[WeightedEdge]", "!= self.pid: self.borders.add(x.index) def get_inner_nodes(self) -> Set[int]: if len(self.inner_nodes) == 0: result =", "= single_source_shortest_path_length(initial_graph, each_node - 1) for each_other_node in self.partition.borders: if each_other_node > each_node:", "import coo_matrix from sklearn.utils.graph import single_source_shortest_path_length class ProgramConfiguration: \"\"\"User arguments Verifies that the", "their traversal graphs. Input to this program are: * The base name of", "edge = WeightedEdge(each_node, each_other_node, shortest_distance) self.edges.append(edge) if each_node > self.max_node: self.max_node = each_node", "execute(self) -> coo_matrix: i = [] j = [] v = [] nodes", "self.all_nodes.add(x.index) if edge_peer.partition != self.pid: self.borders.add(x.index) def get_inner_nodes(self) -> Set[int]: if len(self.inner_nodes) ==", "Assuming that a fragment name is <basename>_<n>.txt, creates the associated fragment information. \"\"\"", "= configuration def execute(self): for each_fragment_id in range(0, self.configuration.nr_fragments()): with open(\"%s_%d.txt\" % (self.configuration.input_basename(),", "base name> <number of fragments>\" % args[0]) exit(1) self.args = args def input_basename(self)", "node1 self.y = node2 def __str__(self) -> str: return \"(%s):(%s)\" % (self.x, self.y)", "args def input_basename(self) -> str: return self.args[1] def nr_fragments(self) -> int: return int(self.args[2])", "- 1) v.append(1) npi = np.array(i) npj = np.array(j) npv = np.array(v) nr_nodes", "% (len(inners), inners)) print(\"\\tBorders = %d = %s\" % (len(self.borders), self.borders)) print(\"\\tQ%% =", "@classmethod def __add_edge_to(cls, d: PartitionDescriptor, x: (str, str), y: (str, str)): nx =", "int): self.pid = partition_id self.borders: Set[int] = set() self.all_nodes: Set[int] = set() self.inner_nodes:", "% (self.partition, self.index) class Edge: def __init__(self, node1: Node, node2: Node): self.x =", "in self.borders: result.add(each_node) return result else: return self.inner_nodes def q(self) -> float: return", "collection of partitions, created by BuildFragments, to produce their traversal graphs. Input to", "result.add(each_node) return result else: return self.inner_nodes def q(self) -> float: return float(len(self.borders)) /", "in nodes: if each_other_node > each_node: i.append(each_node - 1) j.append(each_other_node - 1) v.append(1)", "int): self.x = x self.y = y self.weight = weight class TraversalGraphBuilder: def", "node1, node2) each_line = self.file.readline() return result @classmethod def __add_edge_to(cls, d: PartitionDescriptor, x:", "for each_other_node in self.partition.borders: if each_other_node > each_node: shortest_distance = shortest_paths[each_other_node - 1]", "sklearn.utils.graph import single_source_shortest_path_length class ProgramConfiguration: \"\"\"User arguments Verifies that the program is supplied", "single_source_shortest_path_length class ProgramConfiguration: \"\"\"User arguments Verifies that the program is supplied enough arguments", "[] nodes = sorted(self.nodes) for each_node in nodes: for each_other_node in nodes: if", "nr_nodes, len(weighted_edges))) for each_edge in weighted_edges: f.write(\"%d %d %d\\n\" % (each_edge.x, each_edge.y, each_edge.weight))", "(node1, node2) = map(lambda s: s.split(\".\"), items) self.__add_edge_to(result, node1, node2) each_line = self.file.readline()", "self.index = index def __str__(self) -> str: return \"%d.%d\" % (self.partition, self.index) class", "ny = Node(int(y[0]), int(y[1])) d.add_edge(Edge(nx, ny)) class WeightedEdge: def __init__(self, x: int, y:", "for each_node in self.partition.borders: shortest_paths = single_source_shortest_path_length(initial_graph, each_node - 1) for each_other_node in", "nr_nodes: int, weighted_edges: List[WeightedEdge]): with open(file_name, \"wt\") as f: f.write(\"%%MatrixMarket matrix coordinate pattern", "def __str__(self) -> str: return \"(%s):(%s)\" % (self.x, self.y) class CooMatrixBuilder: def __init__(self,", "import argv from typing import List, TextIO, Set import numpy as np from", "one function for each argument type. \"\"\" def __init__(self, args: List[str]): if len(args)", "partition self.index = index def __str__(self) -> str: return \"%d.%d\" % (self.partition, self.index)", "number and a capital T. \"\"\" from sys import argv from typing import", "npi = np.array(i) npj = np.array(j) npv = np.array(v) nr_nodes = nodes[-1] return", "str, nr_nodes: int, weighted_edges: List[WeightedEdge]): with open(file_name, \"wt\") as f: f.write(\"%%MatrixMarket matrix coordinate", "The base name of fragment files * The number of fragments to process", "each_other_node in nodes: if each_other_node > each_node: i.append(each_node - 1) j.append(each_other_node - 1)", "x: (str, str), y: (str, str)): nx = Node(int(x[0]), int(x[1])) ny = Node(int(y[0]),", "- 1) j.append(each_other_node - 1) v.append(1) npi = np.array(i) npj = np.array(j) npv", "% (100.0 * self.q())) def get_initial_graph(self) -> coo_matrix: return CooMatrixBuilder(self.all_nodes).execute() class FragmentProcessor: \"\"\"", "* The base name of fragment files * The number of fragments to", "Node(int(y[0]), int(y[1])) d.add_edge(Edge(nx, ny)) class WeightedEdge: def __init__(self, x: int, y: int, weight:", "fragment information. \"\"\" def __init__(self, fragment_file: TextIO, partition_id: int): self.file = fragment_file self.pid", "print(\"Usage: %s <fragments base name> <number of fragments>\" % args[0]) exit(1) self.args =", "else: return self.inner_nodes def q(self) -> float: return float(len(self.borders)) / float(len(self.all_nodes)) def summarize(self):", "print(\"Partition %d\" % self.pid) print(\"\\tInner nodes = %d = %s\" % (len(inners), inners))", "int): self.file = fragment_file self.pid = partition_id def get_descriptor(self) -> PartitionDescriptor: result =", "tg = TraversalGraphBuilder(descriptor).create_graph() self.__write_graph_into(\"%s_%dT.mtx\" % (self.configuration.input_basename(), each_fragment_id), tg.max_node, tg.edges) @classmethod def __write_graph_into(self, file_name:", "arguments Verifies that the program is supplied enough arguments and provides one function", "get_descriptor(self) -> PartitionDescriptor: result = PartitionDescriptor(self.pid) each_line = self.file.readline() while each_line: items =", "node2: Node): self.x = node1 self.y = node2 def __str__(self) -> str: return", "return result else: return self.inner_nodes def q(self) -> float: return float(len(self.borders)) / float(len(self.all_nodes))", "shortest_paths = single_source_shortest_path_length(initial_graph, each_node - 1) for each_other_node in self.partition.borders: if each_other_node >", "-> str: return \"(%s):(%s)\" % (self.x, self.y) class CooMatrixBuilder: def __init__(self, nodes: Set[int]):", "set() for each_node in self.all_nodes: if each_node not in self.borders: result.add(each_node) return result", "Set[int]: if len(self.inner_nodes) == 0: result = set() for each_node in self.all_nodes: if", "% (self.configuration.input_basename(), each_fragment_id), tg.max_node, tg.edges) @classmethod def __write_graph_into(self, file_name: str, nr_nodes: int, weighted_edges:", "node2) = map(lambda s: s.split(\".\"), items) self.__add_edge_to(result, node1, node2) each_line = self.file.readline() return", "inners)) print(\"\\tBorders = %d = %s\" % (len(self.borders), self.borders)) print(\"\\tQ%% = %d\" %", "initial_graph = self.partition.get_initial_graph() for each_node in self.partition.borders: shortest_paths = single_source_shortest_path_length(initial_graph, each_node - 1)", "= node1 self.y = node2 def __str__(self) -> str: return \"(%s):(%s)\" % (self.x,", "if edge_peer.partition != self.pid: self.borders.add(x.index) def get_inner_nodes(self) -> Set[int]: if len(self.inner_nodes) == 0:", "% self.pid) print(\"\\tInner nodes = %d = %s\" % (len(inners), inners)) print(\"\\tBorders =", "= weight class TraversalGraphBuilder: def __init__(self, partition: PartitionDescriptor): self.partition = partition self.max_node =", "= args def input_basename(self) -> str: return self.args[1] def nr_fragments(self) -> int: return", "def add_edge(self, edge: Edge): self.edges.append(edge) self.__add_node_from_edge_if_in(edge.x, edge.y) self.__add_node_from_edge_if_in(edge.y, edge.x) def __add_node_from_edge_if_in(self, x: Node,", "partition self.max_node = 0 self.edges: List[WeightedEdge] = [] def create_graph(self): initial_graph = self.partition.get_initial_graph()", "from sklearn.utils.graph import single_source_shortest_path_length class ProgramConfiguration: \"\"\"User arguments Verifies that the program is", "each_node - 1) for each_other_node in self.partition.borders: if each_other_node > each_node: shortest_distance =", "self.index) class Edge: def __init__(self, node1: Node, node2: Node): self.x = node1 self.y", "self.max_node = 0 self.edges: List[WeightedEdge] = [] def create_graph(self): initial_graph = self.partition.get_initial_graph() for", "each_node > self.max_node: self.max_node = each_node return self class Main: def __init__(self, configuration:", "% (self.configuration.input_basename(), each_fragment_id), \"rt\") as f: descriptor = FragmentProcessor(f, each_fragment_id).get_descriptor() descriptor.summarize() tg =", "return int(self.args[2]) class Node: def __init__(self, partition: int, index: int): self.partition = partition", "class CooMatrixBuilder: def __init__(self, nodes: Set[int]): self.nodes = nodes def execute(self) -> coo_matrix:", "self.weight = weight class TraversalGraphBuilder: def __init__(self, partition: PartitionDescriptor): self.partition = partition self.max_node", "get_inner_nodes(self) -> Set[int]: if len(self.inner_nodes) == 0: result = set() for each_node in", "for each_node in self.all_nodes: if each_node not in self.borders: result.add(each_node) return result else:", "1) for each_other_node in self.partition.borders: if each_other_node > each_node: shortest_distance = shortest_paths[each_other_node -", "configuration: ProgramConfiguration): self.configuration = configuration def execute(self): for each_fragment_id in range(0, self.configuration.nr_fragments()): with", "sorted(self.nodes) for each_node in nodes: for each_other_node in nodes: if each_other_node > each_node:", "each_line.replace(\"(\", \"\").replace(\")\", \"\").split(\":\") if len(items) == 2: (node1, node2) = map(lambda s: s.split(\".\"),", "in self.partition.borders: shortest_paths = single_source_shortest_path_length(initial_graph, each_node - 1) for each_other_node in self.partition.borders: if", "q(self) -> float: return float(len(self.borders)) / float(len(self.all_nodes)) def summarize(self): inners = self.get_inner_nodes() print(\"Partition", "class Main: def __init__(self, configuration: ProgramConfiguration): self.configuration = configuration def execute(self): for each_fragment_id", "each_fragment_id), tg.max_node, tg.edges) @classmethod def __write_graph_into(self, file_name: str, nr_nodes: int, weighted_edges: List[WeightedEdge]): with", "y self.weight = weight class TraversalGraphBuilder: def __init__(self, partition: PartitionDescriptor): self.partition = partition", "while each_line: items = each_line.replace(\"(\", \"\").replace(\")\", \"\").split(\":\") if len(items) == 2: (node1, node2)", "self.all_nodes: Set[int] = set() self.inner_nodes: Set[int] = set() self.edges = [] def add_edge(self,", "return float(len(self.borders)) / float(len(self.all_nodes)) def summarize(self): inners = self.get_inner_nodes() print(\"Partition %d\" % self.pid)", "fragment number and a capital T. \"\"\" from sys import argv from typing", "str)): nx = Node(int(x[0]), int(x[1])) ny = Node(int(y[0]), int(y[1])) d.add_edge(Edge(nx, ny)) class WeightedEdge:", "__write_graph_into(self, file_name: str, nr_nodes: int, weighted_edges: List[WeightedEdge]): with open(file_name, \"wt\") as f: f.write(\"%%MatrixMarket", "int, weighted_edges: List[WeightedEdge]): with open(file_name, \"wt\") as f: f.write(\"%%MatrixMarket matrix coordinate pattern symmetric\\n\")", "collection of mtx files, with the same base name, suffixed by the fragment", "a collection of partitions, created by BuildFragments, to produce their traversal graphs. Input", "i.append(each_node - 1) j.append(each_other_node - 1) v.append(1) npi = np.array(i) npj = np.array(j)", "= map(lambda s: s.split(\".\"), items) self.__add_edge_to(result, node1, node2) each_line = self.file.readline() return result", "FragmentProcessor: \"\"\" Assuming that a fragment name is <basename>_<n>.txt, creates the associated fragment", "coo_matrix: i = [] j = [] v = [] nodes = sorted(self.nodes)", "\"wt\") as f: f.write(\"%%MatrixMarket matrix coordinate pattern symmetric\\n\") f.write(\"%d %d %d\\n\" % (nr_nodes,", "set() self.inner_nodes: Set[int] = set() self.edges = [] def add_edge(self, edge: Edge): self.edges.append(edge)", "-> int: return int(self.args[2]) class Node: def __init__(self, partition: int, index: int): self.partition", "ProgramConfiguration): self.configuration = configuration def execute(self): for each_fragment_id in range(0, self.configuration.nr_fragments()): with open(\"%s_%d.txt\"", "nodes = sorted(self.nodes) for each_node in nodes: for each_other_node in nodes: if each_other_node", "self.edges: List[WeightedEdge] = [] def create_graph(self): initial_graph = self.partition.get_initial_graph() for each_node in self.partition.borders:", "each_other_node > each_node: i.append(each_node - 1) j.append(each_other_node - 1) v.append(1) npi = np.array(i)", "== self.pid: self.all_nodes.add(x.index) if edge_peer.partition != self.pid: self.borders.add(x.index) def get_inner_nodes(self) -> Set[int]: if", "\"\").replace(\")\", \"\").split(\":\") if len(items) == 2: (node1, node2) = map(lambda s: s.split(\".\"), items)", "capital T. \"\"\" from sys import argv from typing import List, TextIO, Set", "Node, edge_peer: Node): if x.partition == self.pid: self.all_nodes.add(x.index) if edge_peer.partition != self.pid: self.borders.add(x.index)", "= sorted(self.nodes) for each_node in nodes: for each_other_node in nodes: if each_other_node >", "npj)), shape=(nr_nodes, nr_nodes)) class PartitionDescriptor: def __init__(self, partition_id: int): self.pid = partition_id self.borders:", "coo_matrix((npv, (npi, npj)), shape=(nr_nodes, nr_nodes)) class PartitionDescriptor: def __init__(self, partition_id: int): self.pid =", "self.file = fragment_file self.pid = partition_id def get_descriptor(self) -> PartitionDescriptor: result = PartitionDescriptor(self.pid)", "items) self.__add_edge_to(result, node1, node2) each_line = self.file.readline() return result @classmethod def __add_edge_to(cls, d:", "for each argument type. \"\"\" def __init__(self, args: List[str]): if len(args) != 3:", "%s <fragments base name> <number of fragments>\" % args[0]) exit(1) self.args = args", "1) v.append(1) npi = np.array(i) npj = np.array(j) npv = np.array(v) nr_nodes =", "%d %d\\n\" % (nr_nodes, nr_nodes, len(weighted_edges))) for each_edge in weighted_edges: f.write(\"%d %d %d\\n\"", "set() self.edges = [] def add_edge(self, edge: Edge): self.edges.append(edge) self.__add_node_from_edge_if_in(edge.x, edge.y) self.__add_node_from_edge_if_in(edge.y, edge.x)", "not in self.borders: result.add(each_node) return result else: return self.inner_nodes def q(self) -> float:", "= Node(int(y[0]), int(y[1])) d.add_edge(Edge(nx, ny)) class WeightedEdge: def __init__(self, x: int, y: int,", "= partition_id def get_descriptor(self) -> PartitionDescriptor: result = PartitionDescriptor(self.pid) each_line = self.file.readline() while", "\"\"\" from sys import argv from typing import List, TextIO, Set import numpy", "v.append(1) npi = np.array(i) npj = np.array(j) npv = np.array(v) nr_nodes = nodes[-1]", "def create_graph(self): initial_graph = self.partition.get_initial_graph() for each_node in self.partition.borders: shortest_paths = single_source_shortest_path_length(initial_graph, each_node", "= [] def add_edge(self, edge: Edge): self.edges.append(edge) self.__add_node_from_edge_if_in(edge.x, edge.y) self.__add_node_from_edge_if_in(edge.y, edge.x) def __add_node_from_edge_if_in(self,", "partitions, created by BuildFragments, to produce their traversal graphs. Input to this program", "__init__(self, args: List[str]): if len(args) != 3: print(\"Usage: %s <fragments base name> <number", "partition: int, index: int): self.partition = partition self.index = index def __str__(self) ->", "Node, node2: Node): self.x = node1 self.y = node2 def __str__(self) -> str:", "= self.file.readline() while each_line: items = each_line.replace(\"(\", \"\").replace(\")\", \"\").split(\":\") if len(items) == 2:", "self.configuration.nr_fragments()): with open(\"%s_%d.txt\" % (self.configuration.input_basename(), each_fragment_id), \"rt\") as f: descriptor = FragmentProcessor(f, each_fragment_id).get_descriptor()", "float(len(self.all_nodes)) def summarize(self): inners = self.get_inner_nodes() print(\"Partition %d\" % self.pid) print(\"\\tInner nodes =", "print(\"\\tBorders = %d = %s\" % (len(self.borders), self.borders)) print(\"\\tQ%% = %d\" % (100.0", "mtx files, with the same base name, suffixed by the fragment number and", "single_source_shortest_path_length(initial_graph, each_node - 1) for each_other_node in self.partition.borders: if each_other_node > each_node: shortest_distance", "print(\"\\tInner nodes = %d = %s\" % (len(inners), inners)) print(\"\\tBorders = %d =", "arguments and provides one function for each argument type. \"\"\" def __init__(self, args:", "return \"(%s):(%s)\" % (self.x, self.y) class CooMatrixBuilder: def __init__(self, nodes: Set[int]): self.nodes =", "Main: def __init__(self, configuration: ProgramConfiguration): self.configuration = configuration def execute(self): for each_fragment_id in", "if each_node > self.max_node: self.max_node = each_node return self class Main: def __init__(self,", "__init__(self, partition: PartitionDescriptor): self.partition = partition self.max_node = 0 self.edges: List[WeightedEdge] = []", "%d\" % self.pid) print(\"\\tInner nodes = %d = %s\" % (len(inners), inners)) print(\"\\tBorders", "is <basename>_<n>.txt, creates the associated fragment information. \"\"\" def __init__(self, fragment_file: TextIO, partition_id:", "produce their traversal graphs. Input to this program are: * The base name", "class FragmentProcessor: \"\"\" Assuming that a fragment name is <basename>_<n>.txt, creates the associated", "self.y) class CooMatrixBuilder: def __init__(self, nodes: Set[int]): self.nodes = nodes def execute(self) ->", "j = [] v = [] nodes = sorted(self.nodes) for each_node in nodes:", "to produce their traversal graphs. Input to this program are: * The base", "= np.array(j) npv = np.array(v) nr_nodes = nodes[-1] return coo_matrix((npv, (npi, npj)), shape=(nr_nodes,", "float: return float(len(self.borders)) / float(len(self.all_nodes)) def summarize(self): inners = self.get_inner_nodes() print(\"Partition %d\" %", "(self.x, self.y) class CooMatrixBuilder: def __init__(self, nodes: Set[int]): self.nodes = nodes def execute(self)", "program are: * The base name of fragment files * The number of", "> each_node: shortest_distance = shortest_paths[each_other_node - 1] edge = WeightedEdge(each_node, each_other_node, shortest_distance) self.edges.append(edge)", "List[WeightedEdge] = [] def create_graph(self): initial_graph = self.partition.get_initial_graph() for each_node in self.partition.borders: shortest_paths", "Set[int] = set() self.edges = [] def add_edge(self, edge: Edge): self.edges.append(edge) self.__add_node_from_edge_if_in(edge.x, edge.y)", "str: return \"(%s):(%s)\" % (self.x, self.y) class CooMatrixBuilder: def __init__(self, nodes: Set[int]): self.nodes", "tg.max_node, tg.edges) @classmethod def __write_graph_into(self, file_name: str, nr_nodes: int, weighted_edges: List[WeightedEdge]): with open(file_name,", "%d = %s\" % (len(inners), inners)) print(\"\\tBorders = %d = %s\" % (len(self.borders),", "def nr_fragments(self) -> int: return int(self.args[2]) class Node: def __init__(self, partition: int, index:", "weight class TraversalGraphBuilder: def __init__(self, partition: PartitionDescriptor): self.partition = partition self.max_node = 0", "-> str: return self.args[1] def nr_fragments(self) -> int: return int(self.args[2]) class Node: def", "process Output is a collection of mtx files, with the same base name,", "f: f.write(\"%%MatrixMarket matrix coordinate pattern symmetric\\n\") f.write(\"%d %d %d\\n\" % (nr_nodes, nr_nodes, len(weighted_edges)))", "each_node not in self.borders: result.add(each_node) return result else: return self.inner_nodes def q(self) ->", "the same base name, suffixed by the fragment number and a capital T.", "each_node in self.partition.borders: shortest_paths = single_source_shortest_path_length(initial_graph, each_node - 1) for each_other_node in self.partition.borders:", "summarize(self): inners = self.get_inner_nodes() print(\"Partition %d\" % self.pid) print(\"\\tInner nodes = %d =", "partition_id: int): self.file = fragment_file self.pid = partition_id def get_descriptor(self) -> PartitionDescriptor: result", "edge.y) self.__add_node_from_edge_if_in(edge.y, edge.x) def __add_node_from_edge_if_in(self, x: Node, edge_peer: Node): if x.partition == self.pid:", "self.borders: Set[int] = set() self.all_nodes: Set[int] = set() self.inner_nodes: Set[int] = set() self.edges", "= self.partition.get_initial_graph() for each_node in self.partition.borders: shortest_paths = single_source_shortest_path_length(initial_graph, each_node - 1) for", "= node2 def __str__(self) -> str: return \"(%s):(%s)\" % (self.x, self.y) class CooMatrixBuilder:", "def get_descriptor(self) -> PartitionDescriptor: result = PartitionDescriptor(self.pid) each_line = self.file.readline() while each_line: items", "def summarize(self): inners = self.get_inner_nodes() print(\"Partition %d\" % self.pid) print(\"\\tInner nodes = %d", "int(x[1])) ny = Node(int(y[0]), int(y[1])) d.add_edge(Edge(nx, ny)) class WeightedEdge: def __init__(self, x: int,", "edge_peer: Node): if x.partition == self.pid: self.all_nodes.add(x.index) if edge_peer.partition != self.pid: self.borders.add(x.index) def", "== 2: (node1, node2) = map(lambda s: s.split(\".\"), items) self.__add_edge_to(result, node1, node2) each_line", "def __init__(self, partition: PartitionDescriptor): self.partition = partition self.max_node = 0 self.edges: List[WeightedEdge] =", "self.__write_graph_into(\"%s_%dT.mtx\" % (self.configuration.input_basename(), each_fragment_id), tg.max_node, tg.edges) @classmethod def __write_graph_into(self, file_name: str, nr_nodes: int,", "= self.get_inner_nodes() print(\"Partition %d\" % self.pid) print(\"\\tInner nodes = %d = %s\" %", "class TraversalGraphBuilder: def __init__(self, partition: PartitionDescriptor): self.partition = partition self.max_node = 0 self.edges:", "files * The number of fragments to process Output is a collection of", "np.array(i) npj = np.array(j) npv = np.array(v) nr_nodes = nodes[-1] return coo_matrix((npv, (npi,", "self.configuration = configuration def execute(self): for each_fragment_id in range(0, self.configuration.nr_fragments()): with open(\"%s_%d.txt\" %", "self.inner_nodes def q(self) -> float: return float(len(self.borders)) / float(len(self.all_nodes)) def summarize(self): inners =", "str: return self.args[1] def nr_fragments(self) -> int: return int(self.args[2]) class Node: def __init__(self,", "int(y[1])) d.add_edge(Edge(nx, ny)) class WeightedEdge: def __init__(self, x: int, y: int, weight: int):", "args: List[str]): if len(args) != 3: print(\"Usage: %s <fragments base name> <number of", "-> PartitionDescriptor: result = PartitionDescriptor(self.pid) each_line = self.file.readline() while each_line: items = each_line.replace(\"(\",", "\"\").split(\":\") if len(items) == 2: (node1, node2) = map(lambda s: s.split(\".\"), items) self.__add_edge_to(result,", "nx = Node(int(x[0]), int(x[1])) ny = Node(int(y[0]), int(y[1])) d.add_edge(Edge(nx, ny)) class WeightedEdge: def", "Edge): self.edges.append(edge) self.__add_node_from_edge_if_in(edge.x, edge.y) self.__add_node_from_edge_if_in(edge.y, edge.x) def __add_node_from_edge_if_in(self, x: Node, edge_peer: Node): if", "self.__add_node_from_edge_if_in(edge.y, edge.x) def __add_node_from_edge_if_in(self, x: Node, edge_peer: Node): if x.partition == self.pid: self.all_nodes.add(x.index)", "Set[int] = set() self.inner_nodes: Set[int] = set() self.edges = [] def add_edge(self, edge:", "typing import List, TextIO, Set import numpy as np from scipy.sparse import coo_matrix", "with the same base name, suffixed by the fragment number and a capital", "symmetric\\n\") f.write(\"%d %d %d\\n\" % (nr_nodes, nr_nodes, len(weighted_edges))) for each_edge in weighted_edges: f.write(\"%d", "execute(self): for each_fragment_id in range(0, self.configuration.nr_fragments()): with open(\"%s_%d.txt\" % (self.configuration.input_basename(), each_fragment_id), \"rt\") as", "if each_other_node > each_node: shortest_distance = shortest_paths[each_other_node - 1] edge = WeightedEdge(each_node, each_other_node,", "that the program is supplied enough arguments and provides one function for each", "> self.max_node: self.max_node = each_node return self class Main: def __init__(self, configuration: ProgramConfiguration):", "result = set() for each_node in self.all_nodes: if each_node not in self.borders: result.add(each_node)", "= 0 self.edges: List[WeightedEdge] = [] def create_graph(self): initial_graph = self.partition.get_initial_graph() for each_node", "shortest_distance = shortest_paths[each_other_node - 1] edge = WeightedEdge(each_node, each_other_node, shortest_distance) self.edges.append(edge) if each_node", "TextIO, Set import numpy as np from scipy.sparse import coo_matrix from sklearn.utils.graph import", "to process Output is a collection of mtx files, with the same base", "supplied enough arguments and provides one function for each argument type. \"\"\" def", "ny)) class WeightedEdge: def __init__(self, x: int, y: int, weight: int): self.x =", "CooMatrixBuilder: def __init__(self, nodes: Set[int]): self.nodes = nodes def execute(self) -> coo_matrix: i", "result = PartitionDescriptor(self.pid) each_line = self.file.readline() while each_line: items = each_line.replace(\"(\", \"\").replace(\")\", \"\").split(\":\")", "enough arguments and provides one function for each argument type. \"\"\" def __init__(self,", "partition_id self.borders: Set[int] = set() self.all_nodes: Set[int] = set() self.inner_nodes: Set[int] = set()", "__init__(self, nodes: Set[int]): self.nodes = nodes def execute(self) -> coo_matrix: i = []", "fragment_file self.pid = partition_id def get_descriptor(self) -> PartitionDescriptor: result = PartitionDescriptor(self.pid) each_line =", "if x.partition == self.pid: self.all_nodes.add(x.index) if edge_peer.partition != self.pid: self.borders.add(x.index) def get_inner_nodes(self) ->", "self.edges = [] def add_edge(self, edge: Edge): self.edges.append(edge) self.__add_node_from_edge_if_in(edge.x, edge.y) self.__add_node_from_edge_if_in(edge.y, edge.x) def", "class ProgramConfiguration: \"\"\"User arguments Verifies that the program is supplied enough arguments and", "<gh_stars>0 \"\"\" Reads a collection of partitions, created by BuildFragments, to produce their", "\"rt\") as f: descriptor = FragmentProcessor(f, each_fragment_id).get_descriptor() descriptor.summarize() tg = TraversalGraphBuilder(descriptor).create_graph() self.__write_graph_into(\"%s_%dT.mtx\" %", "nodes = %d = %s\" % (len(inners), inners)) print(\"\\tBorders = %d = %s\"", "nodes: for each_other_node in nodes: if each_other_node > each_node: i.append(each_node - 1) j.append(each_other_node", "[] def create_graph(self): initial_graph = self.partition.get_initial_graph() for each_node in self.partition.borders: shortest_paths = single_source_shortest_path_length(initial_graph,", "__init__(self, partition: int, index: int): self.partition = partition self.index = index def __str__(self)", "def __init__(self, node1: Node, node2: Node): self.x = node1 self.y = node2 def", "Input to this program are: * The base name of fragment files *", "len(args) != 3: print(\"Usage: %s <fragments base name> <number of fragments>\" % args[0])", "= partition self.index = index def __str__(self) -> str: return \"%d.%d\" % (self.partition,", "def execute(self) -> coo_matrix: i = [] j = [] v = []", "if len(self.inner_nodes) == 0: result = set() for each_node in self.all_nodes: if each_node", "def q(self) -> float: return float(len(self.borders)) / float(len(self.all_nodes)) def summarize(self): inners = self.get_inner_nodes()", "inners = self.get_inner_nodes() print(\"Partition %d\" % self.pid) print(\"\\tInner nodes = %d = %s\"", "sys import argv from typing import List, TextIO, Set import numpy as np", "fragment_file: TextIO, partition_id: int): self.file = fragment_file self.pid = partition_id def get_descriptor(self) ->", "len(items) == 2: (node1, node2) = map(lambda s: s.split(\".\"), items) self.__add_edge_to(result, node1, node2)", "shortest_paths[each_other_node - 1] edge = WeightedEdge(each_node, each_other_node, shortest_distance) self.edges.append(edge) if each_node > self.max_node:", "TextIO, partition_id: int): self.file = fragment_file self.pid = partition_id def get_descriptor(self) -> PartitionDescriptor:", "%d\" % (100.0 * self.q())) def get_initial_graph(self) -> coo_matrix: return CooMatrixBuilder(self.all_nodes).execute() class FragmentProcessor:", "graphs. Input to this program are: * The base name of fragment files", "of fragments to process Output is a collection of mtx files, with the", "argv from typing import List, TextIO, Set import numpy as np from scipy.sparse", "%s\" % (len(self.borders), self.borders)) print(\"\\tQ%% = %d\" % (100.0 * self.q())) def get_initial_graph(self)", "__init__(self, x: int, y: int, weight: int): self.x = x self.y = y", "self.pid = partition_id def get_descriptor(self) -> PartitionDescriptor: result = PartitionDescriptor(self.pid) each_line = self.file.readline()", "-> coo_matrix: return CooMatrixBuilder(self.all_nodes).execute() class FragmentProcessor: \"\"\" Assuming that a fragment name is", "2: (node1, node2) = map(lambda s: s.split(\".\"), items) self.__add_edge_to(result, node1, node2) each_line =", "range(0, self.configuration.nr_fragments()): with open(\"%s_%d.txt\" % (self.configuration.input_basename(), each_fragment_id), \"rt\") as f: descriptor = FragmentProcessor(f,", "__init__(self, configuration: ProgramConfiguration): self.configuration = configuration def execute(self): for each_fragment_id in range(0, self.configuration.nr_fragments()):", "PartitionDescriptor): self.partition = partition self.max_node = 0 self.edges: List[WeightedEdge] = [] def create_graph(self):", "= shortest_paths[each_other_node - 1] edge = WeightedEdge(each_node, each_other_node, shortest_distance) self.edges.append(edge) if each_node >", "self.q())) def get_initial_graph(self) -> coo_matrix: return CooMatrixBuilder(self.all_nodes).execute() class FragmentProcessor: \"\"\" Assuming that a", "if len(items) == 2: (node1, node2) = map(lambda s: s.split(\".\"), items) self.__add_edge_to(result, node1,", "= partition self.max_node = 0 self.edges: List[WeightedEdge] = [] def create_graph(self): initial_graph =", "np.array(v) nr_nodes = nodes[-1] return coo_matrix((npv, (npi, npj)), shape=(nr_nodes, nr_nodes)) class PartitionDescriptor: def", "self.x = node1 self.y = node2 def __str__(self) -> str: return \"(%s):(%s)\" %", "= nodes[-1] return coo_matrix((npv, (npi, npj)), shape=(nr_nodes, nr_nodes)) class PartitionDescriptor: def __init__(self, partition_id:", "<number of fragments>\" % args[0]) exit(1) self.args = args def input_basename(self) -> str:", "def input_basename(self) -> str: return self.args[1] def nr_fragments(self) -> int: return int(self.args[2]) class", "BuildFragments, to produce their traversal graphs. Input to this program are: * The", "from sys import argv from typing import List, TextIO, Set import numpy as", "= %d = %s\" % (len(inners), inners)) print(\"\\tBorders = %d = %s\" %", "items = each_line.replace(\"(\", \"\").replace(\")\", \"\").split(\":\") if len(items) == 2: (node1, node2) = map(lambda", "of mtx files, with the same base name, suffixed by the fragment number", "if each_other_node > each_node: i.append(each_node - 1) j.append(each_other_node - 1) v.append(1) npi =", "/ float(len(self.all_nodes)) def summarize(self): inners = self.get_inner_nodes() print(\"Partition %d\" % self.pid) print(\"\\tInner nodes", "int, y: int, weight: int): self.x = x self.y = y self.weight =", "descriptor = FragmentProcessor(f, each_fragment_id).get_descriptor() descriptor.summarize() tg = TraversalGraphBuilder(descriptor).create_graph() self.__write_graph_into(\"%s_%dT.mtx\" % (self.configuration.input_basename(), each_fragment_id), tg.max_node,", "name, suffixed by the fragment number and a capital T. \"\"\" from sys", "fragments>\" % args[0]) exit(1) self.args = args def input_basename(self) -> str: return self.args[1]", "-> str: return \"%d.%d\" % (self.partition, self.index) class Edge: def __init__(self, node1: Node,", "args[0]) exit(1) self.args = args def input_basename(self) -> str: return self.args[1] def nr_fragments(self)", "name is <basename>_<n>.txt, creates the associated fragment information. \"\"\" def __init__(self, fragment_file: TextIO,", "partition_id def get_descriptor(self) -> PartitionDescriptor: result = PartitionDescriptor(self.pid) each_line = self.file.readline() while each_line:", "Node): self.x = node1 self.y = node2 def __str__(self) -> str: return \"(%s):(%s)\"", "= y self.weight = weight class TraversalGraphBuilder: def __init__(self, partition: PartitionDescriptor): self.partition =", "the fragment number and a capital T. \"\"\" from sys import argv from", "index: int): self.partition = partition self.index = index def __str__(self) -> str: return", "of fragments>\" % args[0]) exit(1) self.args = args def input_basename(self) -> str: return", "import numpy as np from scipy.sparse import coo_matrix from sklearn.utils.graph import single_source_shortest_path_length class", "= WeightedEdge(each_node, each_other_node, shortest_distance) self.edges.append(edge) if each_node > self.max_node: self.max_node = each_node return", "for each_node in nodes: for each_other_node in nodes: if each_other_node > each_node: i.append(each_node", "int, index: int): self.partition = partition self.index = index def __str__(self) -> str:", "-> coo_matrix: i = [] j = [] v = [] nodes =", "for each_other_node in nodes: if each_other_node > each_node: i.append(each_node - 1) j.append(each_other_node -", "in range(0, self.configuration.nr_fragments()): with open(\"%s_%d.txt\" % (self.configuration.input_basename(), each_fragment_id), \"rt\") as f: descriptor =", "as np from scipy.sparse import coo_matrix from sklearn.utils.graph import single_source_shortest_path_length class ProgramConfiguration: \"\"\"User", "(len(inners), inners)) print(\"\\tBorders = %d = %s\" % (len(self.borders), self.borders)) print(\"\\tQ%% = %d\"", "* The number of fragments to process Output is a collection of mtx", "if each_node not in self.borders: result.add(each_node) return result else: return self.inner_nodes def q(self)", "x.partition == self.pid: self.all_nodes.add(x.index) if edge_peer.partition != self.pid: self.borders.add(x.index) def get_inner_nodes(self) -> Set[int]:", "each_node: shortest_distance = shortest_paths[each_other_node - 1] edge = WeightedEdge(each_node, each_other_node, shortest_distance) self.edges.append(edge) if", "int): self.partition = partition self.index = index def __str__(self) -> str: return \"%d.%d\"", "self.partition.borders: if each_other_node > each_node: shortest_distance = shortest_paths[each_other_node - 1] edge = WeightedEdge(each_node,", "(100.0 * self.q())) def get_initial_graph(self) -> coo_matrix: return CooMatrixBuilder(self.all_nodes).execute() class FragmentProcessor: \"\"\" Assuming", "= %d\" % (100.0 * self.q())) def get_initial_graph(self) -> coo_matrix: return CooMatrixBuilder(self.all_nodes).execute() class", "np from scipy.sparse import coo_matrix from sklearn.utils.graph import single_source_shortest_path_length class ProgramConfiguration: \"\"\"User arguments", "each_edge in weighted_edges: f.write(\"%d %d %d\\n\" % (each_edge.x, each_edge.y, each_edge.weight)) # ================================================================================ Main(ProgramConfiguration(argv)).execute()", "traversal graphs. Input to this program are: * The base name of fragment", "base name of fragment files * The number of fragments to process Output", "map(lambda s: s.split(\".\"), items) self.__add_edge_to(result, node1, node2) each_line = self.file.readline() return result @classmethod", "= index def __str__(self) -> str: return \"%d.%d\" % (self.partition, self.index) class Edge:", "= self.file.readline() return result @classmethod def __add_edge_to(cls, d: PartitionDescriptor, x: (str, str), y:", "nodes def execute(self) -> coo_matrix: i = [] j = [] v =", "edge_peer.partition != self.pid: self.borders.add(x.index) def get_inner_nodes(self) -> Set[int]: if len(self.inner_nodes) == 0: result", "def get_inner_nodes(self) -> Set[int]: if len(self.inner_nodes) == 0: result = set() for each_node", "in self.partition.borders: if each_other_node > each_node: shortest_distance = shortest_paths[each_other_node - 1] edge =", "d.add_edge(Edge(nx, ny)) class WeightedEdge: def __init__(self, x: int, y: int, weight: int): self.x", "created by BuildFragments, to produce their traversal graphs. Input to this program are:", "index def __str__(self) -> str: return \"%d.%d\" % (self.partition, self.index) class Edge: def", "import List, TextIO, Set import numpy as np from scipy.sparse import coo_matrix from", "nr_nodes = nodes[-1] return coo_matrix((npv, (npi, npj)), shape=(nr_nodes, nr_nodes)) class PartitionDescriptor: def __init__(self,", "= set() self.all_nodes: Set[int] = set() self.inner_nodes: Set[int] = set() self.edges = []", "<basename>_<n>.txt, creates the associated fragment information. \"\"\" def __init__(self, fragment_file: TextIO, partition_id: int):", "= %s\" % (len(self.borders), self.borders)) print(\"\\tQ%% = %d\" % (100.0 * self.q())) def", "if len(args) != 3: print(\"Usage: %s <fragments base name> <number of fragments>\" %", "= set() self.edges = [] def add_edge(self, edge: Edge): self.edges.append(edge) self.__add_node_from_edge_if_in(edge.x, edge.y) self.__add_node_from_edge_if_in(edge.y,", "self.nodes = nodes def execute(self) -> coo_matrix: i = [] j = []", "self.y = y self.weight = weight class TraversalGraphBuilder: def __init__(self, partition: PartitionDescriptor): self.partition", "x: Node, edge_peer: Node): if x.partition == self.pid: self.all_nodes.add(x.index) if edge_peer.partition != self.pid:", "def execute(self): for each_fragment_id in range(0, self.configuration.nr_fragments()): with open(\"%s_%d.txt\" % (self.configuration.input_basename(), each_fragment_id), \"rt\")", "Verifies that the program is supplied enough arguments and provides one function for" ]
[ "{ 'ref' : value['ref'] } }) del tasks[value['ref']] elif change['type'] == 'change': print(f\"Ref", "include_initial=with_initials).run(conn) while True: change = await changes.next() if not change: break if change['type']", "graphene.types.resolver import dict_resolver from graphql import ResolveInfo from rethinkdb import RethinkDB from rethinkdb.errors", "an asynchronous function that resolves every change in RethinkDB table with item with", "bool) -> Observable: ''' Returns subscription updates with the following shape: { changeType:", "ReqlOpFailedError: return if not change: break if change['type'] == 'remove': value = change['old_val']", "async with ReDBConnection().get_async_connection() as conn: table = re.db.table(table_name) changes = await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=with_initials).run(conn)", "not change: break if change['type'] == 'remove': value = change['old_val'] else: value =", "class Change(graphene.Enum): Initial = 'initial' Add = 'add' Remove = 'remove' Change =", "raise ValueError(f\"No such ChangeType: {s}\") @dataclass class TaskCounter: task : asyncio.Task count =", "initial values (default: False). Use True, when a Subscription is not used as", "'initial': return Change.Initial elif s == 'add': return Change.Add elif s == 'remove':", "= await changes.next() if not change: break if change['type'] == 'remove': value =", ": asyncio.Task count = 1 async def create_single_changefeeds(queue: asyncio.Queue, info: ResolveInfo, user_authenticator :", "Deleted \"\"\" class Meta: types = (_class, Deleted, ) change_type = type(f'{_class.__name__}OrDeleted', (graphene.Union,", "This is suitable when one wants to subscribe to changes for one particular", "None: yield None continue else: value = change['new_val'] yield item_class(**value) return Observable.from_future(iterable_to_item()) return", "create_single_changefeeds(queue: asyncio.Queue, info: ResolveInfo, user_authenticator : BasicAuthenticator, xenobject_type: Type[XenObject], with_initials : bool, filter_function=None):", "MakeSubscription(type) :param root: :param info: :param args: :return: ''' async def iterable_to_item(): key", "in mind that this function is called only once when a new item", ":param args: :return: ''' async def iterable_to_item(): async with ReDBConnection().get_async_connection() as conn: key", "return resolve_item def resolve_all_items_changes(item_class: type, table_name : str): \"\"\" Returns an asynchronous function", "== 'initial': return Change.Initial elif s == 'add': return Change.Add elif s ==", "'remove': value = change['old_val'] value['__typename'] = 'Deleted' else: value = change['new_val'] value['__typename'] =", "resolve_item_by_pkey This is suitable when one wants to subscribe to changes for one", "return return Observable.from_future(iterable_to_items()) return resolve_items def resolve_item_by_key(item_class: type, table_name : str, key_name:str =", "Change = 'change' def str_to_changetype(s: str) -> Change: if s == 'initial': return", "Observable: ''' Returns subscription updates with the following shape: { changeType: one of", "ReDBConnection from handlers.graphql.types.deleted import Deleted from handlers.graphql.utils.querybuilder.changefeedbuilder import ChangefeedBuilder from handlers.graphql.utils.querybuilder.get_fields import get_fields", "and with all initial items :return: \"\"\" def resolve_items(root, info : ResolveInfo, with_initials", "include_initial=True).run(conn) while True: change = await changes.next() if not change: break if change['type']", "info, authenticator, xenobject_type, with_initials, filter_function)) try: while True: change = await queue.get() if", "iterable_to_item(): key = args.get(key_name, None) if not key: yield None return builder =", "shape: { changeType: one of Initial, Add, Mod, Remove value: of type item_class", "XenObject from xenadapter.aclxenobject import ACLXenObject class Change(graphene.Enum): Initial = 'initial' Add = 'add'", "= TaskCounter(task=asyncio.create_task(builder.put_values_in_queue())) else: tasks[value['ref']].count += 1 except asyncio.CancelledError: for task_counter in tasks.values(): task_counter.task.cancel()", "backer for Query ''' async def iterable_to_items(): fields_for_return_type = get_fields(info, ['value']) xenobject_type =", "with change tracking. If an object is deleted and it's a XenObject, only", "deleted and it's a XenObject, only its ref is returned :param _class: GraphQL", "\"\"\" def resolve_items(root, info : ResolveInfo, with_initials : bool, **kwargs) -> Observable: '''", ":return: ''' async def iterable_to_items(): async with ReDBConnection().get_async_connection() as conn: table = re.db.table(table_name)", "function should return true or false answering whether we should include this item", "''' async def iterable_to_items(): async with ReDBConnection().get_async_connection() as conn: table = re.db.table(table_name) changes", "sentry_sdk.capture_exception(e) return def MakeSubscriptionWithChangeType(_class : type) -> type: \"\"\" Create a subscription type", "-> Observable: ''' Returns subscription updates with the following shape: { changeType: one", "with said primary key If item is deleted or does not exist, returns", "import sentry_sdk sentry_sdk.capture_exception(e) return def MakeSubscriptionWithChangeType(_class : type) -> type: \"\"\" Create a", "class Meta: default_resolver = dict_resolver return type(f'{_class.__name__}sSubscription', (ObjectType, ), { 'change_type': graphene.Field(Change, required=True,", "shape as a table :param filter_function: this function is given a ref of", "Dict, Type import graphene from graphene import ObjectType from graphene.types.resolver import dict_resolver from", "with ReDBConnection().get_async_connection() as conn: tasks: Dict[str, TaskCounter] = {} try: if not user_authenticator", "a table :param filter_function: this function is given a ref of potential subscription", "**kwargs) -> Observable: ''' Returns subscription updates with the following shape: { changeType:", "resolve_item_by_key(item_class: type, table_name : str, key_name:str = 'ref'): \"\"\" Returns an asynchronous function", "import dataclass from typing import Dict, Type import graphene from graphene import ObjectType", "'ref' : value['ref'] } }) del tasks[value['ref']] elif change['type'] == 'change': print(f\"Ref change?:", "_class.__name__: graphene.Field(_class) # }) return _class def resolve_xen_item_by_key(key_name:str = 'ref'): \"\"\" Returns an", "_class OR Deleted \"\"\" class Meta: types = (_class, Deleted, ) change_type =", ": {...} <-- this is what we need in info status=change['type'], ignore_initials=not with_initials)", "item :param _class: :return: ''' #return type(f'{_class.__name__}Subscription', # (ObjectType, ), # { #", "tasks: tasks[value['ref']] = TaskCounter(task=asyncio.create_task(builder.put_values_in_queue())) else: tasks[value['ref']].count += 1 except asyncio.CancelledError: for task_counter in", "we need in info status=change['type'], ignore_initials=not with_initials) if not value['ref'] in tasks: tasks[value['ref']]", "Mod, Remove value: of type item_class } Create a field with MakeSubscriptionWithChangeType(type) :param", "or does not exist, returns null in place of an item :param item_class:", "type for resolve_item_by_pkey This is suitable when one wants to subscribe to changes", "if change['type'] == 'remove' or change['new_val'] is None: yield None continue else: value", "field with MakeSubscription(type) :param root: :param info: :param args: :return: ''' async def", "\\ .pluck(*item_class._meta.fields)\\ .changes(include_types=True, include_initial=True).run(conn) while True: change = await changes.next() if not change:", "MakeSubscriptionWithChangeType(type) :param info: :param with_initials: Supply subscription with initial values (default: False). Use", "type(f'{_class.__name__}Subscription', # (ObjectType, ), # { # _class.__name__: graphene.Field(_class) # }) return _class", "from handlers.graphql.utils.querybuilder.changefeedbuilder import ChangefeedBuilder from handlers.graphql.utils.querybuilder.get_fields import get_fields from utils.user import user_entities from", "Observable. Works with asyncio \"\"\" def resolve_item(root, info, **args) -> Observable: ''' Create", "of potential subscription candidate (0th arg) and an asyncio connection to work with", "info.context.user_authenticator creator_task = asyncio.create_task(create_single_changefeeds(queue, info, authenticator, xenobject_type, with_initials, filter_function)) try: while True: change", "def resolve_item(root, info, **args) -> Observable: ''' Create a field with MakeSubscription(type) :param", "'remove': return Change.Remove elif s == 'change': return Change.Change else: raise ValueError(f\"No such", "in RethinkDB table with item with said primary key If item is deleted", "= change['new_val'] yield item_class(**value) return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_items_changes(item_class: type, table_name :", "work with DB (1st arg). This function should return true or false answering", "conn)): continue builder = ChangefeedBuilder(id=value['ref'], info=info, queue=queue, additional_string=None, select_subfield=['value'], # { value :", "tasks[value['ref']].count += 1 except asyncio.CancelledError: for task_counter in tasks.values(): task_counter.task.cancel() return except Exception", "Create a field with MakeSubscription(type) :param root: :param info: :param args: :return: '''", "change['type'] == 'remove': value = change['old_val'] else: value = change['new_val'] value = item_class(**value)", "that resolves every change in RethinkDB table :param item_class: GraphQL object type that", "issubclass(xenobject_type, ACLXenObject): table = re.db.table(xenobject_type.db_table_name) else: table = re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity for entity in user_entities(user_authenticator)],", "change tracking. If an object is deleted and it's a XenObject, only its", "change['type'] == 'remove' or change['new_val'] is None: yield None continue else: value =", "object type that has same shape as a table :param table: RethinkDB table", "MakeSubscriptionWithChangeType(type) :param info: :return: ''' async def iterable_to_items(): async with ReDBConnection().get_async_connection() as conn:", "in builder.yield_values(): if not change: break if change['type'] == 'remove' or change['new_val'] is", "an asyncio connection to work with DB (1st arg). This function should return", "import user_entities from xenadapter.xenobject import XenObject from xenadapter.aclxenobject import ACLXenObject class Change(graphene.Enum): Initial", "dataclass from typing import Dict, Type import graphene from graphene import ObjectType from", "if change['type'] == 'remove': value = change['old_val'] task_counter = tasks[value['ref']] task_counter.count -= 1", "to retrieve updates from :return: function that returns Observable. Works with asyncio \"\"\"", "None continue else: value = change['new_val'] yield item_class(**value) return Observable.from_future(iterable_to_item()) return resolve_item def", "to work with DB (1st arg). This function should return true or false", "graphene from graphene import ObjectType from graphene.types.resolver import dict_resolver from graphql import ResolveInfo", "from typing import Dict, Type import graphene from graphene import ObjectType from graphene.types.resolver", "# (ObjectType, ), # { # _class.__name__: graphene.Field(_class) # }) return _class def", "'remove': value = change['old_val'] else: value = change['new_val'] value = item_class(**value) yield MakeSubscriptionWithChangeType(item_class)(change_type=str_to_changetype(change['type']),", "rethinkdb.errors import ReqlOpFailedError from rx import Observable from enum import Enum import constants.re", "connman import ReDBConnection from handlers.graphql.types.deleted import Deleted from handlers.graphql.utils.querybuilder.changefeedbuilder import ChangefeedBuilder from handlers.graphql.utils.querybuilder.get_fields", "def create_single_changefeeds(queue: asyncio.Queue, info: ResolveInfo, user_authenticator : BasicAuthenticator, xenobject_type: Type[XenObject], with_initials : bool,", "table.pluck('ref').changes(include_types=True, include_initial=True).run(conn) while True: try: change = await changes.next() except ReqlOpFailedError: return if", "usage example. Bear in mind that this function is called only once when", "its ref is returned :param _class: GraphQL type to track changes on :return:", "of Initial, Add, Mod, Remove value: of type item_class } Create a field", "queue=queue, additional_string=None, select_subfield=['value'], # { value : {...} <-- this is what we", "an object is deleted and it's a XenObject, only its ref is returned", "asyncio.Queue() authenticator = info.context.user_authenticator creator_task = asyncio.create_task(create_single_changefeeds(queue, info, authenticator, xenobject_type, with_initials, filter_function)) try:", "item_class(**value) return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_items_changes(item_class: type, table_name : str): \"\"\" Returns", ":param root: :param info: :param args: :return: ''' async def iterable_to_item(): key =", "table = re.db.table(table_name) changes = await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=with_initials).run(conn) while True: change = await", "an asynchronous function that resolves every change in RethinkDB table :param item_class: GraphQL", "Bear in mind that this function is called only once when a new", "object is deleted and it's a XenObject, only its ref is returned :param", "graphql import ResolveInfo from rethinkdb import RethinkDB from rethinkdb.errors import ReqlOpFailedError from rx", "change: break if change['type'] == 'remove': value = change['old_val'] else: value = change['new_val']", "= type(f'{_class.__name__}OrDeleted', (graphene.Union, ), { \"Meta\": Meta, }) class Meta: default_resolver = dict_resolver", "type, table_name : str): \"\"\" Returns an asynchronous function that resolves every change", "type(f'{_class.__name__}OrDeleted', (graphene.Union, ), { \"Meta\": Meta, }) class Meta: default_resolver = dict_resolver return", "# }) return _class def resolve_xen_item_by_key(key_name:str = 'ref'): \"\"\" Returns an asynchronous function", "asyncio from dataclasses import dataclass from typing import Dict, Type import graphene from", "Enum import constants.re as re from authentication import BasicAuthenticator from connman import ReDBConnection", "'remove': value = change['old_val'] task_counter = tasks[value['ref']] task_counter.count -= 1 if task_counter.count ==", "if not user_authenticator or user_authenticator.is_admin() or not issubclass(xenobject_type, ACLXenObject): table = re.db.table(xenobject_type.db_table_name) else:", "change: break if change['type'] == 'remove' or change['new_val'] is None: yield None continue", "True: change = await changes.next() if not change: break if change['type'] == 'remove':", "Creates a subscription type for resolve_item_by_pkey This is suitable when one wants to", "GraphQL type to track changes on :return: GraphQL Union type: _class OR Deleted", "one wants to subscribe to changes for one particular item :param _class: :return:", "resolve_xen_item_by_key(key_name:str = 'ref'): \"\"\" Returns an asynchronous function that resolves every change in", "for change in builder.yield_values(): if not change: break if change['type'] == 'remove' or", "str_to_changetype(s: str) -> Change: if s == 'initial': return Change.Initial elif s ==", "ignore_initials=not with_initials) if not value['ref'] in tasks: tasks[value['ref']] = TaskCounter(task=asyncio.create_task(builder.put_values_in_queue())) else: tasks[value['ref']].count +=", ":return: ''' #return type(f'{_class.__name__}Subscription', # (ObjectType, ), # { # _class.__name__: graphene.Field(_class) #", "function that resolves every change in RethinkDB table :param item_class: GraphQL object type", "one of Initial, Add, Mod, Remove value: of type item_class } Create a", "= info.context.user_authenticator creator_task = asyncio.create_task(create_single_changefeeds(queue, info, authenticator, xenobject_type, with_initials, filter_function)) try: while True:", "import Observable from enum import Enum import constants.re as re from authentication import", "with the following shape: { changeType: one of Initial, Add, Mod, Remove value:", "xenobject_type = fields_for_return_type['_xenobject_type_'] queue = asyncio.Queue() authenticator = info.context.user_authenticator creator_task = asyncio.create_task(create_single_changefeeds(queue, info,", "None return table = re.db.table(table_name) changes = await table.get_all(key) \\ .pluck(*item_class._meta.fields)\\ .changes(include_types=True, include_initial=True).run(conn)", "info status=change['type'], ignore_initials=not with_initials) if not value['ref'] in tasks: tasks[value['ref']] = TaskCounter(task=asyncio.create_task(builder.put_values_in_queue())) else:", "table = re.db.table(table_name) changes = await table.get_all(key) \\ .pluck(*item_class._meta.fields)\\ .changes(include_types=True, include_initial=True).run(conn) while True:", "subscription candidate (0th arg) and an asyncio connection to work with DB (1st", "Change.Add elif s == 'remove': return Change.Remove elif s == 'change': return Change.Change", "has same shape as a table :param filter_function: this function is given a", "a new item is added, and with all initial items :return: \"\"\" def", "resolve_vdis is usage example. Bear in mind that this function is called only", "item_class.__name__ yield dict(change_type=str_to_changetype(change['type']), value=value) except asyncio.CancelledError: creator_task.cancel() return return Observable.from_future(iterable_to_items()) return resolve_items def", "track changes on :return: GraphQL Union type: _class OR Deleted \"\"\" class Meta:", "except asyncio.CancelledError: for task_counter in tasks.values(): task_counter.task.cancel() return except Exception as e: import", "@dataclass class TaskCounter: task : asyncio.Task count = 1 async def create_single_changefeeds(queue: asyncio.Queue,", "args: :return: ''' async def iterable_to_item(): async with ReDBConnection().get_async_connection() as conn: key =", "elif change['type'] == 'change': print(f\"Ref change?: {change}\") continue else: value = change['new_val'] if", "rx import Observable from enum import Enum import constants.re as re from authentication", "Deleted from handlers.graphql.utils.querybuilder.changefeedbuilder import ChangefeedBuilder from handlers.graphql.utils.querybuilder.get_fields import get_fields from utils.user import user_entities", "break if change['type'] == 'remove': value = change['old_val'] task_counter = tasks[value['ref']] task_counter.count -=", "(ObjectType, ), # { # _class.__name__: graphene.Field(_class) # }) return _class def resolve_xen_item_by_key(key_name:str", "Use True, when a Subscription is not used as a backer for Query", "a field with MakeSubscriptionWithChangeType(type) :param info: :return: ''' async def iterable_to_items(): async with", "info: ResolveInfo, user_authenticator : BasicAuthenticator, xenobject_type: Type[XenObject], with_initials : bool, filter_function=None): async with", "Union type: _class OR Deleted \"\"\" class Meta: types = (_class, Deleted, )", "when a new item is added, and with all initial items :return: \"\"\"", "Create a subscription type with change tracking. If an object is deleted and", "Type[XenObject], with_initials : bool, filter_function=None): async with ReDBConnection().get_async_connection() as conn: tasks: Dict[str, TaskCounter]", "task_counter = tasks[value['ref']] task_counter.count -= 1 if task_counter.count == 0: if not task_counter.task.done():", "type: _class OR Deleted \"\"\" class Meta: types = (_class, Deleted, ) change_type", "for resolve_item_by_pkey This is suitable when one wants to subscribe to changes for", "Initial, Add, Mod, Remove value: of type item_class } Create a field with", ":param with_initials: Supply subscription with initial values (default: False). Use True, when a", "1 async def create_single_changefeeds(queue: asyncio.Queue, info: ResolveInfo, user_authenticator : BasicAuthenticator, xenobject_type: Type[XenObject], with_initials", "function that resolves every change in RethinkDB table with item with said primary", "for entity in user_entities(user_authenticator)], index='userid') changes = await table.pluck('ref').changes(include_types=True, include_initial=True).run(conn) while True: try:", "include this item in our subscripion resolve_vdis is usage example. Bear in mind", "except asyncio.CancelledError: creator_task.cancel() return return Observable.from_future(iterable_to_items()) return resolve_items def resolve_item_by_key(item_class: type, table_name :", "key_name:str = 'ref'): \"\"\" Returns an asynchronous function that resolves every change in", "DB (1st arg). This function should return true or false answering whether we", ".pluck(*item_class._meta.fields)\\ .changes(include_types=True, include_initial=True).run(conn) while True: change = await changes.next() if not change: break", "dict_resolver from graphql import ResolveInfo from rethinkdb import RethinkDB from rethinkdb.errors import ReqlOpFailedError", "if filter_function and not (await filter_function(value['ref'], conn)): continue builder = ChangefeedBuilder(id=value['ref'], info=info, queue=queue,", "import ReDBConnection from handlers.graphql.types.deleted import Deleted from handlers.graphql.utils.querybuilder.changefeedbuilder import ChangefeedBuilder from handlers.graphql.utils.querybuilder.get_fields import", "graphene.Field(_class) # }) return _class def resolve_xen_item_by_key(key_name:str = 'ref'): \"\"\" Returns an asynchronous", "table :return: \"\"\" def resolve_items(root, info, with_initials: bool) -> Observable: ''' Returns subscription", "type) -> type: \"\"\" Create a subscription type with change tracking. If an", "else: raise ValueError(f\"No such ChangeType: {s}\") @dataclass class TaskCounter: task : asyncio.Task count", "), # { # _class.__name__: graphene.Field(_class) # }) return _class def resolve_xen_item_by_key(key_name:str =", "1 except asyncio.CancelledError: for task_counter in tasks.values(): task_counter.task.cancel() return except Exception as e:", "import graphene from graphene import ObjectType from graphene.types.resolver import dict_resolver from graphql import", "Create a field with MakeSubscriptionWithChangeType(type) :param info: :return: ''' async def iterable_to_items(): async", "with MakeSubscriptionWithChangeType(type) :param info: :return: ''' async def iterable_to_items(): async with ReDBConnection().get_async_connection() as", "that resolves every change in RethinkDB table with item with said primary key", "as a backer for Query ''' async def iterable_to_items(): fields_for_return_type = get_fields(info, ['value'])", "def iterable_to_item(): async with ReDBConnection().get_async_connection() as conn: key = args.get(key_name, None) if not", "'remove', 'old_val': { 'ref' : value['ref'] } }) del tasks[value['ref']] elif change['type'] ==", "{} try: if not user_authenticator or user_authenticator.is_admin() or not issubclass(xenobject_type, ACLXenObject): table =", "from graphene import ObjectType from graphene.types.resolver import dict_resolver from graphql import ResolveInfo from", "-> Change: if s == 'initial': return Change.Initial elif s == 'add': return", "said primary key If item is deleted or does not exist, returns null", "does not exist, returns null in place of an item :param item_class: A", "new item is added, and with all initial items :return: \"\"\" def resolve_items(root,", "{ changeType: one of Initial, Add, Mod, Remove value: of type item_class }", "tasks[value['ref']] elif change['type'] == 'change': print(f\"Ref change?: {change}\") continue else: value = change['new_val']", "GraphQL object type that has same shape as a table :param table: RethinkDB", "(await filter_function(value['ref'], conn)): continue builder = ChangefeedBuilder(id=value['ref'], info=info, queue=queue, additional_string=None, select_subfield=['value'], # {", "Meta }) def MakeSubscription(_class : type) -> type: ''' Creates a subscription type", "del tasks[value['ref']] elif change['type'] == 'change': print(f\"Ref change?: {change}\") continue else: value =", "info: :param with_initials: Supply subscription with initial values (default: False). Use True, when", "has the same shape as a table :param table: a RethinkDB table to", "task_counter.task.cancel() await queue.put({ 'type': 'remove', 'old_val': { 'ref' : value['ref'] } }) del", "resolve_item(root, info, **args) -> Observable: ''' Create a field with MakeSubscription(type) :param root:", "initial items :return: \"\"\" def resolve_items(root, info : ResolveInfo, with_initials : bool, **kwargs)", "changes = await table.pluck('ref').changes(include_types=True, include_initial=True).run(conn) while True: try: change = await changes.next() except", "Change.Change else: raise ValueError(f\"No such ChangeType: {s}\") @dataclass class TaskCounter: task : asyncio.Task", "), { \"Meta\": Meta, }) class Meta: default_resolver = dict_resolver return type(f'{_class.__name__}sSubscription', (ObjectType,", "select_subfield=['value'], # { value : {...} <-- this is what we need in", "subscription type with change tracking. If an object is deleted and it's a", "conn: table = re.db.table(table_name) changes = await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=with_initials).run(conn) while True: change =", "= 'remove' Change = 'change' def str_to_changetype(s: str) -> Change: if s ==", "yield None return builder = ChangefeedBuilder(key, info) async for change in builder.yield_values(): if", "enum import Enum import constants.re as re from authentication import BasicAuthenticator from connman", "return def MakeSubscriptionWithChangeType(_class : type) -> type: \"\"\" Create a subscription type with", "item is added, and with all initial items :return: \"\"\" def resolve_items(root, info", "true or false answering whether we should include this item in our subscripion", "Change.Remove elif s == 'change': return Change.Change else: raise ValueError(f\"No such ChangeType: {s}\")", "graphene.Field(change_type, required=True), 'Meta': Meta }) def MakeSubscription(_class : type) -> type: ''' Creates", "= 1 async def create_single_changefeeds(queue: asyncio.Queue, info: ResolveInfo, user_authenticator : BasicAuthenticator, xenobject_type: Type[XenObject],", "= re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity for entity in user_entities(user_authenticator)], index='userid') changes = await table.pluck('ref').changes(include_types=True, include_initial=True).run(conn) while", "with MakeSubscription(type) :param root: :param info: :param args: :return: ''' async def iterable_to_item():", ": type) -> type: \"\"\" Create a subscription type with change tracking. If", "conn: tasks: Dict[str, TaskCounter] = {} try: if not user_authenticator or user_authenticator.is_admin() or", "await changes.next() if not change: break if change['type'] == 'remove': value = change['old_val']", "TaskCounter(task=asyncio.create_task(builder.put_values_in_queue())) else: tasks[value['ref']].count += 1 except asyncio.CancelledError: for task_counter in tasks.values(): task_counter.task.cancel() return", ": value['ref'] } }) del tasks[value['ref']] elif change['type'] == 'change': print(f\"Ref change?: {change}\")", "= re.db.table(xenobject_type.db_table_name) else: table = re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity for entity in user_entities(user_authenticator)], index='userid') changes =", "0: if not task_counter.task.done(): task_counter.task.cancel() await queue.put({ 'type': 'remove', 'old_val': { 'ref' :", "this item in our subscripion resolve_vdis is usage example. Bear in mind that", "include_initial=True).run(conn) while True: try: change = await changes.next() except ReqlOpFailedError: return if not", "filter_function: this function is given a ref of potential subscription candidate (0th arg)", "task : asyncio.Task count = 1 async def create_single_changefeeds(queue: asyncio.Queue, info: ResolveInfo, user_authenticator", "change['type'] == 'change': print(f\"Ref change?: {change}\") continue else: value = change['new_val'] if filter_function", "type) -> type: ''' Creates a subscription type for resolve_item_by_pkey This is suitable", "import XenObject from xenadapter.aclxenobject import ACLXenObject class Change(graphene.Enum): Initial = 'initial' Add =", "elif s == 'remove': return Change.Remove elif s == 'change': return Change.Change else:", "= fields_for_return_type['_xenobject_type_'] queue = asyncio.Queue() authenticator = info.context.user_authenticator creator_task = asyncio.create_task(create_single_changefeeds(queue, info, authenticator,", ".changes(include_types=True, include_initial=True).run(conn) while True: change = await changes.next() if not change: break if", "typing import Dict, Type import graphene from graphene import ObjectType from graphene.types.resolver import", "else: value = change['new_val'] yield value return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_xen_items_changes(item_class: type,", "None) if not key: yield None return table = re.db.table(table_name) changes = await", "item is deleted or does not exist, returns null in place of an", "table :param filter_function: this function is given a ref of potential subscription candidate", "that has same shape as a table :param filter_function: this function is given", "True: try: change = await changes.next() except ReqlOpFailedError: return if not change: break", "subscription updates with the following shape: { changeType: one of Initial, Add, Mod,", ": type) -> type: ''' Creates a subscription type for resolve_item_by_pkey This is", ": str, key_name:str = 'ref'): \"\"\" Returns an asynchronous function that resolves every", ": str): \"\"\" Returns an asynchronous function that resolves every change in RethinkDB", "continue builder = ChangefeedBuilder(id=value['ref'], info=info, queue=queue, additional_string=None, select_subfield=['value'], # { value : {...}", "a table :param table: a RethinkDB table to retrieve updates from :return: function", "info=info, queue=queue, additional_string=None, select_subfield=['value'], # { value : {...} <-- this is what", "= re.db.table(table_name) changes = await table.get_all(key) \\ .pluck(*item_class._meta.fields)\\ .changes(include_types=True, include_initial=True).run(conn) while True: change", "async def iterable_to_items(): async with ReDBConnection().get_async_connection() as conn: table = re.db.table(table_name) changes =", "(default: False). Use True, when a Subscription is not used as a backer", "{ value : {...} <-- this is what we need in info status=change['type'],", "task_counter.task.done(): task_counter.task.cancel() await queue.put({ 'type': 'remove', 'old_val': { 'ref' : value['ref'] } })", "changes = await table.get_all(key) \\ .pluck(*item_class._meta.fields)\\ .changes(include_types=True, include_initial=True).run(conn) while True: change = await", "BasicAuthenticator from connman import ReDBConnection from handlers.graphql.types.deleted import Deleted from handlers.graphql.utils.querybuilder.changefeedbuilder import ChangefeedBuilder", "import Enum import constants.re as re from authentication import BasicAuthenticator from connman import", "value['ref'] } }) del tasks[value['ref']] elif change['type'] == 'change': print(f\"Ref change?: {change}\") continue", "== 'remove' or change['new_val'] is None: yield None continue else: value = change['new_val']", "change['old_val'] else: value = change['new_val'] value = item_class(**value) yield MakeSubscriptionWithChangeType(item_class)(change_type=str_to_changetype(change['type']), value=value) return Observable.from_future(iterable_to_items())", "resolve_all_items_changes(item_class: type, table_name : str): \"\"\" Returns an asynchronous function that resolves every", "authenticator, xenobject_type, with_initials, filter_function)) try: while True: change = await queue.get() if change['type']", "#return type(f'{_class.__name__}Subscription', # (ObjectType, ), # { # _class.__name__: graphene.Field(_class) # }) return", "with_initials, filter_function)) try: while True: change = await queue.get() if change['type'] == 'remove':", "type with change tracking. If an object is deleted and it's a XenObject,", "# { # _class.__name__: graphene.Field(_class) # }) return _class def resolve_xen_item_by_key(key_name:str = 'ref'):", "'change' def str_to_changetype(s: str) -> Change: if s == 'initial': return Change.Initial elif", "queue.get() if change['type'] == 'remove': value = change['old_val'] value['__typename'] = 'Deleted' else: value", "from enum import Enum import constants.re as re from authentication import BasicAuthenticator from", "= {} try: if not user_authenticator or user_authenticator.is_admin() or not issubclass(xenobject_type, ACLXenObject): table", "with ReDBConnection().get_async_connection() as conn: key = args.get(key_name, None) if not key: yield None", "in our subscripion resolve_vdis is usage example. Bear in mind that this function", ":param info: :return: ''' async def iterable_to_items(): async with ReDBConnection().get_async_connection() as conn: table", "asyncio.create_task(create_single_changefeeds(queue, info, authenticator, xenobject_type, with_initials, filter_function)) try: while True: change = await queue.get()", "type\"), 'value': graphene.Field(change_type, required=True), 'Meta': Meta }) def MakeSubscription(_class : type) -> type:", "import asyncio from dataclasses import dataclass from typing import Dict, Type import graphene", "yield None return table = re.db.table(table_name) changes = await table.get_all(key) \\ .pluck(*item_class._meta.fields)\\ .changes(include_types=True,", "= change['new_val'] yield value return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_xen_items_changes(item_class: type, filter_function=None): \"\"\"", "if not task_counter.task.done(): task_counter.task.cancel() await queue.put({ 'type': 'remove', 'old_val': { 'ref' : value['ref']", "asyncio.CancelledError: for task_counter in tasks.values(): task_counter.task.cancel() return except Exception as e: import sentry_sdk", "= await changes.next() if not change: break if change['type'] == 'remove' or change['new_val']", "False). Use True, when a Subscription is not used as a backer for", "required=True), 'Meta': Meta }) def MakeSubscription(_class : type) -> type: ''' Creates a", "iterable_to_item(): async with ReDBConnection().get_async_connection() as conn: key = args.get(key_name, None) if not key:", "**args) -> Observable: ''' Create a field with MakeSubscription(type) :param root: :param info:", "only once when a new item is added, and with all initial items", "added, and with all initial items :return: \"\"\" def resolve_items(root, info : ResolveInfo,", "value: of type item_class } Create a field with MakeSubscriptionWithChangeType(type) :param info: :param", "a subscription type for resolve_item_by_pkey This is suitable when one wants to subscribe", "str): \"\"\" Returns an asynchronous function that resolves every change in RethinkDB table", "task_counter in tasks.values(): task_counter.task.cancel() return except Exception as e: import sentry_sdk sentry_sdk.capture_exception(e) return", "resolve_items(root, info : ResolveInfo, with_initials : bool, **kwargs) -> Observable: ''' Returns subscription", "= change['old_val'] task_counter = tasks[value['ref']] task_counter.count -= 1 if task_counter.count == 0: if", "root: :param info: :param args: :return: ''' async def iterable_to_item(): key = args.get(key_name,", "every change in RethinkDB table with item with said primary key If item", "try: change = await changes.next() except ReqlOpFailedError: return if not change: break if", "import ACLXenObject class Change(graphene.Enum): Initial = 'initial' Add = 'add' Remove = 'remove'", "value['ref'] in tasks: tasks[value['ref']] = TaskCounter(task=asyncio.create_task(builder.put_values_in_queue())) else: tasks[value['ref']].count += 1 except asyncio.CancelledError: for", "True, when a Subscription is not used as a backer for Query '''", "type, filter_function=None): \"\"\" Returns an asynchronous function that resolves every change in RethinkDB", "type item_class } Create a field with MakeSubscriptionWithChangeType(type) :param info: :param with_initials: Supply", "args.get(key_name, None) if not key: yield None return table = re.db.table(table_name) changes =", "example. Bear in mind that this function is called only once when a", "type: \"\"\" Create a subscription type with change tracking. If an object is", "with_initials : bool, **kwargs) -> Observable: ''' Returns subscription updates with the following", "tasks: Dict[str, TaskCounter] = {} try: if not user_authenticator or user_authenticator.is_admin() or not", "returns Observable. Works with asyncio \"\"\" def resolve_item(root, info, **args) -> Observable: '''", "null in place of an item :param item_class: A GraphQL object type that", "in info status=change['type'], ignore_initials=not with_initials) if not value['ref'] in tasks: tasks[value['ref']] = TaskCounter(task=asyncio.create_task(builder.put_values_in_queue()))", "args.get(key_name, None) if not key: yield None return builder = ChangefeedBuilder(key, info) async", "return type(f'{_class.__name__}sSubscription', (ObjectType, ), { 'change_type': graphene.Field(Change, required=True, description=\"Change type\"), 'value': graphene.Field(change_type, required=True),", "import constants.re as re from authentication import BasicAuthenticator from connman import ReDBConnection from", "with MakeSubscriptionWithChangeType(type) :param info: :param with_initials: Supply subscription with initial values (default: False).", "table_name : str, key_name:str = 'ref'): \"\"\" Returns an asynchronous function that resolves", "item_class } Create a field with MakeSubscriptionWithChangeType(type) :param info: :return: ''' async def", "builder = ChangefeedBuilder(id=value['ref'], info=info, queue=queue, additional_string=None, select_subfield=['value'], # { value : {...} <--", "str) -> Change: if s == 'initial': return Change.Initial elif s == 'add':", "resolves every change in RethinkDB table with item with said primary key If", "TaskCounter: task : asyncio.Task count = 1 async def create_single_changefeeds(queue: asyncio.Queue, info: ResolveInfo,", "re from authentication import BasicAuthenticator from connman import ReDBConnection from handlers.graphql.types.deleted import Deleted", "what we need in info status=change['type'], ignore_initials=not with_initials) if not value['ref'] in tasks:", ") change_type = type(f'{_class.__name__}OrDeleted', (graphene.Union, ), { \"Meta\": Meta, }) class Meta: default_resolver", "wants to subscribe to changes for one particular item :param _class: :return: '''", "iterable_to_items(): fields_for_return_type = get_fields(info, ['value']) xenobject_type = fields_for_return_type['_xenobject_type_'] queue = asyncio.Queue() authenticator =", "args: :return: ''' async def iterable_to_item(): key = args.get(key_name, None) if not key:", "async with ReDBConnection().get_async_connection() as conn: key = args.get(key_name, None) if not key: yield", "return resolve_items def resolve_item_by_key(item_class: type, table_name : str, key_name:str = 'ref'): \"\"\" Returns", "not issubclass(xenobject_type, ACLXenObject): table = re.db.table(xenobject_type.db_table_name) else: table = re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity for entity in", "item in our subscripion resolve_vdis is usage example. Bear in mind that this", "else: value = change['new_val'] if filter_function and not (await filter_function(value['ref'], conn)): continue builder", "to track changes on :return: GraphQL Union type: _class OR Deleted \"\"\" class", "connection to work with DB (1st arg). This function should return true or", "None) if not key: yield None return builder = ChangefeedBuilder(key, info) async for", "ResolveInfo, with_initials : bool, **kwargs) -> Observable: ''' Returns subscription updates with the", "= change['new_val'] if filter_function and not (await filter_function(value['ref'], conn)): continue builder = ChangefeedBuilder(id=value['ref'],", "def iterable_to_items(): fields_for_return_type = get_fields(info, ['value']) xenobject_type = fields_for_return_type['_xenobject_type_'] queue = asyncio.Queue() authenticator", "with ReDBConnection().get_async_connection() as conn: table = re.db.table(table_name) changes = await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=with_initials).run(conn) while", "is not used as a backer for Query ''' async def iterable_to_items(): fields_for_return_type", "on :return: GraphQL Union type: _class OR Deleted \"\"\" class Meta: types =", "asyncio.Queue, info: ResolveInfo, user_authenticator : BasicAuthenticator, xenobject_type: Type[XenObject], with_initials : bool, filter_function=None): async", "following shape: { changeType: one of Initial, Add, Mod, Remove value: of type", "a backer for Query ''' async def iterable_to_items(): fields_for_return_type = get_fields(info, ['value']) xenobject_type", "async def iterable_to_item(): async with ReDBConnection().get_async_connection() as conn: key = args.get(key_name, None) if", "Meta: types = (_class, Deleted, ) change_type = type(f'{_class.__name__}OrDeleted', (graphene.Union, ), { \"Meta\":", "if not key: yield None return table = re.db.table(table_name) changes = await table.get_all(key)", "TaskCounter] = {} try: if not user_authenticator or user_authenticator.is_admin() or not issubclass(xenobject_type, ACLXenObject):", "== 'remove': value = change['old_val'] task_counter = tasks[value['ref']] task_counter.count -= 1 if task_counter.count", "ACLXenObject): table = re.db.table(xenobject_type.db_table_name) else: table = re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity for entity in user_entities(user_authenticator)], index='userid')", "filter_function=None): \"\"\" Returns an asynchronous function that resolves every change in RethinkDB table", "subscription type for resolve_item_by_pkey This is suitable when one wants to subscribe to", "required=True, description=\"Change type\"), 'value': graphene.Field(change_type, required=True), 'Meta': Meta }) def MakeSubscription(_class : type)", "return builder = ChangefeedBuilder(key, info) async for change in builder.yield_values(): if not change:", "== 'change': print(f\"Ref change?: {change}\") continue else: value = change['new_val'] if filter_function and", "else: tasks[value['ref']].count += 1 except asyncio.CancelledError: for task_counter in tasks.values(): task_counter.task.cancel() return except", "a RethinkDB table to retrieve updates from :return: function that returns Observable. Works", "Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_items_changes(item_class: type, table_name : str): \"\"\" Returns an asynchronous", ":param info: :param args: :return: ''' async def iterable_to_item(): async with ReDBConnection().get_async_connection() as", "'add' Remove = 'remove' Change = 'change' def str_to_changetype(s: str) -> Change: if", "= asyncio.create_task(create_single_changefeeds(queue, info, authenticator, xenobject_type, with_initials, filter_function)) try: while True: change = await", "changes.next() if not change: break if change['type'] == 'remove' or change['new_val'] is None:", "has same shape as a table :param table: RethinkDB table :return: \"\"\" def", "class Meta: types = (_class, Deleted, ) change_type = type(f'{_class.__name__}OrDeleted', (graphene.Union, ), {", "is deleted or does not exist, returns null in place of an item", "change = await queue.get() if change['type'] == 'remove': value = change['old_val'] value['__typename'] =", "Change(graphene.Enum): Initial = 'initial' Add = 'add' Remove = 'remove' Change = 'change'", "a Subscription is not used as a backer for Query ''' async def", "is what we need in info status=change['type'], ignore_initials=not with_initials) if not value['ref'] in", "RethinkDB table with item with said primary key If item is deleted or", "returns null in place of an item :param item_class: A GraphQL object type", "or change['new_val'] is None: yield None continue else: value = change['new_val'] yield value", "} }) del tasks[value['ref']] elif change['type'] == 'change': print(f\"Ref change?: {change}\") continue else:", "or false answering whether we should include this item in our subscripion resolve_vdis", "True: change = await changes.next() if not change: break if change['type'] == 'remove'", "item with said primary key If item is deleted or does not exist,", "our subscripion resolve_vdis is usage example. Bear in mind that this function is", "ref of potential subscription candidate (0th arg) and an asyncio connection to work", "type: ''' Creates a subscription type for resolve_item_by_pkey This is suitable when one", "\"\"\" Returns an asynchronous function that resolves every change in RethinkDB table with", "as a table :param table: a RethinkDB table to retrieve updates from :return:", "false answering whether we should include this item in our subscripion resolve_vdis is", "a subscription type with change tracking. If an object is deleted and it's", "change['old_val'] value['__typename'] = 'Deleted' else: value = change['new_val'] value['__typename'] = item_class.__name__ yield dict(change_type=str_to_changetype(change['type']),", "= change['new_val'] value['__typename'] = item_class.__name__ yield dict(change_type=str_to_changetype(change['type']), value=value) except asyncio.CancelledError: creator_task.cancel() return return", "s == 'remove': return Change.Remove elif s == 'change': return Change.Change else: raise", "type to track changes on :return: GraphQL Union type: _class OR Deleted \"\"\"", "info : ResolveInfo, with_initials : bool, **kwargs) -> Observable: ''' Returns subscription updates", "yield None continue else: value = change['new_val'] yield item_class(**value) return Observable.from_future(iterable_to_item()) return resolve_item", "change['new_val'] is None: yield None continue else: value = change['new_val'] yield item_class(**value) return", "and an asyncio connection to work with DB (1st arg). This function should", "== 0: if not task_counter.task.done(): task_counter.task.cancel() await queue.put({ 'type': 'remove', 'old_val': { 'ref'", "once when a new item is added, and with all initial items :return:", "(graphene.Union, ), { \"Meta\": Meta, }) class Meta: default_resolver = dict_resolver return type(f'{_class.__name__}sSubscription',", "= args.get(key_name, None) if not key: yield None return table = re.db.table(table_name) changes", ":return: \"\"\" def resolve_items(root, info, with_initials: bool) -> Observable: ''' Returns subscription updates", "elif s == 'change': return Change.Change else: raise ValueError(f\"No such ChangeType: {s}\") @dataclass", "updates from :return: function that returns Observable. Works with asyncio \"\"\" def resolve_item(root,", "type item_class } Create a field with MakeSubscriptionWithChangeType(type) :param info: :return: ''' async", "table :param item_class: GraphQL object type that has same shape as a table", "if not value['ref'] in tasks: tasks[value['ref']] = TaskCounter(task=asyncio.create_task(builder.put_values_in_queue())) else: tasks[value['ref']].count += 1 except", "except ReqlOpFailedError: return if not change: break if change['type'] == 'remove': value =", "asynchronous function that resolves every change in RethinkDB table :param item_class: GraphQL object", "value: of type item_class } Create a field with MakeSubscriptionWithChangeType(type) :param info: :return:", "def iterable_to_item(): key = args.get(key_name, None) if not key: yield None return builder", "type that has same shape as a table :param table: RethinkDB table :return:", "table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=with_initials).run(conn) while True: change = await changes.next() if not change: break if", "ReDBConnection().get_async_connection() as conn: key = args.get(key_name, None) if not key: yield None return", "queue = asyncio.Queue() authenticator = info.context.user_authenticator creator_task = asyncio.create_task(create_single_changefeeds(queue, info, authenticator, xenobject_type, with_initials,", "when one wants to subscribe to changes for one particular item :param _class:", "primary key If item is deleted or does not exist, returns null in", "} Create a field with MakeSubscriptionWithChangeType(type) :param info: :param with_initials: Supply subscription with", "== 'remove': value = change['old_val'] value['__typename'] = 'Deleted' else: value = change['new_val'] value['__typename']", "+= 1 except asyncio.CancelledError: for task_counter in tasks.values(): task_counter.task.cancel() return except Exception as", "This function should return true or false answering whether we should include this", "shape as a table :param table: RethinkDB table :return: \"\"\" def resolve_items(root, info,", "field with MakeSubscriptionWithChangeType(type) :param info: :return: ''' async def iterable_to_items(): async with ReDBConnection().get_async_connection()", "xenadapter.aclxenobject import ACLXenObject class Change(graphene.Enum): Initial = 'initial' Add = 'add' Remove =", "), { 'change_type': graphene.Field(Change, required=True, description=\"Change type\"), 'value': graphene.Field(change_type, required=True), 'Meta': Meta })", "else: value = change['new_val'] value = item_class(**value) yield MakeSubscriptionWithChangeType(item_class)(change_type=str_to_changetype(change['type']), value=value) return Observable.from_future(iterable_to_items()) return", "same shape as a table :param table: RethinkDB table :return: \"\"\" def resolve_items(root,", "subscripion resolve_vdis is usage example. Bear in mind that this function is called", "value = change['old_val'] value['__typename'] = 'Deleted' else: value = change['new_val'] value['__typename'] = item_class.__name__", "Returns subscription updates with the following shape: { changeType: one of Initial, Add,", "every change in RethinkDB table :param item_class: GraphQL object type that has same", "table :param table: a RethinkDB table to retrieve updates from :return: function that", "as a table :param table: RethinkDB table :return: \"\"\" def resolve_items(root, info, with_initials:", ":param item_class: GraphQL object type that has same shape as a table :param", "for Query ''' async def iterable_to_items(): fields_for_return_type = get_fields(info, ['value']) xenobject_type = fields_for_return_type['_xenobject_type_']", "value return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_xen_items_changes(item_class: type, filter_function=None): \"\"\" Returns an asynchronous", "with DB (1st arg). This function should return true or false answering whether", "'add': return Change.Add elif s == 'remove': return Change.Remove elif s == 'change':", "async def create_single_changefeeds(queue: asyncio.Queue, info: ResolveInfo, user_authenticator : BasicAuthenticator, xenobject_type: Type[XenObject], with_initials :", "= 'Deleted' else: value = change['new_val'] value['__typename'] = item_class.__name__ yield dict(change_type=str_to_changetype(change['type']), value=value) except", "Meta: default_resolver = dict_resolver return type(f'{_class.__name__}sSubscription', (ObjectType, ), { 'change_type': graphene.Field(Change, required=True, description=\"Change", "Subscription is not used as a backer for Query ''' async def iterable_to_items():", "{ \"Meta\": Meta, }) class Meta: default_resolver = dict_resolver return type(f'{_class.__name__}sSubscription', (ObjectType, ),", "not value['ref'] in tasks: tasks[value['ref']] = TaskCounter(task=asyncio.create_task(builder.put_values_in_queue())) else: tasks[value['ref']].count += 1 except asyncio.CancelledError:", "''' async def iterable_to_item(): async with ReDBConnection().get_async_connection() as conn: key = args.get(key_name, None)", "that returns Observable. Works with asyncio \"\"\" def resolve_item(root, info, **args) -> Observable:", "with asyncio \"\"\" def resolve_item(root, info, **args) -> Observable: ''' Create a field", "in tasks.values(): task_counter.task.cancel() return except Exception as e: import sentry_sdk sentry_sdk.capture_exception(e) return def", "s == 'add': return Change.Add elif s == 'remove': return Change.Remove elif s", "return _class def resolve_xen_item_by_key(key_name:str = 'ref'): \"\"\" Returns an asynchronous function that resolves", "answering whether we should include this item in our subscripion resolve_vdis is usage", "Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_xen_items_changes(item_class: type, filter_function=None): \"\"\" Returns an asynchronous function that", "await queue.put({ 'type': 'remove', 'old_val': { 'ref' : value['ref'] } }) del tasks[value['ref']]", "not change: break if change['type'] == 'remove': value = change['old_val'] task_counter = tasks[value['ref']]", "creator_task = asyncio.create_task(create_single_changefeeds(queue, info, authenticator, xenobject_type, with_initials, filter_function)) try: while True: change =", "dict_resolver return type(f'{_class.__name__}sSubscription', (ObjectType, ), { 'change_type': graphene.Field(Change, required=True, description=\"Change type\"), 'value': graphene.Field(change_type,", "not (await filter_function(value['ref'], conn)): continue builder = ChangefeedBuilder(id=value['ref'], info=info, queue=queue, additional_string=None, select_subfield=['value'], #", "True: change = await queue.get() if change['type'] == 'remove': value = change['old_val'] value['__typename']", "value = change['old_val'] else: value = change['new_val'] value = item_class(**value) yield MakeSubscriptionWithChangeType(item_class)(change_type=str_to_changetype(change['type']), value=value)", "or not issubclass(xenobject_type, ACLXenObject): table = re.db.table(xenobject_type.db_table_name) else: table = re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity for entity", "filter_function(value['ref'], conn)): continue builder = ChangefeedBuilder(id=value['ref'], info=info, queue=queue, additional_string=None, select_subfield=['value'], # { value", "from authentication import BasicAuthenticator from connman import ReDBConnection from handlers.graphql.types.deleted import Deleted from", "change = await changes.next() except ReqlOpFailedError: return if not change: break if change['type']", "bool, **kwargs) -> Observable: ''' Returns subscription updates with the following shape: {", "type that has the same shape as a table :param table: a RethinkDB", "and not (await filter_function(value['ref'], conn)): continue builder = ChangefeedBuilder(id=value['ref'], info=info, queue=queue, additional_string=None, select_subfield=['value'],", "from utils.user import user_entities from xenadapter.xenobject import XenObject from xenadapter.aclxenobject import ACLXenObject class", "Change.Initial elif s == 'add': return Change.Add elif s == 'remove': return Change.Remove", "= ChangefeedBuilder(key, info) async for change in builder.yield_values(): if not change: break if", "'initial' Add = 'add' Remove = 'remove' Change = 'change' def str_to_changetype(s: str)", "Returns an asynchronous function that resolves every change in RethinkDB table :param item_class:", "ChangefeedBuilder(key, info) async for change in builder.yield_values(): if not change: break if change['type']", "RethinkDB table to retrieve updates from :return: function that returns Observable. Works with", "change['new_val'] yield value return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_xen_items_changes(item_class: type, filter_function=None): \"\"\" Returns", "change['type'] == 'remove': value = change['old_val'] value['__typename'] = 'Deleted' else: value = change['new_val']", "with_initials : bool, filter_function=None): async with ReDBConnection().get_async_connection() as conn: tasks: Dict[str, TaskCounter] =", "is suitable when one wants to subscribe to changes for one particular item", "from connman import ReDBConnection from handlers.graphql.types.deleted import Deleted from handlers.graphql.utils.querybuilder.changefeedbuilder import ChangefeedBuilder from", "await queue.get() if change['type'] == 'remove': value = change['old_val'] value['__typename'] = 'Deleted' else:", "it's a XenObject, only its ref is returned :param _class: GraphQL type to", "not user_authenticator or user_authenticator.is_admin() or not issubclass(xenobject_type, ACLXenObject): table = re.db.table(xenobject_type.db_table_name) else: table", "\"\"\" def resolve_items(root, info, with_initials: bool) -> Observable: ''' Returns subscription updates with", "in tasks: tasks[value['ref']] = TaskCounter(task=asyncio.create_task(builder.put_values_in_queue())) else: tasks[value['ref']].count += 1 except asyncio.CancelledError: for task_counter", "= tasks[value['ref']] task_counter.count -= 1 if task_counter.count == 0: if not task_counter.task.done(): task_counter.task.cancel()", "Observable from enum import Enum import constants.re as re from authentication import BasicAuthenticator", "'old_val': { 'ref' : value['ref'] } }) del tasks[value['ref']] elif change['type'] == 'change':", "Query ''' async def iterable_to_items(): fields_for_return_type = get_fields(info, ['value']) xenobject_type = fields_for_return_type['_xenobject_type_'] queue", "GraphQL object type that has same shape as a table :param filter_function: this", "e: import sentry_sdk sentry_sdk.capture_exception(e) return def MakeSubscriptionWithChangeType(_class : type) -> type: \"\"\" Create", "not task_counter.task.done(): task_counter.task.cancel() await queue.put({ 'type': 'remove', 'old_val': { 'ref' : value['ref'] }", "item_class: GraphQL object type that has same shape as a table :param filter_function:", "value=value) except asyncio.CancelledError: creator_task.cancel() return return Observable.from_future(iterable_to_items()) return resolve_items def resolve_item_by_key(item_class: type, table_name", "fields_for_return_type['_xenobject_type_'] queue = asyncio.Queue() authenticator = info.context.user_authenticator creator_task = asyncio.create_task(create_single_changefeeds(queue, info, authenticator, xenobject_type,", "get_fields(info, ['value']) xenobject_type = fields_for_return_type['_xenobject_type_'] queue = asyncio.Queue() authenticator = info.context.user_authenticator creator_task =", "table :param table: RethinkDB table :return: \"\"\" def resolve_items(root, info, with_initials: bool) ->", "await table.get_all(key) \\ .pluck(*item_class._meta.fields)\\ .changes(include_types=True, include_initial=True).run(conn) while True: change = await changes.next() if", "a table :param table: RethinkDB table :return: \"\"\" def resolve_items(root, info, with_initials: bool)", "is None: yield None continue else: value = change['new_val'] yield value return Observable.from_future(iterable_to_item())", "to changes for one particular item :param _class: :return: ''' #return type(f'{_class.__name__}Subscription', #", "return if not change: break if change['type'] == 'remove': value = change['old_val'] task_counter", "entity in user_entities(user_authenticator)], index='userid') changes = await table.pluck('ref').changes(include_types=True, include_initial=True).run(conn) while True: try: change", "asyncio.Task count = 1 async def create_single_changefeeds(queue: asyncio.Queue, info: ResolveInfo, user_authenticator : BasicAuthenticator,", "= 'add' Remove = 'remove' Change = 'change' def str_to_changetype(s: str) -> Change:", "await table.pluck('ref').changes(include_types=True, include_initial=True).run(conn) while True: try: change = await changes.next() except ReqlOpFailedError: return", "mind that this function is called only once when a new item is", "change in RethinkDB table :param item_class: GraphQL object type that has same shape", "user_authenticator.is_admin() or not issubclass(xenobject_type, ACLXenObject): table = re.db.table(xenobject_type.db_table_name) else: table = re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity for", "filter_function=None): async with ReDBConnection().get_async_connection() as conn: tasks: Dict[str, TaskCounter] = {} try: if", "asyncio.CancelledError: creator_task.cancel() return return Observable.from_future(iterable_to_items()) return resolve_items def resolve_item_by_key(item_class: type, table_name : str,", "types = (_class, Deleted, ) change_type = type(f'{_class.__name__}OrDeleted', (graphene.Union, ), { \"Meta\": Meta,", "handlers.graphql.utils.querybuilder.changefeedbuilder import ChangefeedBuilder from handlers.graphql.utils.querybuilder.get_fields import get_fields from utils.user import user_entities from xenadapter.xenobject", "for task_counter in tasks.values(): task_counter.task.cancel() return except Exception as e: import sentry_sdk sentry_sdk.capture_exception(e)", "Works with asyncio \"\"\" def resolve_item(root, info, **args) -> Observable: ''' Create a", "<filename>backend/handlers/graphql/utils/subscription.py import asyncio from dataclasses import dataclass from typing import Dict, Type import", "= asyncio.Queue() authenticator = info.context.user_authenticator creator_task = asyncio.create_task(create_single_changefeeds(queue, info, authenticator, xenobject_type, with_initials, filter_function))", "a XenObject, only its ref is returned :param _class: GraphQL type to track", "when a Subscription is not used as a backer for Query ''' async", "from :return: function that returns Observable. Works with asyncio \"\"\" def resolve_item(root, info,", "change['old_val'] task_counter = tasks[value['ref']] task_counter.count -= 1 if task_counter.count == 0: if not", "None return builder = ChangefeedBuilder(key, info) async for change in builder.yield_values(): if not", "A GraphQL object type that has the same shape as a table :param", "= await changes.next() except ReqlOpFailedError: return if not change: break if change['type'] ==", ":return: \"\"\" def resolve_items(root, info : ResolveInfo, with_initials : bool, **kwargs) -> Observable:", "is given a ref of potential subscription candidate (0th arg) and an asyncio", "dataclasses import dataclass from typing import Dict, Type import graphene from graphene import", "RethinkDB table :param item_class: GraphQL object type that has same shape as a", "changes on :return: GraphQL Union type: _class OR Deleted \"\"\" class Meta: types", "''' Create a field with MakeSubscription(type) :param root: :param info: :param args: :return:", "re.db.table(table_name) changes = await table.get_all(key) \\ .pluck(*item_class._meta.fields)\\ .changes(include_types=True, include_initial=True).run(conn) while True: change =", "'Meta': Meta }) def MakeSubscription(_class : type) -> type: ''' Creates a subscription", "or user_authenticator.is_admin() or not issubclass(xenobject_type, ACLXenObject): table = re.db.table(xenobject_type.db_table_name) else: table = re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity", "ReDBConnection().get_async_connection() as conn: tasks: Dict[str, TaskCounter] = {} try: if not user_authenticator or", "items :return: \"\"\" def resolve_items(root, info : ResolveInfo, with_initials : bool, **kwargs) ->", "filter_function)) try: while True: change = await queue.get() if change['type'] == 'remove': value", "not key: yield None return table = re.db.table(table_name) changes = await table.get_all(key) \\", "'change_type': graphene.Field(Change, required=True, description=\"Change type\"), 'value': graphene.Field(change_type, required=True), 'Meta': Meta }) def MakeSubscription(_class", "that has the same shape as a table :param table: a RethinkDB table", "retrieve updates from :return: function that returns Observable. Works with asyncio \"\"\" def", "xenobject_type, with_initials, filter_function)) try: while True: change = await queue.get() if change['type'] ==", "info: :return: ''' async def iterable_to_items(): async with ReDBConnection().get_async_connection() as conn: table =", "the following shape: { changeType: one of Initial, Add, Mod, Remove value: of", "while True: change = await queue.get() if change['type'] == 'remove': value = change['old_val']", "xenobject_type: Type[XenObject], with_initials : bool, filter_function=None): async with ReDBConnection().get_async_connection() as conn: tasks: Dict[str,", "import ResolveInfo from rethinkdb import RethinkDB from rethinkdb.errors import ReqlOpFailedError from rx import", "a field with MakeSubscriptionWithChangeType(type) :param info: :param with_initials: Supply subscription with initial values", "function that returns Observable. Works with asyncio \"\"\" def resolve_item(root, info, **args) ->", ":return: ''' async def iterable_to_item(): async with ReDBConnection().get_async_connection() as conn: key = args.get(key_name,", "else: value = change['new_val'] yield item_class(**value) return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_items_changes(item_class: type,", "from xenadapter.aclxenobject import ACLXenObject class Change(graphene.Enum): Initial = 'initial' Add = 'add' Remove", ":param _class: GraphQL type to track changes on :return: GraphQL Union type: _class", "sentry_sdk sentry_sdk.capture_exception(e) return def MakeSubscriptionWithChangeType(_class : type) -> type: \"\"\" Create a subscription", "change: break if change['type'] == 'remove': value = change['old_val'] task_counter = tasks[value['ref']] task_counter.count", "one particular item :param _class: :return: ''' #return type(f'{_class.__name__}Subscription', # (ObjectType, ), #", "= await table.get_all(key) \\ .pluck(*item_class._meta.fields)\\ .changes(include_types=True, include_initial=True).run(conn) while True: change = await changes.next()", "= args.get(key_name, None) if not key: yield None return builder = ChangefeedBuilder(key, info)", "resolve_items def resolve_item_by_key(item_class: type, table_name : str, key_name:str = 'ref'): \"\"\" Returns an", "graphene import ObjectType from graphene.types.resolver import dict_resolver from graphql import ResolveInfo from rethinkdb", "== 'add': return Change.Add elif s == 'remove': return Change.Remove elif s ==", "tasks[value['ref']] task_counter.count -= 1 if task_counter.count == 0: if not task_counter.task.done(): task_counter.task.cancel() await", "the same shape as a table :param table: a RethinkDB table to retrieve", "from dataclasses import dataclass from typing import Dict, Type import graphene from graphene", "== 'change': return Change.Change else: raise ValueError(f\"No such ChangeType: {s}\") @dataclass class TaskCounter:", "used as a backer for Query ''' async def iterable_to_items(): fields_for_return_type = get_fields(info,", "def resolve_item_by_key(item_class: type, table_name : str, key_name:str = 'ref'): \"\"\" Returns an asynchronous", ":param info: :param args: :return: ''' async def iterable_to_item(): key = args.get(key_name, None)", "asyncio connection to work with DB (1st arg). This function should return true", "'value': graphene.Field(change_type, required=True), 'Meta': Meta }) def MakeSubscription(_class : type) -> type: '''", ": bool, **kwargs) -> Observable: ''' Returns subscription updates with the following shape:", "authenticator = info.context.user_authenticator creator_task = asyncio.create_task(create_single_changefeeds(queue, info, authenticator, xenobject_type, with_initials, filter_function)) try: while", "that has same shape as a table :param table: RethinkDB table :return: \"\"\"", "break if change['type'] == 'remove' or change['new_val'] is None: yield None continue else:", "user_entities from xenadapter.xenobject import XenObject from xenadapter.aclxenobject import ACLXenObject class Change(graphene.Enum): Initial =", "item_class: A GraphQL object type that has the same shape as a table", "constants.re as re from authentication import BasicAuthenticator from connman import ReDBConnection from handlers.graphql.types.deleted", "'change': return Change.Change else: raise ValueError(f\"No such ChangeType: {s}\") @dataclass class TaskCounter: task", ": ResolveInfo, with_initials : bool, **kwargs) -> Observable: ''' Returns subscription updates with", "await changes.next() except ReqlOpFailedError: return if not change: break if change['type'] == 'remove':", "\"\"\" Create a subscription type with change tracking. If an object is deleted", "\"\"\" class Meta: types = (_class, Deleted, ) change_type = type(f'{_class.__name__}OrDeleted', (graphene.Union, ),", "that this function is called only once when a new item is added,", "str, key_name:str = 'ref'): \"\"\" Returns an asynchronous function that resolves every change", "is called only once when a new item is added, and with all", "Initial = 'initial' Add = 'add' Remove = 'remove' Change = 'change' def", "asyncio \"\"\" def resolve_item(root, info, **args) -> Observable: ''' Create a field with", ":param filter_function: this function is given a ref of potential subscription candidate (0th", "only its ref is returned :param _class: GraphQL type to track changes on", "s == 'initial': return Change.Initial elif s == 'add': return Change.Add elif s", "''' async def iterable_to_items(): fields_for_return_type = get_fields(info, ['value']) xenobject_type = fields_for_return_type['_xenobject_type_'] queue =", "'change': print(f\"Ref change?: {change}\") continue else: value = change['new_val'] if filter_function and not", "import dict_resolver from graphql import ResolveInfo from rethinkdb import RethinkDB from rethinkdb.errors import", "''' Creates a subscription type for resolve_item_by_pkey This is suitable when one wants", "authentication import BasicAuthenticator from connman import ReDBConnection from handlers.graphql.types.deleted import Deleted from handlers.graphql.utils.querybuilder.changefeedbuilder", "Observable: ''' Create a field with MakeSubscription(type) :param root: :param info: :param args:", "key = args.get(key_name, None) if not key: yield None return builder = ChangefeedBuilder(key,", "same shape as a table :param filter_function: this function is given a ref", "return true or false answering whether we should include this item in our", "dict(change_type=str_to_changetype(change['type']), value=value) except asyncio.CancelledError: creator_task.cancel() return return Observable.from_future(iterable_to_items()) return resolve_items def resolve_item_by_key(item_class: type,", "await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=with_initials).run(conn) while True: change = await changes.next() if not change: break", "graphene.Field(Change, required=True, description=\"Change type\"), 'value': graphene.Field(change_type, required=True), 'Meta': Meta }) def MakeSubscription(_class :", "should include this item in our subscripion resolve_vdis is usage example. Bear in", "try: while True: change = await queue.get() if change['type'] == 'remove': value =", ":param table: RethinkDB table :return: \"\"\" def resolve_items(root, info, with_initials: bool) -> Observable:", "in RethinkDB table :param item_class: GraphQL object type that has same shape as", "ChangefeedBuilder from handlers.graphql.utils.querybuilder.get_fields import get_fields from utils.user import user_entities from xenadapter.xenobject import XenObject", "is usage example. Bear in mind that this function is called only once", "import Dict, Type import graphene from graphene import ObjectType from graphene.types.resolver import dict_resolver", "deleted or does not exist, returns null in place of an item :param", "else: table = re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity for entity in user_entities(user_authenticator)], index='userid') changes = await table.pluck('ref').changes(include_types=True,", "{s}\") @dataclass class TaskCounter: task : asyncio.Task count = 1 async def create_single_changefeeds(queue:", "'Deleted' else: value = change['new_val'] value['__typename'] = item_class.__name__ yield dict(change_type=str_to_changetype(change['type']), value=value) except asyncio.CancelledError:", "while True: change = await changes.next() if not change: break if change['type'] ==", "info, with_initials: bool) -> Observable: ''' Returns subscription updates with the following shape:", "is added, and with all initial items :return: \"\"\" def resolve_items(root, info :", "re.db.table(table_name) changes = await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=with_initials).run(conn) while True: change = await changes.next() if", "user_authenticator : BasicAuthenticator, xenobject_type: Type[XenObject], with_initials : bool, filter_function=None): async with ReDBConnection().get_async_connection() as", "info, **args) -> Observable: ''' Create a field with MakeSubscription(type) :param root: :param", "change_type = type(f'{_class.__name__}OrDeleted', (graphene.Union, ), { \"Meta\": Meta, }) class Meta: default_resolver =", "updates with the following shape: { changeType: one of Initial, Add, Mod, Remove", "continue else: value = change['new_val'] if filter_function and not (await filter_function(value['ref'], conn)): continue", "as conn: table = re.db.table(table_name) changes = await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=with_initials).run(conn) while True: change", "ObjectType from graphene.types.resolver import dict_resolver from graphql import ResolveInfo from rethinkdb import RethinkDB", "all initial items :return: \"\"\" def resolve_items(root, info : ResolveInfo, with_initials : bool,", "shape as a table :param table: a RethinkDB table to retrieve updates from", "Meta, }) class Meta: default_resolver = dict_resolver return type(f'{_class.__name__}sSubscription', (ObjectType, ), { 'change_type':", "yield value return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_xen_items_changes(item_class: type, filter_function=None): \"\"\" Returns an", "object type that has the same shape as a table :param table: a", "for one particular item :param _class: :return: ''' #return type(f'{_class.__name__}Subscription', # (ObjectType, ),", "with_initials: bool) -> Observable: ''' Returns subscription updates with the following shape: {", "if change['type'] == 'remove': value = change['old_val'] else: value = change['new_val'] value =", "(_class, Deleted, ) change_type = type(f'{_class.__name__}OrDeleted', (graphene.Union, ), { \"Meta\": Meta, }) class", "potential subscription candidate (0th arg) and an asyncio connection to work with DB", "task_counter.count -= 1 if task_counter.count == 0: if not task_counter.task.done(): task_counter.task.cancel() await queue.put({", "queue.put({ 'type': 'remove', 'old_val': { 'ref' : value['ref'] } }) del tasks[value['ref']] elif", "task_counter.task.cancel() return except Exception as e: import sentry_sdk sentry_sdk.capture_exception(e) return def MakeSubscriptionWithChangeType(_class :", "table_name : str): \"\"\" Returns an asynchronous function that resolves every change in", "= 'initial' Add = 'add' Remove = 'remove' Change = 'change' def str_to_changetype(s:", "table = re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity for entity in user_entities(user_authenticator)], index='userid') changes = await table.pluck('ref').changes(include_types=True, include_initial=True).run(conn)", "return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_xen_items_changes(item_class: type, filter_function=None): \"\"\" Returns an asynchronous function", "info: :param args: :return: ''' async def iterable_to_item(): async with ReDBConnection().get_async_connection() as conn:", "subscription with initial values (default: False). Use True, when a Subscription is not", "value = change['new_val'] value['__typename'] = item_class.__name__ yield dict(change_type=str_to_changetype(change['type']), value=value) except asyncio.CancelledError: creator_task.cancel() return", "change = await changes.next() if not change: break if change['type'] == 'remove' or", "= await queue.get() if change['type'] == 'remove': value = change['old_val'] value['__typename'] = 'Deleted'", "import ObjectType from graphene.types.resolver import dict_resolver from graphql import ResolveInfo from rethinkdb import", "}) def MakeSubscription(_class : type) -> type: ''' Creates a subscription type for", "resolves every change in RethinkDB table :param item_class: GraphQL object type that has", "xenadapter.xenobject import XenObject from xenadapter.aclxenobject import ACLXenObject class Change(graphene.Enum): Initial = 'initial' Add", "-> type: \"\"\" Create a subscription type with change tracking. If an object", "table to retrieve updates from :return: function that returns Observable. Works with asyncio", "item_class } Create a field with MakeSubscriptionWithChangeType(type) :param info: :param with_initials: Supply subscription", ":param root: :param info: :param args: :return: ''' async def iterable_to_item(): async with", "table = re.db.table(xenobject_type.db_table_name) else: table = re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity for entity in user_entities(user_authenticator)], index='userid') changes", "OR Deleted \"\"\" class Meta: types = (_class, Deleted, ) change_type = type(f'{_class.__name__}OrDeleted',", "async def iterable_to_items(): fields_for_return_type = get_fields(info, ['value']) xenobject_type = fields_for_return_type['_xenobject_type_'] queue = asyncio.Queue()", "{ # _class.__name__: graphene.Field(_class) # }) return _class def resolve_xen_item_by_key(key_name:str = 'ref'): \"\"\"", "ReqlOpFailedError from rx import Observable from enum import Enum import constants.re as re", "= get_fields(info, ['value']) xenobject_type = fields_for_return_type['_xenobject_type_'] queue = asyncio.Queue() authenticator = info.context.user_authenticator creator_task", "as re from authentication import BasicAuthenticator from connman import ReDBConnection from handlers.graphql.types.deleted import", "with item with said primary key If item is deleted or does not", "def resolve_items(root, info : ResolveInfo, with_initials : bool, **kwargs) -> Observable: ''' Returns", "Remove value: of type item_class } Create a field with MakeSubscriptionWithChangeType(type) :param info:", "from xenadapter.xenobject import XenObject from xenadapter.aclxenobject import ACLXenObject class Change(graphene.Enum): Initial = 'initial'", "arg) and an asyncio connection to work with DB (1st arg). This function", "RethinkDB from rethinkdb.errors import ReqlOpFailedError from rx import Observable from enum import Enum", "''' #return type(f'{_class.__name__}Subscription', # (ObjectType, ), # { # _class.__name__: graphene.Field(_class) # })", "'ref'): \"\"\" Returns an asynchronous function that resolves every change in RethinkDB table", "value['__typename'] = item_class.__name__ yield dict(change_type=str_to_changetype(change['type']), value=value) except asyncio.CancelledError: creator_task.cancel() return return Observable.from_future(iterable_to_items()) return", "ResolveInfo, user_authenticator : BasicAuthenticator, xenobject_type: Type[XenObject], with_initials : bool, filter_function=None): async with ReDBConnection().get_async_connection()", "def str_to_changetype(s: str) -> Change: if s == 'initial': return Change.Initial elif s", "return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_items_changes(item_class: type, table_name : str): \"\"\" Returns an", "= re.db.table(table_name) changes = await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=with_initials).run(conn) while True: change = await changes.next()", "except Exception as e: import sentry_sdk sentry_sdk.capture_exception(e) return def MakeSubscriptionWithChangeType(_class : type) ->", "root: :param info: :param args: :return: ''' async def iterable_to_item(): async with ReDBConnection().get_async_connection()", "this is what we need in info status=change['type'], ignore_initials=not with_initials) if not value['ref']", "or change['new_val'] is None: yield None continue else: value = change['new_val'] yield item_class(**value)", "\"Meta\": Meta, }) class Meta: default_resolver = dict_resolver return type(f'{_class.__name__}sSubscription', (ObjectType, ), {", "_class def resolve_xen_item_by_key(key_name:str = 'ref'): \"\"\" Returns an asynchronous function that resolves every", "as a table :param filter_function: this function is given a ref of potential", "type(f'{_class.__name__}sSubscription', (ObjectType, ), { 'change_type': graphene.Field(Change, required=True, description=\"Change type\"), 'value': graphene.Field(change_type, required=True), 'Meta':", "subscribe to changes for one particular item :param _class: :return: ''' #return type(f'{_class.__name__}Subscription',", "} Create a field with MakeSubscriptionWithChangeType(type) :param info: :return: ''' async def iterable_to_items():", "resolve_item def resolve_all_xen_items_changes(item_class: type, filter_function=None): \"\"\" Returns an asynchronous function that resolves every", "from rx import Observable from enum import Enum import constants.re as re from", "change in builder.yield_values(): if not change: break if change['type'] == 'remove' or change['new_val']", "change['new_val'] value['__typename'] = item_class.__name__ yield dict(change_type=str_to_changetype(change['type']), value=value) except asyncio.CancelledError: creator_task.cancel() return return Observable.from_future(iterable_to_items())", "as conn: key = args.get(key_name, None) if not key: yield None return table", "1 if task_counter.count == 0: if not task_counter.task.done(): task_counter.task.cancel() await queue.put({ 'type': 'remove',", "return except Exception as e: import sentry_sdk sentry_sdk.capture_exception(e) return def MakeSubscriptionWithChangeType(_class : type)", "additional_string=None, select_subfield=['value'], # { value : {...} <-- this is what we need", "= 'ref'): \"\"\" Returns an asynchronous function that resolves every change in RethinkDB", "tracking. If an object is deleted and it's a XenObject, only its ref", "if task_counter.count == 0: if not task_counter.task.done(): task_counter.task.cancel() await queue.put({ 'type': 'remove', 'old_val':", "called only once when a new item is added, and with all initial", "}) return _class def resolve_xen_item_by_key(key_name:str = 'ref'): \"\"\" Returns an asynchronous function that", "if not key: yield None return builder = ChangefeedBuilder(key, info) async for change", "info: :param args: :return: ''' async def iterable_to_item(): key = args.get(key_name, None) if", "field with MakeSubscriptionWithChangeType(type) :param info: :param with_initials: Supply subscription with initial values (default:", "such ChangeType: {s}\") @dataclass class TaskCounter: task : asyncio.Task count = 1 async", "exist, returns null in place of an item :param item_class: A GraphQL object", "= (_class, Deleted, ) change_type = type(f'{_class.__name__}OrDeleted', (graphene.Union, ), { \"Meta\": Meta, })", ":param item_class: A GraphQL object type that has the same shape as a", "value = change['new_val'] value = item_class(**value) yield MakeSubscriptionWithChangeType(item_class)(change_type=str_to_changetype(change['type']), value=value) return Observable.from_future(iterable_to_items()) return resolve_items", "change['type'] == 'remove': value = change['old_val'] task_counter = tasks[value['ref']] task_counter.count -= 1 if", "yield None continue else: value = change['new_val'] yield value return Observable.from_future(iterable_to_item()) return resolve_item", "from graphene.types.resolver import dict_resolver from graphql import ResolveInfo from rethinkdb import RethinkDB from", "yield dict(change_type=str_to_changetype(change['type']), value=value) except asyncio.CancelledError: creator_task.cancel() return return Observable.from_future(iterable_to_items()) return resolve_items def resolve_item_by_key(item_class:", "creator_task.cancel() return return Observable.from_future(iterable_to_items()) return resolve_items def resolve_item_by_key(item_class: type, table_name : str, key_name:str", "key: yield None return table = re.db.table(table_name) changes = await table.get_all(key) \\ .pluck(*item_class._meta.fields)\\", "= await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=with_initials).run(conn) while True: change = await changes.next() if not change:", "await changes.next() if not change: break if change['type'] == 'remove' or change['new_val'] is", "ReDBConnection().get_async_connection() as conn: table = re.db.table(table_name) changes = await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=with_initials).run(conn) while True:", "in user_entities(user_authenticator)], index='userid') changes = await table.pluck('ref').changes(include_types=True, include_initial=True).run(conn) while True: try: change =", "try: if not user_authenticator or user_authenticator.is_admin() or not issubclass(xenobject_type, ACLXenObject): table = re.db.table(xenobject_type.db_table_name)", "of type item_class } Create a field with MakeSubscriptionWithChangeType(type) :param info: :param with_initials:", "resolve_all_xen_items_changes(item_class: type, filter_function=None): \"\"\" Returns an asynchronous function that resolves every change in", "resolve_items(root, info, with_initials: bool) -> Observable: ''' Returns subscription updates with the following", "if not change: break if change['type'] == 'remove': value = change['old_val'] else: value", "async for change in builder.yield_values(): if not change: break if change['type'] == 'remove'", "# _class.__name__: graphene.Field(_class) # }) return _class def resolve_xen_item_by_key(key_name:str = 'ref'): \"\"\" Returns", "Returns an asynchronous function that resolves every change in RethinkDB table with item", "get_fields from utils.user import user_entities from xenadapter.xenobject import XenObject from xenadapter.aclxenobject import ACLXenObject", "in place of an item :param item_class: A GraphQL object type that has", "need in info status=change['type'], ignore_initials=not with_initials) if not value['ref'] in tasks: tasks[value['ref']] =", "with_initials: Supply subscription with initial values (default: False). Use True, when a Subscription", "an item :param item_class: A GraphQL object type that has the same shape", "while True: try: change = await changes.next() except ReqlOpFailedError: return if not change:", "candidate (0th arg) and an asyncio connection to work with DB (1st arg).", "key If item is deleted or does not exist, returns null in place", "function is called only once when a new item is added, and with", "yield item_class(**value) return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_items_changes(item_class: type, table_name : str): \"\"\"", "key = args.get(key_name, None) if not key: yield None return table = re.db.table(table_name)", "we should include this item in our subscripion resolve_vdis is usage example. Bear", "not key: yield None return builder = ChangefeedBuilder(key, info) async for change in", "if s == 'initial': return Change.Initial elif s == 'add': return Change.Add elif", "= 'change' def str_to_changetype(s: str) -> Change: if s == 'initial': return Change.Initial", "return resolve_item def resolve_all_xen_items_changes(item_class: type, filter_function=None): \"\"\" Returns an asynchronous function that resolves", "Create a field with MakeSubscriptionWithChangeType(type) :param info: :param with_initials: Supply subscription with initial", "change['new_val'] is None: yield None continue else: value = change['new_val'] yield value return", "If item is deleted or does not exist, returns null in place of", "values (default: False). Use True, when a Subscription is not used as a", "s == 'change': return Change.Change else: raise ValueError(f\"No such ChangeType: {s}\") @dataclass class", "change['new_val'] yield item_class(**value) return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_items_changes(item_class: type, table_name : str):", "Add, Mod, Remove value: of type item_class } Create a field with MakeSubscriptionWithChangeType(type)", "same shape as a table :param table: a RethinkDB table to retrieve updates", "None continue else: value = change['new_val'] yield value return Observable.from_future(iterable_to_item()) return resolve_item def", "change = await changes.next() if not change: break if change['type'] == 'remove': value", "= change['old_val'] else: value = change['new_val'] value = item_class(**value) yield MakeSubscriptionWithChangeType(item_class)(change_type=str_to_changetype(change['type']), value=value) return", "return table = re.db.table(table_name) changes = await table.get_all(key) \\ .pluck(*item_class._meta.fields)\\ .changes(include_types=True, include_initial=True).run(conn) while", "ref is returned :param _class: GraphQL type to track changes on :return: GraphQL", "None: yield None continue else: value = change['new_val'] yield value return Observable.from_future(iterable_to_item()) return", "import Deleted from handlers.graphql.utils.querybuilder.changefeedbuilder import ChangefeedBuilder from handlers.graphql.utils.querybuilder.get_fields import get_fields from utils.user import", "is deleted and it's a XenObject, only its ref is returned :param _class:", "-= 1 if task_counter.count == 0: if not task_counter.task.done(): task_counter.task.cancel() await queue.put({ 'type':", "status=change['type'], ignore_initials=not with_initials) if not value['ref'] in tasks: tasks[value['ref']] = TaskCounter(task=asyncio.create_task(builder.put_values_in_queue())) else: tasks[value['ref']].count", "= item_class.__name__ yield dict(change_type=str_to_changetype(change['type']), value=value) except asyncio.CancelledError: creator_task.cancel() return return Observable.from_future(iterable_to_items()) return resolve_items", "return Change.Initial elif s == 'add': return Change.Add elif s == 'remove': return", "= change['old_val'] value['__typename'] = 'Deleted' else: value = change['new_val'] value['__typename'] = item_class.__name__ yield", "type that has same shape as a table :param filter_function: this function is", "re.db.table(xenobject_type.db_table_name) else: table = re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity for entity in user_entities(user_authenticator)], index='userid') changes = await", "tasks[value['ref']] = TaskCounter(task=asyncio.create_task(builder.put_values_in_queue())) else: tasks[value['ref']].count += 1 except asyncio.CancelledError: for task_counter in tasks.values():", "from rethinkdb import RethinkDB from rethinkdb.errors import ReqlOpFailedError from rx import Observable from", "ACLXenObject class Change(graphene.Enum): Initial = 'initial' Add = 'add' Remove = 'remove' Change", "''' async def iterable_to_item(): key = args.get(key_name, None) if not key: yield None", "def MakeSubscriptionWithChangeType(_class : type) -> type: \"\"\" Create a subscription type with change", "is returned :param _class: GraphQL type to track changes on :return: GraphQL Union", "with initial values (default: False). Use True, when a Subscription is not used", "ValueError(f\"No such ChangeType: {s}\") @dataclass class TaskCounter: task : asyncio.Task count = 1", "Type import graphene from graphene import ObjectType from graphene.types.resolver import dict_resolver from graphql", "print(f\"Ref change?: {change}\") continue else: value = change['new_val'] if filter_function and not (await", "fields_for_return_type = get_fields(info, ['value']) xenobject_type = fields_for_return_type['_xenobject_type_'] queue = asyncio.Queue() authenticator = info.context.user_authenticator", "change?: {change}\") continue else: value = change['new_val'] if filter_function and not (await filter_function(value['ref'],", "ChangefeedBuilder(id=value['ref'], info=info, queue=queue, additional_string=None, select_subfield=['value'], # { value : {...} <-- this is", "a field with MakeSubscription(type) :param root: :param info: :param args: :return: ''' async", "default_resolver = dict_resolver return type(f'{_class.__name__}sSubscription', (ObjectType, ), { 'change_type': graphene.Field(Change, required=True, description=\"Change type\"),", "GraphQL object type that has the same shape as a table :param table:", "\"\"\" Returns an asynchronous function that resolves every change in RethinkDB table :param", "import RethinkDB from rethinkdb.errors import ReqlOpFailedError from rx import Observable from enum import", "continue else: value = change['new_val'] yield value return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_xen_items_changes(item_class:", "given a ref of potential subscription candidate (0th arg) and an asyncio connection", "MakeSubscription(_class : type) -> type: ''' Creates a subscription type for resolve_item_by_pkey This", "if change['type'] == 'remove': value = change['old_val'] value['__typename'] = 'Deleted' else: value =", "from handlers.graphql.utils.querybuilder.get_fields import get_fields from utils.user import user_entities from xenadapter.xenobject import XenObject from", "{change}\") continue else: value = change['new_val'] if filter_function and not (await filter_function(value['ref'], conn)):", "return Observable.from_future(iterable_to_items()) return resolve_items def resolve_item_by_key(item_class: type, table_name : str, key_name:str = 'ref'):", "as e: import sentry_sdk sentry_sdk.capture_exception(e) return def MakeSubscriptionWithChangeType(_class : type) -> type: \"\"\"", "else: value = change['new_val'] value['__typename'] = item_class.__name__ yield dict(change_type=str_to_changetype(change['type']), value=value) except asyncio.CancelledError: creator_task.cancel()", "re.db.table(f'{xenobject_type.db_table_name}_user').get_all(*[entity for entity in user_entities(user_authenticator)], index='userid') changes = await table.pluck('ref').changes(include_types=True, include_initial=True).run(conn) while True:", "table: a RethinkDB table to retrieve updates from :return: function that returns Observable.", "import get_fields from utils.user import user_entities from xenadapter.xenobject import XenObject from xenadapter.aclxenobject import", "filter_function and not (await filter_function(value['ref'], conn)): continue builder = ChangefeedBuilder(id=value['ref'], info=info, queue=queue, additional_string=None,", "and it's a XenObject, only its ref is returned :param _class: GraphQL type", ":return: GraphQL Union type: _class OR Deleted \"\"\" class Meta: types = (_class,", "\"\"\" def resolve_item(root, info, **args) -> Observable: ''' Create a field with MakeSubscription(type)", "return Change.Add elif s == 'remove': return Change.Remove elif s == 'change': return", "a ref of potential subscription candidate (0th arg) and an asyncio connection to", "builder = ChangefeedBuilder(key, info) async for change in builder.yield_values(): if not change: break", "rethinkdb import RethinkDB from rethinkdb.errors import ReqlOpFailedError from rx import Observable from enum", "from rethinkdb.errors import ReqlOpFailedError from rx import Observable from enum import Enum import", "table with item with said primary key If item is deleted or does", "changes.next() if not change: break if change['type'] == 'remove': value = change['old_val'] else:", "this function is called only once when a new item is added, and", "Exception as e: import sentry_sdk sentry_sdk.capture_exception(e) return def MakeSubscriptionWithChangeType(_class : type) -> type:", "of type item_class } Create a field with MakeSubscriptionWithChangeType(type) :param info: :return: '''", "-> Observable: ''' Create a field with MakeSubscription(type) :param root: :param info: :param", ": bool, filter_function=None): async with ReDBConnection().get_async_connection() as conn: tasks: Dict[str, TaskCounter] = {}", "['value']) xenobject_type = fields_for_return_type['_xenobject_type_'] queue = asyncio.Queue() authenticator = info.context.user_authenticator creator_task = asyncio.create_task(create_single_changefeeds(queue,", "table: RethinkDB table :return: \"\"\" def resolve_items(root, info, with_initials: bool) -> Observable: '''", "changes.next() except ReqlOpFailedError: return if not change: break if change['type'] == 'remove': value", "value['__typename'] = 'Deleted' else: value = change['new_val'] value['__typename'] = item_class.__name__ yield dict(change_type=str_to_changetype(change['type']), value=value)", "changes for one particular item :param _class: :return: ''' #return type(f'{_class.__name__}Subscription', # (ObjectType,", "value = change['old_val'] task_counter = tasks[value['ref']] task_counter.count -= 1 if task_counter.count == 0:", "builder.yield_values(): if not change: break if change['type'] == 'remove' or change['new_val'] is None:", "if not change: break if change['type'] == 'remove': value = change['old_val'] task_counter =", "item_class: GraphQL object type that has same shape as a table :param table:", "RethinkDB table :return: \"\"\" def resolve_items(root, info, with_initials: bool) -> Observable: ''' Returns", "description=\"Change type\"), 'value': graphene.Field(change_type, required=True), 'Meta': Meta }) def MakeSubscription(_class : type) ->", "''' Returns subscription updates with the following shape: { changeType: one of Initial,", "Add = 'add' Remove = 'remove' Change = 'change' def str_to_changetype(s: str) ->", "Dict[str, TaskCounter] = {} try: if not user_authenticator or user_authenticator.is_admin() or not issubclass(xenobject_type,", "def resolve_items(root, info, with_initials: bool) -> Observable: ''' Returns subscription updates with the", ":return: ''' async def iterable_to_item(): key = args.get(key_name, None) if not key: yield", "-> type: ''' Creates a subscription type for resolve_item_by_pkey This is suitable when", "asynchronous function that resolves every change in RethinkDB table with item with said", "{ 'change_type': graphene.Field(Change, required=True, description=\"Change type\"), 'value': graphene.Field(change_type, required=True), 'Meta': Meta }) def", "index='userid') changes = await table.pluck('ref').changes(include_types=True, include_initial=True).run(conn) while True: try: change = await changes.next()", ":return: function that returns Observable. Works with asyncio \"\"\" def resolve_item(root, info, **args)", "whether we should include this item in our subscripion resolve_vdis is usage example.", "import BasicAuthenticator from connman import ReDBConnection from handlers.graphql.types.deleted import Deleted from handlers.graphql.utils.querybuilder.changefeedbuilder import", "user_authenticator or user_authenticator.is_admin() or not issubclass(xenobject_type, ACLXenObject): table = re.db.table(xenobject_type.db_table_name) else: table =", "GraphQL Union type: _class OR Deleted \"\"\" class Meta: types = (_class, Deleted,", "def resolve_all_xen_items_changes(item_class: type, filter_function=None): \"\"\" Returns an asynchronous function that resolves every change", "type, table_name : str, key_name:str = 'ref'): \"\"\" Returns an asynchronous function that", "if not change: break if change['type'] == 'remove' or change['new_val'] is None: yield", "def MakeSubscription(_class : type) -> type: ''' Creates a subscription type for resolve_item_by_pkey", "Observable.from_future(iterable_to_items()) return resolve_items def resolve_item_by_key(item_class: type, table_name : str, key_name:str = 'ref'): \"\"\"", "changes = await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True, include_initial=with_initials).run(conn) while True: change = await changes.next() if not", "with_initials) if not value['ref'] in tasks: tasks[value['ref']] = TaskCounter(task=asyncio.create_task(builder.put_values_in_queue())) else: tasks[value['ref']].count += 1", "'type': 'remove', 'old_val': { 'ref' : value['ref'] } }) del tasks[value['ref']] elif change['type']", "'remove' Change = 'change' def str_to_changetype(s: str) -> Change: if s == 'initial':", "XenObject, only its ref is returned :param _class: GraphQL type to track changes", "(ObjectType, ), { 'change_type': graphene.Field(Change, required=True, description=\"Change type\"), 'value': graphene.Field(change_type, required=True), 'Meta': Meta", "'remove' or change['new_val'] is None: yield None continue else: value = change['new_val'] yield", "conn: key = args.get(key_name, None) if not key: yield None return table =", "resolve_item def resolve_all_items_changes(item_class: type, table_name : str): \"\"\" Returns an asynchronous function that", "break if change['type'] == 'remove': value = change['old_val'] else: value = change['new_val'] value", "to subscribe to changes for one particular item :param _class: :return: ''' #return", "utils.user import user_entities from xenadapter.xenobject import XenObject from xenadapter.aclxenobject import ACLXenObject class Change(graphene.Enum):", "ResolveInfo from rethinkdb import RethinkDB from rethinkdb.errors import ReqlOpFailedError from rx import Observable", "task_counter.count == 0: if not task_counter.task.done(): task_counter.task.cancel() await queue.put({ 'type': 'remove', 'old_val': {", "value = change['new_val'] if filter_function and not (await filter_function(value['ref'], conn)): continue builder =", "returned :param _class: GraphQL type to track changes on :return: GraphQL Union type:", "change in RethinkDB table with item with said primary key If item is", "async def iterable_to_item(): key = args.get(key_name, None) if not key: yield None return", "continue else: value = change['new_val'] yield item_class(**value) return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_items_changes(item_class:", "function is given a ref of potential subscription candidate (0th arg) and an", "Deleted, ) change_type = type(f'{_class.__name__}OrDeleted', (graphene.Union, ), { \"Meta\": Meta, }) class Meta:", "ChangeType: {s}\") @dataclass class TaskCounter: task : asyncio.Task count = 1 async def", "<-- this is what we need in info status=change['type'], ignore_initials=not with_initials) if not", "particular item :param _class: :return: ''' #return type(f'{_class.__name__}Subscription', # (ObjectType, ), # {", "class TaskCounter: task : asyncio.Task count = 1 async def create_single_changefeeds(queue: asyncio.Queue, info:", "MakeSubscriptionWithChangeType(_class : type) -> type: \"\"\" Create a subscription type with change tracking.", "user_entities(user_authenticator)], index='userid') changes = await table.pluck('ref').changes(include_types=True, include_initial=True).run(conn) while True: try: change = await", "handlers.graphql.types.deleted import Deleted from handlers.graphql.utils.querybuilder.changefeedbuilder import ChangefeedBuilder from handlers.graphql.utils.querybuilder.get_fields import get_fields from utils.user", "place of an item :param item_class: A GraphQL object type that has the", "== 'remove': value = change['old_val'] else: value = change['new_val'] value = item_class(**value) yield", ":param args: :return: ''' async def iterable_to_item(): key = args.get(key_name, None) if not", ":param _class: :return: ''' #return type(f'{_class.__name__}Subscription', # (ObjectType, ), # { # _class.__name__:", "not exist, returns null in place of an item :param item_class: A GraphQL", "this function is given a ref of potential subscription candidate (0th arg) and", "tasks.values(): task_counter.task.cancel() return except Exception as e: import sentry_sdk sentry_sdk.capture_exception(e) return def MakeSubscriptionWithChangeType(_class", "}) del tasks[value['ref']] elif change['type'] == 'change': print(f\"Ref change?: {change}\") continue else: value", "Change: if s == 'initial': return Change.Initial elif s == 'add': return Change.Add", "value = change['new_val'] yield item_class(**value) return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_items_changes(item_class: type, table_name", "}) class Meta: default_resolver = dict_resolver return type(f'{_class.__name__}sSubscription', (ObjectType, ), { 'change_type': graphene.Field(Change,", "iterable_to_items(): async with ReDBConnection().get_async_connection() as conn: table = re.db.table(table_name) changes = await table.pluck(*item_class._meta.fields.keys()).changes(include_types=True,", "def iterable_to_items(): async with ReDBConnection().get_async_connection() as conn: table = re.db.table(table_name) changes = await", "with all initial items :return: \"\"\" def resolve_items(root, info : ResolveInfo, with_initials :", "not used as a backer for Query ''' async def iterable_to_items(): fields_for_return_type =", "as conn: tasks: Dict[str, TaskCounter] = {} try: if not user_authenticator or user_authenticator.is_admin()", "table.get_all(key) \\ .pluck(*item_class._meta.fields)\\ .changes(include_types=True, include_initial=True).run(conn) while True: change = await changes.next() if not", "of an item :param item_class: A GraphQL object type that has the same", "return Change.Change else: raise ValueError(f\"No such ChangeType: {s}\") @dataclass class TaskCounter: task :", "item :param item_class: A GraphQL object type that has the same shape as", "def resolve_xen_item_by_key(key_name:str = 'ref'): \"\"\" Returns an asynchronous function that resolves every change", "from graphql import ResolveInfo from rethinkdb import RethinkDB from rethinkdb.errors import ReqlOpFailedError from", "is None: yield None continue else: value = change['new_val'] yield item_class(**value) return Observable.from_future(iterable_to_item())", "_class: :return: ''' #return type(f'{_class.__name__}Subscription', # (ObjectType, ), # { # _class.__name__: graphene.Field(_class)", "async with ReDBConnection().get_async_connection() as conn: tasks: Dict[str, TaskCounter] = {} try: if not", "(0th arg) and an asyncio connection to work with DB (1st arg). This", "changeType: one of Initial, Add, Mod, Remove value: of type item_class } Create", "return Change.Remove elif s == 'change': return Change.Change else: raise ValueError(f\"No such ChangeType:", "If an object is deleted and it's a XenObject, only its ref is", "_class: GraphQL type to track changes on :return: GraphQL Union type: _class OR", "arg). This function should return true or false answering whether we should include", "MakeSubscription(type) :param root: :param info: :param args: :return: ''' async def iterable_to_item(): async", "(1st arg). This function should return true or false answering whether we should", "= await table.pluck('ref').changes(include_types=True, include_initial=True).run(conn) while True: try: change = await changes.next() except ReqlOpFailedError:", "should return true or false answering whether we should include this item in", "count = 1 async def create_single_changefeeds(queue: asyncio.Queue, info: ResolveInfo, user_authenticator : BasicAuthenticator, xenobject_type:", "from handlers.graphql.types.deleted import Deleted from handlers.graphql.utils.querybuilder.changefeedbuilder import ChangefeedBuilder from handlers.graphql.utils.querybuilder.get_fields import get_fields from", ": BasicAuthenticator, xenobject_type: Type[XenObject], with_initials : bool, filter_function=None): async with ReDBConnection().get_async_connection() as conn:", "== 'remove': return Change.Remove elif s == 'change': return Change.Change else: raise ValueError(f\"No", "not change: break if change['type'] == 'remove' or change['new_val'] is None: yield None", ":param info: :param with_initials: Supply subscription with initial values (default: False). Use True,", "value : {...} <-- this is what we need in info status=change['type'], ignore_initials=not", "key: yield None return builder = ChangefeedBuilder(key, info) async for change in builder.yield_values():", "def resolve_all_items_changes(item_class: type, table_name : str): \"\"\" Returns an asynchronous function that resolves", "elif s == 'add': return Change.Add elif s == 'remove': return Change.Remove elif", "bool, filter_function=None): async with ReDBConnection().get_async_connection() as conn: tasks: Dict[str, TaskCounter] = {} try:", "info) async for change in builder.yield_values(): if not change: break if change['type'] ==", "Supply subscription with initial values (default: False). Use True, when a Subscription is", "handlers.graphql.utils.querybuilder.get_fields import get_fields from utils.user import user_entities from xenadapter.xenobject import XenObject from xenadapter.aclxenobject", "# { value : {...} <-- this is what we need in info", "change['new_val'] if filter_function and not (await filter_function(value['ref'], conn)): continue builder = ChangefeedBuilder(id=value['ref'], info=info,", "value = change['new_val'] yield value return Observable.from_future(iterable_to_item()) return resolve_item def resolve_all_xen_items_changes(item_class: type, filter_function=None):", "suitable when one wants to subscribe to changes for one particular item :param", ":param table: a RethinkDB table to retrieve updates from :return: function that returns", "import ChangefeedBuilder from handlers.graphql.utils.querybuilder.get_fields import get_fields from utils.user import user_entities from xenadapter.xenobject import", "Remove = 'remove' Change = 'change' def str_to_changetype(s: str) -> Change: if s", "import ReqlOpFailedError from rx import Observable from enum import Enum import constants.re as", "BasicAuthenticator, xenobject_type: Type[XenObject], with_initials : bool, filter_function=None): async with ReDBConnection().get_async_connection() as conn: tasks:", "= dict_resolver return type(f'{_class.__name__}sSubscription', (ObjectType, ), { 'change_type': graphene.Field(Change, required=True, description=\"Change type\"), 'value':", "{...} <-- this is what we need in info status=change['type'], ignore_initials=not with_initials) if", "= ChangefeedBuilder(id=value['ref'], info=info, queue=queue, additional_string=None, select_subfield=['value'], # { value : {...} <-- this", "object type that has same shape as a table :param filter_function: this function" ]
[ "1) if draw < rewards[a]: r = 1 else: r = 0 '''", "+= X[i][1] data0 /= (nb_datapoints * 100.) # data given as percentage but", "a = draw_from_discrete_proba(dist) ''' Get reward: GOTO_X -> RW_X ''' draw = random.uniform(0,", "''' out_choices, out_vcrw = rl_3target_vc(self.alpha, self.tau, self.max_steps) ''' Set attributes ''' self.rw_ =", "= 0 closest_index = -1 pred = self.predict(X) pred0 = pred[0] pred1 =", "with contructor arguments ''' args, _, _, values = inspect.getargvalues(inspect.currentframe()) values.pop(\"self\") for arg,", "form discrete proba dist ''' def draw_from_discrete_proba(dist): d = random.uniform(0, 1) cumul =", "mean_ut_rate = 0 for i in range(0, nb_test_sessions): last_step = max_steps - i*lensession", "states = [IN_A, IN_B, IN_C] actions = [GOTO_A, GOTO_B, GOTO_C] labels = [\"A\",", "output data ''' out_choices.append(a) str_choices = str_choices + str(a) if r <= 0:", "is computed. Here, the score is the distance between prediction and data \"\"\"", "\"rw_\") getattr(self, \"s_\") except AttributeError: raise RuntimeError(\"You must train estimator before predicting data!\")", "last_step - lensession rw_in_session = self.rw_[first_step:last_step] s_in_session = self.s_[first_step:last_step] # rw nb_rw =", "will be computed online sample_index : int index of current estimator, the default", "= nb_ut * 1. / (lensession-2) mean_rw_rate += rw_rate mean_ut_rate += ut_rate mean_rw_rate", "if self.log_sequences_internally == 1: datafile = \"log/fit_\" + str(self.sample_index) + \"_run_\" + str(self.run)", "the average or has to be fitted, otherwise -1 means the average will", "+= dist[i] ''' Define QL algorithm for this problem ''' def rl_3target_vc(alpha, tau,", "(self.alpha - 0 < 0.0000001): print \"Error: Invalid value for parameter alpha given", "of current estimator, the default value -1 should be overriden run : int", "where the output data is predicted. Here, it amounts to evaluate the success", "/ 100. data1 = X[i][1] / 100. score = 1 - ( (abs(pred0", "= X[self.average_line][0] / 100. # data given as percentage but score measured based", "scor eof the estimator wrt the average is computed. Here, the score is", "self.alpha, self.tau, data0, data1, pred0, pred1) outfp.write(data_to_save) return score def score_wrt_closest(self, X, y=None):", "range(0, len(dist)): if d < dist[i] + cumul: return i cumul += dist[i]", "0\".format(self) exit() if (self.sample_index == -1) : print \"Error: Invalid value for parameter", "{:d} {:4.3f} {:4.3f}\\n'.format(closest_score, closest_index, self.alpha, self.tau, closest_index, pred0, pred1) outfp.write(data_to_save) \"\"\" These are", "if self.log_results_internally == 1: logfile = \"results/score_c_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run)", "draw = random.uniform(0, 1) if draw < rewards[a]: r = 1 else: r", "range(0, nb_test_sessions): last_step = max_steps - i*lensession first_step = last_step - lensession rw_in_session", "str(self.run) with open(logfile,'a') as outfp: data_to_save = '{:4.3f} {:d} {:4.3f} {:06.3f} {:d} {:4.3f}", "in the dataset corresponds to the average or has to be fitted, otherwise", "= np.transpose((out_choices, out_vcrw)) np.savetxt(datafile, data_to_save, fmt='%d') def predict(self, X, y=None): \"\"\" This is", "nb_test_sessions last sessions ''' max_steps = self.max_steps lensession = self.lensession nb_test_sessions = self.nb_test_sessions", "''' a = s opts = np.copy(Q[s][:]) opts[s] = -99 dist = softmax(opts[:],", "IN_C = GOTO_C = 2 states = [IN_A, IN_B, IN_C] actions = [GOTO_A,", "''' Get reward: GOTO_X -> RW_X ''' draw = random.uniform(0, 1) if draw", "args, _, _, values = inspect.getargvalues(inspect.currentframe()) values.pop(\"self\") for arg, val in values.items(): setattr(self,", "given as percentage but score measured based on rates data1 /= (nb_datapoints *", "def __init__(self, alpha=0.1, tau=5.0, average_line=-1, sample_index=-1, run=1, log_results_internally=1, log_sequences_internally=1): \"\"\" This is the", "This is my toy example of a Q-Learning estimator using softmax policy It", "''' draw = random.uniform(0, 1) if draw < rewards[a]: r = 1 else:", "out_vcrw] class QLEstimator(BaseEstimator): \"\"\" This is my toy example of a Q-Learning estimator", "X[i][0] / 100. data1 = X[i][1] / 100. score = 1 - (", "i in range(0, nb_datapoints): data0 += X[i][0] data1 += X[i][1] data0 /= (nb_datapoints", "1: datafile = \"log/fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) data_to_save = np.transpose((out_choices,", "1 IN_C = GOTO_C = 2 states = [IN_A, IN_B, IN_C] actions =", "optimistic initialization ''' Start simulation ''' s = IN_A step = 0 while", "given as percentage but score measured based on rates pred0 = pred[0] pred1", "-99 dist = softmax(opts[:], tau) while a==s: # try until GOTO != s,", "as percentage but score measured based on rates data1 = X[self.average_line][1] / 100.", "computed. Here, the score is the distance between prediction and data \"\"\" score", "+= ut_rate mean_rw_rate /= nb_test_sessions mean_ut_rate /= nb_test_sessions return [mean_rw_rate, mean_ut_rate] def score_wrt_average(self,", "/ 100. # data given as percentage but score measured based on rates", "# number of sessions at the end of run of which the average", "of sessions at the end of run of which the average is considered", "if score > closest_score: closest_score = score closest_index = i if self.log_results_internally ==", "(self.sample_index == -1) : print \"Error: Invalid value for parameter sample_index given to", "RuntimeError(\"You must train estimator before predicting data!\") # use check_is_fitted(self, ['X_', 'y_']) instead", "inherits the get_params and set_params methods from BaseEstimator It overrides the methods fit(),", "the average will be computed online sample_index : int index of current estimator,", "exit() if (self.sample_index == -1) : print \"Error: Invalid value for parameter sample_index", "= '{:4.3f} -1 {:4.3f} {:06.3f} -1 {:4.3f} {:4.3f} {:4.3f} {:4.3f}\\n'.format(score, self.alpha, self.tau, data0,", "data0) + abs(pred1 - data1)) / 2. ) if score > closest_score: closest_score", "of the run ''' Print attributes ''' #for arg, val in values.items(): #print(\"{}", "''' Update state ''' s = a ''' Update loop variable ''' step", "= \"results/score_c_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a') as outfp: data_to_save", "for i in range(0, len(dist)): if d < dist[i] + cumul: return i", "out_vcrw = [] # append rewards given by vc ''' Intialize Q table", "Print attributes ''' #for arg, val in values.items(): #print(\"{} = {}\".format(arg,val)) def fit(self,", "''' self.rw_ = out_vcrw self.s_ = out_choices ''' Save data ''' if self.log_sequences_internally", "= random.uniform(0, 1) if draw < rewards[a]: r = 1 else: r =", "online sample_index : int index of current estimator, the default value -1 should", "data given as percentage but score measured based on rates data1 /= (nb_datapoints", "data0, data1, pred0, pred1) outfp.write(data_to_save) return score def score_wrt_closest(self, X, y=None): closest_score =", "= 0 for i in range(0, len(dist)): if d < dist[i] + cumul:", "for vc out_vcrw = [] # append rewards given by vc ''' Intialize", "using softmax policy ''' a = s opts = np.copy(Q[s][:]) opts[s] = -99", "IN_B = GOTO_B = 1 IN_C = GOTO_C = 2 states = [IN_A,", "the get_params and set_params methods from BaseEstimator It overrides the methods fit(), predict()", "out_choices, out_vcrw = rl_3target_vc(self.alpha, self.tau, self.max_steps) ''' Set attributes ''' self.rw_ = out_vcrw", "score def score_wrt_closest(self, X, y=None): closest_score = 0 closest_index = -1 pred =", "IN_A step = 0 while step < max_steps: ''' Act using softmax policy", "= pred[0] pred1 = pred[1] nb_datapoints = len(X) for i in range(0, nb_datapoints):", "fit() to check parameters \"\"\" if (self.alpha - 1 > 0.0000001) or (self.alpha", "number of trials in one session self.nb_test_sessions = 10 # number of sessions", "+ \"_run_\" + str(self.run) with open(logfile,'a') as outfp: data_to_save = '{:4.3f} {:d} {:4.3f}", "_, values = inspect.getargvalues(inspect.currentframe()) values.pop(\"self\") for arg, val in values.items(): setattr(self, arg, val)", "by fit() to check parameters \"\"\" if (self.alpha - 1 > 0.0000001) or", "= rl_3target_vc(self.alpha, self.tau, self.max_steps) ''' Set attributes ''' self.rw_ = out_vcrw self.s_ =", "Q[s][a] += delta ''' Update state ''' s = a ''' Update loop", "estimator with contructor arguments ''' args, _, _, values = inspect.getargvalues(inspect.currentframe()) values.pop(\"self\") for", "\"\"\" This is where the scor eof the estimator wrt the average is", "This is the constructor Parameters ---------- alpha, tau : float QL parameters, resp.", "useful when using Grid or Random Search Optimization methods however Bayesian Optimization has", "2. ) if score > closest_score: closest_score = score closest_index = i if", "range(0,len(opts)): ret[i] /= norm return ret ''' Define function for random draw form", "X[self.average_line][0] / 100. # data given as percentage but score measured based on", "must be in [0,1].\".format(self) exit() if (self.tau - 0 < 0.0000001): print \"Error:", "parameter tau given to {0}. Value must be > 0\".format(self) exit() if (self.sample_index", "!= s, because agent cannot choose the same target in two consecutive trials", "''' s = IN_A step = 0 while step < max_steps: ''' Act", "= self.s_[first_step:last_step] # rw nb_rw = np.bincount(rw_in_session)[1] rw_rate = nb_rw * 1. /", "tau given to {0}. Value must be > 0\".format(self) exit() if (self.sample_index ==", "last_step = max_steps - i*lensession first_step = last_step - lensession rw_in_session = self.rw_[first_step:last_step]", "if self.log_results_internally == 1: logfile = \"results/score_a_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run)", "len(X) data0 = 0. data1 = 0. for i in range(0, nb_datapoints): data0", "step = 0 while step < max_steps: ''' Act using softmax policy '''", "self.lensession = 200 # number of trials in one session self.nb_test_sessions = 10", "log functions \"\"\" ''' Initialize the estimator with contructor arguments ''' args, _,", "s_in_session = self.s_[first_step:last_step] # rw nb_rw = np.bincount(rw_in_session)[1] rw_rate = nb_rw * 1.", "but score measured based on rates pred0 = pred[0] pred1 = pred[1] score", "2. ) if self.log_results_internally == 1: logfile = \"results/score_a_fit_\" + str(self.sample_index) + \"_run_\"", "RW_X ''' draw = random.uniform(0, 1) if draw < rewards[a]: r = 1", "get_params and set_params methods from BaseEstimator It overrides the methods fit(), predict() and", "choose the same target in two consecutive trials a = draw_from_discrete_proba(dist) ''' Get", "in one session self.nb_test_sessions = 10 # number of sessions at the end", "results of the run ''' Print attributes ''' #for arg, val in values.items():", "/= nb_test_sessions mean_ut_rate /= nb_test_sessions return [mean_rw_rate, mean_ut_rate] def score_wrt_average(self, X, y=None): \"\"\"", "= 0. data1 = 0. for i in range(0, nb_datapoints): data0 += X[i][0]", "to {0}. Value must be in [0,1].\".format(self) exit() if (self.tau - 0 <", "RW_B, RW_C] ''' Define output data variables ''' out_choices = [] # append", "the methods fit(), predict() and score() \"\"\" def __init__(self, alpha=0.1, tau=5.0, average_line=-1, sample_index=-1,", "1.1 Q = np.full( (len(states), len(actions)), init_Qval ) # optimistic initialization ''' Start", "simulation ''' s = IN_A step = 0 while step < max_steps: '''", "-> RW_X ''' draw = random.uniform(0, 1) if draw < rewards[a]: r =", "out_vcrw.append(0) else: out_vcrw.append(1) return [out_choices, out_vcrw] class QLEstimator(BaseEstimator): \"\"\" This is my toy", "within estimator this is useful when using Grid or Random Search Optimization methods", "nb_ut += 1 ut_rate = nb_ut * 1. / (lensession-2) mean_rw_rate += rw_rate", "pred = self.predict(X) if self.average_line == -1: nb_datapoints = len(X) data0 = 0.", "it amounts to evaluate the success rate, u-turn rate, and complexity of the", "\"\"\" This is where the output data is predicted. Here, it amounts to", "and the results are saved \"\"\" ''' Check parameters ''' self.__check_params(X) ''' Run", "score measured based on rates pred0 = pred[0] pred1 = pred[1] score =", "\"\"\" def __init__(self, alpha=0.1, tau=5.0, average_line=-1, sample_index=-1, run=1, log_results_internally=1, log_sequences_internally=1): \"\"\" This is", "== 1: logfile = \"results/score_c_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a')", "on rates data1 = X[self.average_line][1] / 100. # data given as percentage but", "closest_index = -1 pred = self.predict(X) pred0 = pred[0] pred1 = pred[1] nb_datapoints", "Invalid value for parameter sample_index given to {0}. Default value (-1) should be", "self.rw_[first_step:last_step] s_in_session = self.s_[first_step:last_step] # rw nb_rw = np.bincount(rw_in_session)[1] rw_rate = nb_rw *", "Add hard-coded parameters ''' self.max_steps = 10000 # number of trials per run", "choices str_choices = \"\" # useful for vc out_vcrw = [] # append", "= pred[1] score = 1 - ( (abs(pred0 - data0) + abs(pred1 -", "Update state ''' s = a ''' Update loop variable ''' step +=", "values.items(): setattr(self, arg, val) ''' Add hard-coded parameters ''' self.max_steps = 10000 #", "by vc ''' Intialize Q table ''' init_Qval = 1.1 Q = np.full(", "eof the estimator wrt the average is computed. Here, the score is the", "nb_test_sessions mean_ut_rate /= nb_test_sessions return [mean_rw_rate, mean_ut_rate] def score_wrt_average(self, X, y=None): \"\"\" This", "out_choices ''' Save data ''' if self.log_sequences_internally == 1: datafile = \"log/fit_\" +", "out_vcrw)) np.savetxt(datafile, data_to_save, fmt='%d') def predict(self, X, y=None): \"\"\" This is where the", "__check_params(self, X): \"\"\" This is called by fit() to check parameters \"\"\" if", "while step < max_steps: ''' Act using softmax policy ''' a = s", "numpy as np import random import math ''' Define softmax function ''' def", "\"\"\" These are private methods \"\"\" def __check_params(self, X): \"\"\" This is called", "+= ret[i] for i in range(0,len(opts)): ret[i] /= norm return ret ''' Define", "log_results_internally, log_sequences_internally : int flags indicating whether to save log and result files", "function ''' def softmax(opts, tau): norm = 0 ret = [] for i", "value for parameter sample_index given to {0}. Default value (-1) should be overriden", "given to {0}. Value must be > 0\".format(self) exit() if (self.sample_index == -1)", "opts = np.copy(Q[s][:]) opts[s] = -99 dist = softmax(opts[:], tau) while a==s: #", "where the QL is run and the results are saved \"\"\" ''' Check", "''' Run QL ''' out_choices, out_vcrw = rl_3target_vc(self.alpha, self.tau, self.max_steps) ''' Set attributes", "evaluate the success rate, u-turn rate, and complexity of the QL agent. \"\"\"", "= '{:4.3f} {:d} {:4.3f} {:06.3f} {:d} {:4.3f} {:4.3f}\\n'.format(closest_score, closest_index, self.alpha, self.tau, closest_index, pred0,", "current estimator, the default value -1 should be overriden run : int index", "1. RW_B = 0. RW_C = 1. rewards = [RW_A, RW_B, RW_C] '''", "score() \"\"\" def __init__(self, alpha=0.1, tau=5.0, average_line=-1, sample_index=-1, run=1, log_results_internally=1, log_sequences_internally=1): \"\"\" This", "Set attributes ''' self.rw_ = out_vcrw self.s_ = out_choices ''' Save data '''", "rates pred0 = pred[0] pred1 = pred[1] score = 1 - ( (abs(pred0", ": int index of run (if many executions per paramset) log_results_internally, log_sequences_internally :", "y=None): \"\"\" This is where the QL is run and the results are", "\"s_\") except AttributeError: raise RuntimeError(\"You must train estimator before predicting data!\") # use", "= 0 for k in range(2, lensession): if s_in_session[k] == s_in_session[k-2]: nb_ut +=", "the dataset corresponds to the average or has to be fitted, otherwise -1", "/= (nb_datapoints * 100.) # data given as percentage but score measured based", "data ''' out_choices.append(a) str_choices = str_choices + str(a) if r <= 0: out_vcrw.append(0)", "#print(\"{} = {}\".format(arg,val)) def fit(self, X, y=None): \"\"\" This is where the QL", "sample_index given to {0}. Default value (-1) should be overriden with a positive", "Get reward: GOTO_X -> RW_X ''' draw = random.uniform(0, 1) if draw <", "is my toy example of a Q-Learning estimator using softmax policy It has", "using softmax policy It has a constructor and it inherits the get_params and", "abs(pred1 - data1)) / 2. ) if score > closest_score: closest_score = score", "math ''' Define softmax function ''' def softmax(opts, tau): norm = 0 ret", "nb_datapoints): data0 += X[i][0] data1 += X[i][1] data0 /= (nb_datapoints * 100.) #", "called by fit() to check parameters \"\"\" if (self.alpha - 1 > 0.0000001)", "set_params methods from BaseEstimator It overrides the methods fit(), predict() and score() \"\"\"", "\"\"\" if (self.alpha - 1 > 0.0000001) or (self.alpha - 0 < 0.0000001):", "= {}\".format(arg,val)) def fit(self, X, y=None): \"\"\" This is where the QL is", "= [GOTO_A, GOTO_B, GOTO_C] labels = [\"A\", 'B', \"C\"] RW_A = 1. RW_B", "return [out_choices, out_vcrw] class QLEstimator(BaseEstimator): \"\"\" This is my toy example of a", "predict() and score() \"\"\" def __init__(self, alpha=0.1, tau=5.0, average_line=-1, sample_index=-1, run=1, log_results_internally=1, log_sequences_internally=1):", "self.__check_params(X) ''' Run QL ''' out_choices, out_vcrw = rl_3target_vc(self.alpha, self.tau, self.max_steps) ''' Set", "outfp.write(data_to_save) \"\"\" These are private methods \"\"\" def __check_params(self, X): \"\"\" This is", "d < dist[i] + cumul: return i cumul += dist[i] ''' Define QL", "alpha*( r - Q[s][a] ) # gamma = 0 Q[s][a] += delta '''", "= last_step - lensession rw_in_session = self.rw_[first_step:last_step] s_in_session = self.s_[first_step:last_step] # rw nb_rw", "temperature average_line : int if one of the line in the dataset corresponds", "= pred[1] nb_datapoints = len(X) for i in range(0, nb_datapoints): if i !=", "my toy example of a Q-Learning estimator using softmax policy It has a", "in range(0,len(opts)): ret[i] /= norm return ret ''' Define function for random draw", "ret[i] /= norm return ret ''' Define function for random draw form discrete", "as np import random import math ''' Define softmax function ''' def softmax(opts,", "It overrides the methods fit(), predict() and score() \"\"\" def __init__(self, alpha=0.1, tau=5.0,", ": int if one of the line in the dataset corresponds to the", "{}\".format(arg,val)) def fit(self, X, y=None): \"\"\" This is where the QL is run", "self.rw_ = out_vcrw self.s_ = out_choices ''' Save data ''' if self.log_sequences_internally ==", "it inherits the get_params and set_params methods from BaseEstimator It overrides the methods", "\"\"\" This is where the QL is run and the results are saved", "agent. \"\"\" try: getattr(self, \"rw_\") getattr(self, \"s_\") except AttributeError: raise RuntimeError(\"You must train", "0. data1 = 0. for i in range(0, nb_datapoints): data0 += X[i][0] data1", "rates data1 /= (nb_datapoints * 100.) # data given as percentage but score", "if (self.tau - 0 < 0.0000001): print \"Error: Invalid value for parameter tau", "value for parameter tau given to {0}. Value must be > 0\".format(self) exit()", "draw form discrete proba dist ''' def draw_from_discrete_proba(dist): d = random.uniform(0, 1) cumul", "is the constructor Parameters ---------- alpha, tau : float QL parameters, resp. learning", "Check parameters ''' self.__check_params(X) ''' Run QL ''' out_choices, out_vcrw = rl_3target_vc(self.alpha, self.tau,", "= self.nb_test_sessions mean_rw_rate = 0 mean_ut_rate = 0 for i in range(0, nb_test_sessions):", "RW_B = 0. RW_C = 1. rewards = [RW_A, RW_B, RW_C] ''' Define", "Q-Learning estimator using softmax policy It has a constructor and it inherits the", "tau : float QL parameters, resp. learning rate and softmax temperature average_line :", "int flags indicating whether to save log and result files within estimator this", "10000 # number of trials per run self.lensession = 200 # number of", "RW_A = 1. RW_B = 0. RW_C = 1. rewards = [RW_A, RW_B,", "= np.copy(Q[s][:]) opts[s] = -99 dist = softmax(opts[:], tau) while a==s: # try", "= 1 IN_C = GOTO_C = 2 states = [IN_A, IN_B, IN_C] actions", "X[i][1] / 100. score = 1 - ( (abs(pred0 - data0) + abs(pred1", "the estimator with contructor arguments ''' args, _, _, values = inspect.getargvalues(inspect.currentframe()) values.pop(\"self\")", "if (self.sample_index == -1) : print \"Error: Invalid value for parameter sample_index given", "# append choices str_choices = \"\" # useful for vc out_vcrw = []", "(lensession-2) mean_rw_rate += rw_rate mean_ut_rate += ut_rate mean_rw_rate /= nb_test_sessions mean_ut_rate /= nb_test_sessions", "measured based on rates else: data0 = X[self.average_line][0] / 100. # data given", "''' Define softmax function ''' def softmax(opts, tau): norm = 0 ret =", "a = s opts = np.copy(Q[s][:]) opts[s] = -99 dist = softmax(opts[:], tau)", "Grid or Random Search Optimization methods however Bayesian Optimization has built-in log functions", "* 1. / (lensession-2) mean_rw_rate += rw_rate mean_ut_rate += ut_rate mean_rw_rate /= nb_test_sessions", "100. data1 = X[i][1] / 100. score = 1 - ( (abs(pred0 -", "def draw_from_discrete_proba(dist): d = random.uniform(0, 1) cumul = 0 for i in range(0,", "fitted, otherwise -1 means the average will be computed online sample_index : int", "score > closest_score: closest_score = score closest_index = i if self.log_results_internally == 1:", "{:06.3f} -1 {:4.3f} {:4.3f} {:4.3f} {:4.3f}\\n'.format(score, self.alpha, self.tau, data0, data1, pred0, pred1) outfp.write(data_to_save)", "0.0000001) or (self.alpha - 0 < 0.0000001): print \"Error: Invalid value for parameter", "Q = np.full( (len(states), len(actions)), init_Qval ) # optimistic initialization ''' Start simulation", "data ''' if self.log_sequences_internally == 1: datafile = \"log/fit_\" + str(self.sample_index) + \"_run_\"", "0.0000001): print \"Error: Invalid value for parameter alpha given to {0}. Value must", "pred0, pred1) outfp.write(data_to_save) return score def score_wrt_closest(self, X, y=None): closest_score = 0 closest_index", "\"\"\" score = 0 pred = self.predict(X) if self.average_line == -1: nb_datapoints =", "as outfp: data_to_save = '{:4.3f} -1 {:4.3f} {:06.3f} -1 {:4.3f} {:4.3f} {:4.3f} {:4.3f}\\n'.format(score,", "nb_rw * 1. / lensession # ut nb_ut = 0 for k in", "+= X[i][0] data1 += X[i][1] data0 /= (nb_datapoints * 100.) # data given", "random draw form discrete proba dist ''' def draw_from_discrete_proba(dist): d = random.uniform(0, 1)", "0 Q[s][a] += delta ''' Update state ''' s = a ''' Update", "1 > 0.0000001) or (self.alpha - 0 < 0.0000001): print \"Error: Invalid value", "data1, pred0, pred1) outfp.write(data_to_save) return score def score_wrt_closest(self, X, y=None): closest_score = 0", "= 1. rewards = [RW_A, RW_B, RW_C] ''' Define output data variables '''", "sklearn.base import BaseEstimator import inspect import numpy as np import random import math", "str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a') as outfp: data_to_save = '{:4.3f} {:d}", "100. score = 1 - ( (abs(pred0 - data0) + abs(pred1 - data1))", "+= delta ''' Update state ''' s = a ''' Update loop variable", "Q table ''' init_Qval = 1.1 Q = np.full( (len(states), len(actions)), init_Qval )", "{:4.3f} {:4.3f} {:4.3f} {:4.3f}\\n'.format(score, self.alpha, self.tau, data0, data1, pred0, pred1) outfp.write(data_to_save) return score", "draw < rewards[a]: r = 1 else: r = 0 ''' Update Q", "useful for vc out_vcrw = [] # append rewards given by vc '''", "{:4.3f} {:06.3f} -1 {:4.3f} {:4.3f} {:4.3f} {:4.3f}\\n'.format(score, self.alpha, self.tau, data0, data1, pred0, pred1)", "str_choices = \"\" # useful for vc out_vcrw = [] # append rewards", "nb_test_sessions return [mean_rw_rate, mean_ut_rate] def score_wrt_average(self, X, y=None): \"\"\" This is where the", "the QL is run and the results are saved \"\"\" ''' Check parameters", "overriden run : int index of run (if many executions per paramset) log_results_internally,", "while a==s: # try until GOTO != s, because agent cannot choose the", "s, because agent cannot choose the same target in two consecutive trials a", "= 10000 # number of trials per run self.lensession = 200 # number", "average_line=-1, sample_index=-1, run=1, log_results_internally=1, log_sequences_internally=1): \"\"\" This is the constructor Parameters ---------- alpha,", "average or has to be fitted, otherwise -1 means the average will be", "[IN_A, IN_B, IN_C] actions = [GOTO_A, GOTO_B, GOTO_C] labels = [\"A\", 'B', \"C\"]", "s = IN_A step = 0 while step < max_steps: ''' Act using", "+ str(self.sample_index) + \"_run_\" + str(self.run) data_to_save = np.transpose((out_choices, out_vcrw)) np.savetxt(datafile, data_to_save, fmt='%d')", "GOTO_C = 2 states = [IN_A, IN_B, IN_C] actions = [GOTO_A, GOTO_B, GOTO_C]", "str(self.run) data_to_save = np.transpose((out_choices, out_vcrw)) np.savetxt(datafile, data_to_save, fmt='%d') def predict(self, X, y=None): \"\"\"", "check parameters \"\"\" if (self.alpha - 1 > 0.0000001) or (self.alpha - 0", "norm = 0 ret = [] for i in range(0,len(opts)): ret.append(math.exp(opts[i]/tau)) norm +=", "be overriden run : int index of run (if many executions per paramset)", "100.) # data given as percentage but score measured based on rates else:", "\"\"\" def __check_params(self, X): \"\"\" This is called by fit() to check parameters", "+ str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a') as outfp: data_to_save = '{:4.3f}", "and score() \"\"\" def __init__(self, alpha=0.1, tau=5.0, average_line=-1, sample_index=-1, run=1, log_results_internally=1, log_sequences_internally=1): \"\"\"", "10 # number of sessions at the end of run of which the", "at the end of run of which the average is considered as the", ": int index of current estimator, the default value -1 should be overriden", "Q[s][a] ) # gamma = 0 Q[s][a] += delta ''' Update state '''", "QL agent. \"\"\" try: getattr(self, \"rw_\") getattr(self, \"s_\") except AttributeError: raise RuntimeError(\"You must", "print \"Error: Invalid value for parameter sample_index given to {0}. Default value (-1)", "methods from BaseEstimator It overrides the methods fit(), predict() and score() \"\"\" def", "# try until GOTO != s, because agent cannot choose the same target", "in range(0, len(dist)): if d < dist[i] + cumul: return i cumul +=", "estimator this is useful when using Grid or Random Search Optimization methods however", "len(dist)): if d < dist[i] + cumul: return i cumul += dist[i] '''", "= out_vcrw self.s_ = out_choices ''' Save data ''' if self.log_sequences_internally == 1:", "self.max_steps lensession = self.lensession nb_test_sessions = self.nb_test_sessions mean_rw_rate = 0 mean_ut_rate = 0", "average is computed. Here, the score is the distance between prediction and data", "0. for i in range(0, nb_datapoints): data0 += X[i][0] data1 += X[i][1] data0", "i in range(0, len(dist)): if d < dist[i] + cumul: return i cumul", "open(logfile,'a') as outfp: data_to_save = '{:4.3f} {:d} {:4.3f} {:06.3f} {:d} {:4.3f} {:4.3f}\\n'.format(closest_score, closest_index,", "means the average will be computed online sample_index : int index of current", "the final results of the run ''' Print attributes ''' #for arg, val", "rate, u-turn rate, and complexity of the QL agent. \"\"\" try: getattr(self, \"rw_\")", "= X[self.average_line][1] / 100. # data given as percentage but score measured based", "IN_C] actions = [GOTO_A, GOTO_B, GOTO_C] labels = [\"A\", 'B', \"C\"] RW_A =", "score = 1 - ( (abs(pred0 - data0) + abs(pred1 - data1)) /", "- ( (abs(pred0 - data0) + abs(pred1 - data1)) / 2. ) if", "+ \"_run_\" + str(self.run) with open(logfile,'a') as outfp: data_to_save = '{:4.3f} -1 {:4.3f}", "+ str(self.run) with open(logfile,'a') as outfp: data_to_save = '{:4.3f} -1 {:4.3f} {:06.3f} -1", "+ abs(pred1 - data1)) / 2. ) if score > closest_score: closest_score =", "be computed online sample_index : int index of current estimator, the default value", "percentage but score measured based on rates pred0 = pred[0] pred1 = pred[1]", "[GOTO_A, GOTO_B, GOTO_C] labels = [\"A\", 'B', \"C\"] RW_A = 1. RW_B =", "pred0, pred1) outfp.write(data_to_save) \"\"\" These are private methods \"\"\" def __check_params(self, X): \"\"\"", "or has to be fitted, otherwise -1 means the average will be computed", "the average is considered as the final results of the run ''' Print", "first_step = last_step - lensession rw_in_session = self.rw_[first_step:last_step] s_in_session = self.s_[first_step:last_step] # rw", "data1 += X[i][1] data0 /= (nb_datapoints * 100.) # data given as percentage", "cumul: return i cumul += dist[i] ''' Define QL algorithm for this problem", "the same target in two consecutive trials a = draw_from_discrete_proba(dist) ''' Get reward:", "/ lensession # ut nb_ut = 0 for k in range(2, lensession): if", "0 for i in range(0, nb_test_sessions): last_step = max_steps - i*lensession first_step =", "\"results/score_c_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a') as outfp: data_to_save =", "average will be computed online sample_index : int index of current estimator, the", "in values.items(): #print(\"{} = {}\".format(arg,val)) def fit(self, X, y=None): \"\"\" This is where", "sessions ''' max_steps = self.max_steps lensession = self.lensession nb_test_sessions = self.nb_test_sessions mean_rw_rate =", "i in range(0, nb_test_sessions): last_step = max_steps - i*lensession first_step = last_step -", "''' Set attributes ''' self.rw_ = out_vcrw self.s_ = out_choices ''' Save data", "range(0,len(opts)): ret.append(math.exp(opts[i]/tau)) norm += ret[i] for i in range(0,len(opts)): ret[i] /= norm return", "the scor eof the estimator wrt the average is computed. Here, the score", "gamma = 0 Q[s][a] += delta ''' Update state ''' s = a", "'{:4.3f} {:d} {:4.3f} {:06.3f} {:d} {:4.3f} {:4.3f}\\n'.format(closest_score, closest_index, self.alpha, self.tau, closest_index, pred0, pred1)", "values.pop(\"self\") for arg, val in values.items(): setattr(self, arg, val) ''' Add hard-coded parameters", "for i in range(0, nb_datapoints): data0 += X[i][0] data1 += X[i][1] data0 /=", "random.uniform(0, 1) if draw < rewards[a]: r = 1 else: r = 0", "''' step += 1 ''' Save output data ''' out_choices.append(a) str_choices = str_choices", "run and the results are saved \"\"\" ''' Check parameters ''' self.__check_params(X) '''", "rw nb_rw = np.bincount(rw_in_session)[1] rw_rate = nb_rw * 1. / lensession # ut", ") if self.log_results_internally == 1: logfile = \"results/score_a_fit_\" + str(self.sample_index) + \"_run_\" +", "* 1. / lensession # ut nb_ut = 0 for k in range(2,", "= 0 pred = self.predict(X) if self.average_line == -1: nb_datapoints = len(X) data0", "r = 1 else: r = 0 ''' Update Q table ''' delta", "def softmax(opts, tau): norm = 0 ret = [] for i in range(0,len(opts)):", "cannot choose the same target in two consecutive trials a = draw_from_discrete_proba(dist) '''", "result files within estimator this is useful when using Grid or Random Search", "nb_ut = 0 for k in range(2, lensession): if s_in_session[k] == s_in_session[k-2]: nb_ut", ") # optimistic initialization ''' Start simulation ''' s = IN_A step =", "s_in_session[k] == s_in_session[k-2]: nb_ut += 1 ut_rate = nb_ut * 1. / (lensession-2)", "out_vcrw self.s_ = out_choices ''' Save data ''' if self.log_sequences_internally == 1: datafile", "else: data0 = X[self.average_line][0] / 100. # data given as percentage but score", "!= self.average_line : data0 = X[i][0] / 100. data1 = X[i][1] / 100.", "setattr(self, arg, val) ''' Add hard-coded parameters ''' self.max_steps = 10000 # number", "str(self.run) with open(logfile,'a') as outfp: data_to_save = '{:4.3f} -1 {:4.3f} {:06.3f} -1 {:4.3f}", "self.tau, data0, data1, pred0, pred1) outfp.write(data_to_save) return score def score_wrt_closest(self, X, y=None): closest_score", "- data1)) / 2. ) if score > closest_score: closest_score = score closest_index", "\"\"\" This is called by fit() to check parameters \"\"\" if (self.alpha -", "import math ''' Define softmax function ''' def softmax(opts, tau): norm = 0", "len(X) for i in range(0, nb_datapoints): if i != self.average_line : data0 =", "= \"\" # useful for vc out_vcrw = [] # append rewards given", "values.items(): #print(\"{} = {}\".format(arg,val)) def fit(self, X, y=None): \"\"\" This is where the", "mean_ut_rate] def score_wrt_average(self, X, y=None): \"\"\" This is where the scor eof the", "when using Grid or Random Search Optimization methods however Bayesian Optimization has built-in", "# number of trials per run self.lensession = 200 # number of trials", "is where the QL is run and the results are saved \"\"\" '''", "[RW_A, RW_B, RW_C] ''' Define output data variables ''' out_choices = [] #", "range(0, nb_datapoints): data0 += X[i][0] data1 += X[i][1] data0 /= (nb_datapoints * 100.)", "y=None): closest_score = 0 closest_index = -1 pred = self.predict(X) pred0 = pred[0]", "pred[0] pred1 = pred[1] nb_datapoints = len(X) for i in range(0, nb_datapoints): if", "data1)) / 2. ) if self.log_results_internally == 1: logfile = \"results/score_a_fit_\" + str(self.sample_index)", "rewards given by vc ''' Intialize Q table ''' init_Qval = 1.1 Q", "until GOTO != s, because agent cannot choose the same target in two", "of run of which the average is considered as the final results of", "in [0,1].\".format(self) exit() if (self.tau - 0 < 0.0000001): print \"Error: Invalid value", "< 0.0000001): print \"Error: Invalid value for parameter tau given to {0}. Value", "arg, val in values.items(): setattr(self, arg, val) ''' Add hard-coded parameters ''' self.max_steps", "step += 1 ''' Save output data ''' out_choices.append(a) str_choices = str_choices +", "else: out_vcrw.append(1) return [out_choices, out_vcrw] class QLEstimator(BaseEstimator): \"\"\" This is my toy example", "and softmax temperature average_line : int if one of the line in the", "+ cumul: return i cumul += dist[i] ''' Define QL algorithm for this", "GOTO_A = 0 IN_B = GOTO_B = 1 IN_C = GOTO_C = 2", "+ str(a) if r <= 0: out_vcrw.append(0) else: out_vcrw.append(1) return [out_choices, out_vcrw] class", "outfp: data_to_save = '{:4.3f} -1 {:4.3f} {:06.3f} -1 {:4.3f} {:4.3f} {:4.3f} {:4.3f}\\n'.format(score, self.alpha,", ": float QL parameters, resp. learning rate and softmax temperature average_line : int", "''' def rl_3target_vc(alpha, tau, max_steps): ''' Define states, actions and reward probabilities '''", "self.nb_test_sessions mean_rw_rate = 0 mean_ut_rate = 0 for i in range(0, nb_test_sessions): last_step", "ut_rate mean_rw_rate /= nb_test_sessions mean_ut_rate /= nb_test_sessions return [mean_rw_rate, mean_ut_rate] def score_wrt_average(self, X,", "attributes ''' #for arg, val in values.items(): #print(\"{} = {}\".format(arg,val)) def fit(self, X,", "for i in range(0,len(opts)): ret[i] /= norm return ret ''' Define function for", "resp. learning rate and softmax temperature average_line : int if one of the", "''' out_choices.append(a) str_choices = str_choices + str(a) if r <= 0: out_vcrw.append(0) else:", "[mean_rw_rate, mean_ut_rate] def score_wrt_average(self, X, y=None): \"\"\" This is where the scor eof", "tau=5.0, average_line=-1, sample_index=-1, run=1, log_results_internally=1, log_sequences_internally=1): \"\"\" This is the constructor Parameters ----------", "== -1: nb_datapoints = len(X) data0 = 0. data1 = 0. for i", "= 0. RW_C = 1. rewards = [RW_A, RW_B, RW_C] ''' Define output", "np import random import math ''' Define softmax function ''' def softmax(opts, tau):", "0 < 0.0000001): print \"Error: Invalid value for parameter tau given to {0}.", "self.log_sequences_internally == 1: datafile = \"log/fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) data_to_save", "variables ''' out_choices = [] # append choices str_choices = \"\" # useful", "run of which the average is considered as the final results of the", "on rates pred0 = pred[0] pred1 = pred[1] score = 1 - (", "with open(logfile,'a') as outfp: data_to_save = '{:4.3f} -1 {:4.3f} {:06.3f} -1 {:4.3f} {:4.3f}", "measured based on rates pred0 = pred[0] pred1 = pred[1] score = 1", "ret = [] for i in range(0,len(opts)): ret.append(math.exp(opts[i]/tau)) norm += ret[i] for i", "range(0, nb_datapoints): if i != self.average_line : data0 = X[i][0] / 100. data1", "+= 1 ut_rate = nb_ut * 1. / (lensession-2) mean_rw_rate += rw_rate mean_ut_rate", "1 ''' Save output data ''' out_choices.append(a) str_choices = str_choices + str(a) if", "= 10 # number of sessions at the end of run of which", "import inspect import numpy as np import random import math ''' Define softmax", "closest_score = 0 closest_index = -1 pred = self.predict(X) pred0 = pred[0] pred1", "= 1 - ( (abs(pred0 - data0) + abs(pred1 - data1)) / 2.", "def fit(self, X, y=None): \"\"\" This is where the QL is run and", ") if score > closest_score: closest_score = score closest_index = i if self.log_results_internally", "self.max_steps = 10000 # number of trials per run self.lensession = 200 #", "if i != self.average_line : data0 = X[i][0] / 100. data1 = X[i][1]", "measured based on rates data1 /= (nb_datapoints * 100.) # data given as", "executions per paramset) log_results_internally, log_sequences_internally : int flags indicating whether to save log", "predicted. Here, it amounts to evaluate the success rate, u-turn rate, and complexity", "= 0 while step < max_steps: ''' Act using softmax policy ''' a", "This is called by fit() to check parameters \"\"\" if (self.alpha - 1", "rewards[a]: r = 1 else: r = 0 ''' Update Q table '''", "= softmax(opts[:], tau) while a==s: # try until GOTO != s, because agent", "[out_choices, out_vcrw] class QLEstimator(BaseEstimator): \"\"\" This is my toy example of a Q-Learning", "is considered as the final results of the run ''' Print attributes '''", "mean_rw_rate = 0 mean_ut_rate = 0 for i in range(0, nb_test_sessions): last_step =", "tau) while a==s: # try until GOTO != s, because agent cannot choose", "= X[i][0] / 100. data1 = X[i][1] / 100. score = 1 -", "= [RW_A, RW_B, RW_C] ''' Define output data variables ''' out_choices = []", "= 0 ''' Update Q table ''' delta = alpha*( r - Q[s][a]", "one of the line in the dataset corresponds to the average or has", "= [IN_A, IN_B, IN_C] actions = [GOTO_A, GOTO_B, GOTO_C] labels = [\"A\", 'B',", "IN_B, IN_C] actions = [GOTO_A, GOTO_B, GOTO_C] labels = [\"A\", 'B', \"C\"] RW_A", "the line in the dataset corresponds to the average or has to be", "= self.max_steps lensession = self.lensession nb_test_sessions = self.nb_test_sessions mean_rw_rate = 0 mean_ut_rate =", "1. / (lensession-2) mean_rw_rate += rw_rate mean_ut_rate += ut_rate mean_rw_rate /= nb_test_sessions mean_ut_rate", "parameters \"\"\" if (self.alpha - 1 > 0.0000001) or (self.alpha - 0 <", "= GOTO_C = 2 states = [IN_A, IN_B, IN_C] actions = [GOTO_A, GOTO_B,", "= alpha*( r - Q[s][a] ) # gamma = 0 Q[s][a] += delta", "data_to_save = np.transpose((out_choices, out_vcrw)) np.savetxt(datafile, data_to_save, fmt='%d') def predict(self, X, y=None): \"\"\" This", "distance between prediction and data \"\"\" score = 0 pred = self.predict(X) if", "based on rates else: data0 = X[self.average_line][0] / 100. # data given as", "100. # data given as percentage but score measured based on rates pred0", "pred[1] nb_datapoints = len(X) for i in range(0, nb_datapoints): if i != self.average_line", "wrt the average is computed. Here, the score is the distance between prediction", "given to {0}. Value must be in [0,1].\".format(self) exit() if (self.tau - 0", "actions and reward probabilities ''' IN_A = GOTO_A = 0 IN_B = GOTO_B", "datafile = \"log/fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) data_to_save = np.transpose((out_choices, out_vcrw))", "data0 /= (nb_datapoints * 100.) # data given as percentage but score measured", "dataset corresponds to the average or has to be fitted, otherwise -1 means", "function for random draw form discrete proba dist ''' def draw_from_discrete_proba(dist): d =", "one session self.nb_test_sessions = 10 # number of sessions at the end of", "X[i][0] data1 += X[i][1] data0 /= (nb_datapoints * 100.) # data given as", "in values.items(): setattr(self, arg, val) ''' Add hard-coded parameters ''' self.max_steps = 10000", "QL ''' out_choices, out_vcrw = rl_3target_vc(self.alpha, self.tau, self.max_steps) ''' Set attributes ''' self.rw_", "(nb_datapoints * 100.) # data given as percentage but score measured based on", "== s_in_session[k-2]: nb_ut += 1 ut_rate = nb_ut * 1. / (lensession-2) mean_rw_rate", "== 1: logfile = \"results/score_a_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a')", "0 for k in range(2, lensession): if s_in_session[k] == s_in_session[k-2]: nb_ut += 1", "pred = self.predict(X) pred0 = pred[0] pred1 = pred[1] nb_datapoints = len(X) for", ": print \"Error: Invalid value for parameter sample_index given to {0}. Default value", "# data given as percentage but score measured based on rates else: data0", "/ 2. ) if score > closest_score: closest_score = score closest_index = i", "pred[0] pred1 = pred[1] score = 1 - ( (abs(pred0 - data0) +", "in two consecutive trials a = draw_from_discrete_proba(dist) ''' Get reward: GOTO_X -> RW_X", "data is predicted. Here, it amounts to evaluate the success rate, u-turn rate,", "data1 /= (nb_datapoints * 100.) # data given as percentage but score measured", "''' Print attributes ''' #for arg, val in values.items(): #print(\"{} = {}\".format(arg,val)) def", "# number of trials in one session self.nb_test_sessions = 10 # number of", "''' def softmax(opts, tau): norm = 0 ret = [] for i in", "problem ''' def rl_3target_vc(alpha, tau, max_steps): ''' Define states, actions and reward probabilities", "(abs(pred0 - data0) + abs(pred1 - data1)) / 2. ) if self.log_results_internally ==", "# append rewards given by vc ''' Intialize Q table ''' init_Qval =", "{0}. Value must be in [0,1].\".format(self) exit() if (self.tau - 0 < 0.0000001):", "session self.nb_test_sessions = 10 # number of sessions at the end of run", "the output data is predicted. Here, it amounts to evaluate the success rate,", "abs(pred1 - data1)) / 2. ) if self.log_results_internally == 1: logfile = \"results/score_a_fit_\"", "['X_', 'y_']) instead ? ''' Get average result over nb_test_sessions last sessions '''", "def __check_params(self, X): \"\"\" This is called by fit() to check parameters \"\"\"", "run=1, log_results_internally=1, log_sequences_internally=1): \"\"\" This is the constructor Parameters ---------- alpha, tau :", "if d < dist[i] + cumul: return i cumul += dist[i] ''' Define", "alpha, tau : float QL parameters, resp. learning rate and softmax temperature average_line", "Define function for random draw form discrete proba dist ''' def draw_from_discrete_proba(dist): d", "methods however Bayesian Optimization has built-in log functions \"\"\" ''' Initialize the estimator", "''' Define states, actions and reward probabilities ''' IN_A = GOTO_A = 0", "0 mean_ut_rate = 0 for i in range(0, nb_test_sessions): last_step = max_steps -", "0 while step < max_steps: ''' Act using softmax policy ''' a =", "estimator, the default value -1 should be overriden run : int index of", "This is where the scor eof the estimator wrt the average is computed.", "0 for i in range(0, len(dist)): if d < dist[i] + cumul: return", "np.copy(Q[s][:]) opts[s] = -99 dist = softmax(opts[:], tau) while a==s: # try until", "= random.uniform(0, 1) cumul = 0 for i in range(0, len(dist)): if d", "# data given as percentage but score measured based on rates data1 =", "and reward probabilities ''' IN_A = GOTO_A = 0 IN_B = GOTO_B =", "output data variables ''' out_choices = [] # append choices str_choices = \"\"", "in range(0,len(opts)): ret.append(math.exp(opts[i]/tau)) norm += ret[i] for i in range(0,len(opts)): ret[i] /= norm", "overrides the methods fit(), predict() and score() \"\"\" def __init__(self, alpha=0.1, tau=5.0, average_line=-1,", "log and result files within estimator this is useful when using Grid or", "a==s: # try until GOTO != s, because agent cannot choose the same", "import numpy as np import random import math ''' Define softmax function '''", "0 IN_B = GOTO_B = 1 IN_C = GOTO_C = 2 states =", "hard-coded parameters ''' self.max_steps = 10000 # number of trials per run self.lensession", "str_choices = str_choices + str(a) if r <= 0: out_vcrw.append(0) else: out_vcrw.append(1) return", "-1 {:4.3f} {:4.3f} {:4.3f} {:4.3f}\\n'.format(score, self.alpha, self.tau, data0, data1, pred0, pred1) outfp.write(data_to_save) return", "rate, and complexity of the QL agent. \"\"\" try: getattr(self, \"rw_\") getattr(self, \"s_\")", "< 0.0000001): print \"Error: Invalid value for parameter alpha given to {0}. Value", "if s_in_session[k] == s_in_session[k-2]: nb_ut += 1 ut_rate = nb_ut * 1. /", "int index of run (if many executions per paramset) log_results_internally, log_sequences_internally : int", "as percentage but score measured based on rates else: data0 = X[self.average_line][0] /", "100. # data given as percentage but score measured based on rates data1", "data1 = X[i][1] / 100. score = 1 - ( (abs(pred0 - data0)", "example of a Q-Learning estimator using softmax policy It has a constructor and", "closest_index, self.alpha, self.tau, closest_index, pred0, pred1) outfp.write(data_to_save) \"\"\" These are private methods \"\"\"", "GOTO != s, because agent cannot choose the same target in two consecutive", "== -1) : print \"Error: Invalid value for parameter sample_index given to {0}.", "average result over nb_test_sessions last sessions ''' max_steps = self.max_steps lensession = self.lensession", "#for arg, val in values.items(): #print(\"{} = {}\".format(arg,val)) def fit(self, X, y=None): \"\"\"", "value -1 should be overriden run : int index of run (if many", "consecutive trials a = draw_from_discrete_proba(dist) ''' Get reward: GOTO_X -> RW_X ''' draw", "output data is predicted. Here, it amounts to evaluate the success rate, u-turn", "lensession = self.lensession nb_test_sessions = self.nb_test_sessions mean_rw_rate = 0 mean_ut_rate = 0 for", "(self.tau - 0 < 0.0000001): print \"Error: Invalid value for parameter tau given", "softmax policy ''' a = s opts = np.copy(Q[s][:]) opts[s] = -99 dist", "100.) # data given as percentage but score measured based on rates data1", "be > 0\".format(self) exit() if (self.sample_index == -1) : print \"Error: Invalid value", "= 0 mean_ut_rate = 0 for i in range(0, nb_test_sessions): last_step = max_steps", "- 0 < 0.0000001): print \"Error: Invalid value for parameter alpha given to", "and it inherits the get_params and set_params methods from BaseEstimator It overrides the", "print \"Error: Invalid value for parameter alpha given to {0}. Value must be", "be in [0,1].\".format(self) exit() if (self.tau - 0 < 0.0000001): print \"Error: Invalid", "arg, val in values.items(): #print(\"{} = {}\".format(arg,val)) def fit(self, X, y=None): \"\"\" This", "nb_rw = np.bincount(rw_in_session)[1] rw_rate = nb_rw * 1. / lensession # ut nb_ut", "target in two consecutive trials a = draw_from_discrete_proba(dist) ''' Get reward: GOTO_X ->", "= self.lensession nb_test_sessions = self.nb_test_sessions mean_rw_rate = 0 mean_ut_rate = 0 for i", "str(a) if r <= 0: out_vcrw.append(0) else: out_vcrw.append(1) return [out_choices, out_vcrw] class QLEstimator(BaseEstimator):", "\"\"\" This is my toy example of a Q-Learning estimator using softmax policy", "log_sequences_internally : int flags indicating whether to save log and result files within", "= score closest_index = i if self.log_results_internally == 1: logfile = \"results/score_c_fit_\" +", "i cumul += dist[i] ''' Define QL algorithm for this problem ''' def", "'B', \"C\"] RW_A = 1. RW_B = 0. RW_C = 1. rewards =", "= 2 states = [IN_A, IN_B, IN_C] actions = [GOTO_A, GOTO_B, GOTO_C] labels", "or Random Search Optimization methods however Bayesian Optimization has built-in log functions \"\"\"", "over nb_test_sessions last sessions ''' max_steps = self.max_steps lensession = self.lensession nb_test_sessions =", "mean_rw_rate /= nb_test_sessions mean_ut_rate /= nb_test_sessions return [mean_rw_rate, mean_ut_rate] def score_wrt_average(self, X, y=None):", "score = 0 pred = self.predict(X) if self.average_line == -1: nb_datapoints = len(X)", "''' Define output data variables ''' out_choices = [] # append choices str_choices", "[] # append choices str_choices = \"\" # useful for vc out_vcrw =", "/= nb_test_sessions return [mean_rw_rate, mean_ut_rate] def score_wrt_average(self, X, y=None): \"\"\" This is where", "methods \"\"\" def __check_params(self, X): \"\"\" This is called by fit() to check", "to check parameters \"\"\" if (self.alpha - 1 > 0.0000001) or (self.alpha -", "val) ''' Add hard-coded parameters ''' self.max_steps = 10000 # number of trials", "len(actions)), init_Qval ) # optimistic initialization ''' Start simulation ''' s = IN_A", "sample_index : int index of current estimator, the default value -1 should be", "u-turn rate, and complexity of the QL agent. \"\"\" try: getattr(self, \"rw_\") getattr(self,", "GOTO_B = 1 IN_C = GOTO_C = 2 states = [IN_A, IN_B, IN_C]", "X[self.average_line][1] / 100. # data given as percentage but score measured based on", "* 100.) # data given as percentage but score measured based on rates", "trials a = draw_from_discrete_proba(dist) ''' Get reward: GOTO_X -> RW_X ''' draw =", "Q table ''' delta = alpha*( r - Q[s][a] ) # gamma =", "self.lensession nb_test_sessions = self.nb_test_sessions mean_rw_rate = 0 mean_ut_rate = 0 for i in", "self.predict(X) pred0 = pred[0] pred1 = pred[1] nb_datapoints = len(X) for i in", "for parameter sample_index given to {0}. Default value (-1) should be overriden with", "private methods \"\"\" def __check_params(self, X): \"\"\" This is called by fit() to", "this problem ''' def rl_3target_vc(alpha, tau, max_steps): ''' Define states, actions and reward", "''' #for arg, val in values.items(): #print(\"{} = {}\".format(arg,val)) def fit(self, X, y=None):", "otherwise -1 means the average will be computed online sample_index : int index", "many executions per paramset) log_results_internally, log_sequences_internally : int flags indicating whether to save", "must train estimator before predicting data!\") # use check_is_fitted(self, ['X_', 'y_']) instead ?", "the constructor Parameters ---------- alpha, tau : float QL parameters, resp. learning rate", "loop variable ''' step += 1 ''' Save output data ''' out_choices.append(a) str_choices", "rw_rate = nb_rw * 1. / lensession # ut nb_ut = 0 for", "score measured based on rates data1 /= (nb_datapoints * 100.) # data given", "index of current estimator, the default value -1 should be overriden run :", "table ''' delta = alpha*( r - Q[s][a] ) # gamma = 0", "= max_steps - i*lensession first_step = last_step - lensession rw_in_session = self.rw_[first_step:last_step] s_in_session", "= len(X) for i in range(0, nb_datapoints): if i != self.average_line : data0", "= 1 else: r = 0 ''' Update Q table ''' delta =", "<filename>basic_qlestimator.py from sklearn.base import BaseEstimator import inspect import numpy as np import random", "of trials per run self.lensession = 200 # number of trials in one", "y=None): \"\"\" This is where the scor eof the estimator wrt the average", "considered as the final results of the run ''' Print attributes ''' #for", "nb_datapoints = len(X) data0 = 0. data1 = 0. for i in range(0,", "<= 0: out_vcrw.append(0) else: out_vcrw.append(1) return [out_choices, out_vcrw] class QLEstimator(BaseEstimator): \"\"\" This is", "self.nb_test_sessions = 10 # number of sessions at the end of run of", "1 ut_rate = nb_ut * 1. / (lensession-2) mean_rw_rate += rw_rate mean_ut_rate +=", "{:4.3f} {:06.3f} {:d} {:4.3f} {:4.3f}\\n'.format(closest_score, closest_index, self.alpha, self.tau, closest_index, pred0, pred1) outfp.write(data_to_save) \"\"\"", "policy It has a constructor and it inherits the get_params and set_params methods", "Run QL ''' out_choices, out_vcrw = rl_3target_vc(self.alpha, self.tau, self.max_steps) ''' Set attributes '''", "proba dist ''' def draw_from_discrete_proba(dist): d = random.uniform(0, 1) cumul = 0 for", "_, _, values = inspect.getargvalues(inspect.currentframe()) values.pop(\"self\") for arg, val in values.items(): setattr(self, arg,", "outfp: data_to_save = '{:4.3f} {:d} {:4.3f} {:06.3f} {:d} {:4.3f} {:4.3f}\\n'.format(closest_score, closest_index, self.alpha, self.tau,", "Define states, actions and reward probabilities ''' IN_A = GOTO_A = 0 IN_B", "actions = [GOTO_A, GOTO_B, GOTO_C] labels = [\"A\", 'B', \"C\"] RW_A = 1.", "value for parameter alpha given to {0}. Value must be in [0,1].\".format(self) exit()", "agent cannot choose the same target in two consecutive trials a = draw_from_discrete_proba(dist)", "Here, the score is the distance between prediction and data \"\"\" score =", "= -1 pred = self.predict(X) pred0 = pred[0] pred1 = pred[1] nb_datapoints =", "def score_wrt_average(self, X, y=None): \"\"\" This is where the scor eof the estimator", "except AttributeError: raise RuntimeError(\"You must train estimator before predicting data!\") # use check_is_fitted(self,", "line in the dataset corresponds to the average or has to be fitted,", "\"results/score_a_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a') as outfp: data_to_save =", "softmax policy It has a constructor and it inherits the get_params and set_params", "= 0 ret = [] for i in range(0,len(opts)): ret.append(math.exp(opts[i]/tau)) norm += ret[i]", "delta ''' Update state ''' s = a ''' Update loop variable '''", "mean_ut_rate /= nb_test_sessions return [mean_rw_rate, mean_ut_rate] def score_wrt_average(self, X, y=None): \"\"\" This is", "# gamma = 0 Q[s][a] += delta ''' Update state ''' s =", "''' Initialize the estimator with contructor arguments ''' args, _, _, values =", "{0}. Value must be > 0\".format(self) exit() if (self.sample_index == -1) : print", "- data1)) / 2. ) if self.log_results_internally == 1: logfile = \"results/score_a_fit_\" +", "data0 = X[i][0] / 100. data1 = X[i][1] / 100. score = 1", "of which the average is considered as the final results of the run", "= inspect.getargvalues(inspect.currentframe()) values.pop(\"self\") for arg, val in values.items(): setattr(self, arg, val) ''' Add", "closest_index = i if self.log_results_internally == 1: logfile = \"results/score_c_fit_\" + str(self.sample_index) +", "- data0) + abs(pred1 - data1)) / 2. ) if score > closest_score:", "end of run of which the average is considered as the final results", "is where the scor eof the estimator wrt the average is computed. Here,", "fmt='%d') def predict(self, X, y=None): \"\"\" This is where the output data is", "for i in range(0, nb_test_sessions): last_step = max_steps - i*lensession first_step = last_step", "given as percentage but score measured based on rates data1 = X[self.average_line][1] /", "data given as percentage but score measured based on rates else: data0 =", "Invalid value for parameter alpha given to {0}. Value must be in [0,1].\".format(self)", "2 states = [IN_A, IN_B, IN_C] actions = [GOTO_A, GOTO_B, GOTO_C] labels =", "the run ''' Print attributes ''' #for arg, val in values.items(): #print(\"{} =", "= nb_rw * 1. / lensession # ut nb_ut = 0 for k", "to {0}. Default value (-1) should be overriden with a positive value.\".format(self) exit()", "''' Act using softmax policy ''' a = s opts = np.copy(Q[s][:]) opts[s]", "the end of run of which the average is considered as the final", "to be fitted, otherwise -1 means the average will be computed online sample_index", "per run self.lensession = 200 # number of trials in one session self.nb_test_sessions", "1 - ( (abs(pred0 - data0) + abs(pred1 - data1)) / 2. )", "This is where the output data is predicted. Here, it amounts to evaluate", "outfp.write(data_to_save) return score def score_wrt_closest(self, X, y=None): closest_score = 0 closest_index = -1", "0 pred = self.predict(X) if self.average_line == -1: nb_datapoints = len(X) data0 =", "however Bayesian Optimization has built-in log functions \"\"\" ''' Initialize the estimator with", "in range(2, lensession): if s_in_session[k] == s_in_session[k-2]: nb_ut += 1 ut_rate = nb_ut", "= X[i][1] / 100. score = 1 - ( (abs(pred0 - data0) +", "else: r = 0 ''' Update Q table ''' delta = alpha*( r", "run (if many executions per paramset) log_results_internally, log_sequences_internally : int flags indicating whether", "= self.predict(X) pred0 = pred[0] pred1 = pred[1] nb_datapoints = len(X) for i", "+ \"_run_\" + str(self.run) data_to_save = np.transpose((out_choices, out_vcrw)) np.savetxt(datafile, data_to_save, fmt='%d') def predict(self,", "= self.rw_[first_step:last_step] s_in_session = self.s_[first_step:last_step] # rw nb_rw = np.bincount(rw_in_session)[1] rw_rate = nb_rw", "{:4.3f}\\n'.format(closest_score, closest_index, self.alpha, self.tau, closest_index, pred0, pred1) outfp.write(data_to_save) \"\"\" These are private methods", "reward: GOTO_X -> RW_X ''' draw = random.uniform(0, 1) if draw < rewards[a]:", "-1: nb_datapoints = len(X) data0 = 0. data1 = 0. for i in", "out_choices.append(a) str_choices = str_choices + str(a) if r <= 0: out_vcrw.append(0) else: out_vcrw.append(1)", "rate and softmax temperature average_line : int if one of the line in", "''' Define function for random draw form discrete proba dist ''' def draw_from_discrete_proba(dist):", "cumul += dist[i] ''' Define QL algorithm for this problem ''' def rl_3target_vc(alpha,", "inspect.getargvalues(inspect.currentframe()) values.pop(\"self\") for arg, val in values.items(): setattr(self, arg, val) ''' Add hard-coded", "0: out_vcrw.append(0) else: out_vcrw.append(1) return [out_choices, out_vcrw] class QLEstimator(BaseEstimator): \"\"\" This is my", "discrete proba dist ''' def draw_from_discrete_proba(dist): d = random.uniform(0, 1) cumul = 0", "average is considered as the final results of the run ''' Print attributes", "if one of the line in the dataset corresponds to the average or", "on rates data1 /= (nb_datapoints * 100.) # data given as percentage but", "vc out_vcrw = [] # append rewards given by vc ''' Intialize Q", "max_steps: ''' Act using softmax policy ''' a = s opts = np.copy(Q[s][:])", "parameters, resp. learning rate and softmax temperature average_line : int if one of", "self.max_steps) ''' Set attributes ''' self.rw_ = out_vcrw self.s_ = out_choices ''' Save", "and data \"\"\" score = 0 pred = self.predict(X) if self.average_line == -1:", "logfile = \"results/score_c_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a') as outfp:", "max_steps - i*lensession first_step = last_step - lensession rw_in_session = self.rw_[first_step:last_step] s_in_session =", "initialization ''' Start simulation ''' s = IN_A step = 0 while step", "opts[s] = -99 dist = softmax(opts[:], tau) while a==s: # try until GOTO", "score measured based on rates else: data0 = X[self.average_line][0] / 100. # data", "(len(states), len(actions)), init_Qval ) # optimistic initialization ''' Start simulation ''' s =", "tau): norm = 0 ret = [] for i in range(0,len(opts)): ret.append(math.exp(opts[i]/tau)) norm", "r - Q[s][a] ) # gamma = 0 Q[s][a] += delta ''' Update", "run self.lensession = 200 # number of trials in one session self.nb_test_sessions =", "lensession rw_in_session = self.rw_[first_step:last_step] s_in_session = self.s_[first_step:last_step] # rw nb_rw = np.bincount(rw_in_session)[1] rw_rate", "self.tau, self.max_steps) ''' Set attributes ''' self.rw_ = out_vcrw self.s_ = out_choices '''", "the success rate, u-turn rate, and complexity of the QL agent. \"\"\" try:", "but score measured based on rates data1 = X[self.average_line][1] / 100. # data", "= draw_from_discrete_proba(dist) ''' Get reward: GOTO_X -> RW_X ''' draw = random.uniform(0, 1)", "QL algorithm for this problem ''' def rl_3target_vc(alpha, tau, max_steps): ''' Define states,", "are saved \"\"\" ''' Check parameters ''' self.__check_params(X) ''' Run QL ''' out_choices,", "pred1 = pred[1] score = 1 - ( (abs(pred0 - data0) + abs(pred1", "data0) + abs(pred1 - data1)) / 2. ) if self.log_results_internally == 1: logfile", ": data0 = X[i][0] / 100. data1 = X[i][1] / 100. score =", "a constructor and it inherits the get_params and set_params methods from BaseEstimator It", "where the scor eof the estimator wrt the average is computed. Here, the", "contructor arguments ''' args, _, _, values = inspect.getargvalues(inspect.currentframe()) values.pop(\"self\") for arg, val", "is predicted. Here, it amounts to evaluate the success rate, u-turn rate, and", "Random Search Optimization methods however Bayesian Optimization has built-in log functions \"\"\" '''", "toy example of a Q-Learning estimator using softmax policy It has a constructor", "data0 = 0. data1 = 0. for i in range(0, nb_datapoints): data0 +=", "-1 pred = self.predict(X) pred0 = pred[0] pred1 = pred[1] nb_datapoints = len(X)", "''' max_steps = self.max_steps lensession = self.lensession nb_test_sessions = self.nb_test_sessions mean_rw_rate = 0", "closest_index, pred0, pred1) outfp.write(data_to_save) \"\"\" These are private methods \"\"\" def __check_params(self, X):", "Update Q table ''' delta = alpha*( r - Q[s][a] ) # gamma", "val in values.items(): setattr(self, arg, val) ''' Add hard-coded parameters ''' self.max_steps =", "s_in_session[k-2]: nb_ut += 1 ut_rate = nb_ut * 1. / (lensession-2) mean_rw_rate +=", "table ''' init_Qval = 1.1 Q = np.full( (len(states), len(actions)), init_Qval ) #", "index of run (if many executions per paramset) log_results_internally, log_sequences_internally : int flags", "out_vcrw = rl_3target_vc(self.alpha, self.tau, self.max_steps) ''' Set attributes ''' self.rw_ = out_vcrw self.s_", "but score measured based on rates data1 /= (nb_datapoints * 100.) # data", "( (abs(pred0 - data0) + abs(pred1 - data1)) / 2. ) if self.log_results_internally", "max_steps): ''' Define states, actions and reward probabilities ''' IN_A = GOTO_A =", "1 else: r = 0 ''' Update Q table ''' delta = alpha*(", "( (abs(pred0 - data0) + abs(pred1 - data1)) / 2. ) if score", "given as percentage but score measured based on rates else: data0 = X[self.average_line][0]", "''' Save output data ''' out_choices.append(a) str_choices = str_choices + str(a) if r", "init_Qval = 1.1 Q = np.full( (len(states), len(actions)), init_Qval ) # optimistic initialization", "= \"log/fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) data_to_save = np.transpose((out_choices, out_vcrw)) np.savetxt(datafile,", "\"_run_\" + str(self.run) with open(logfile,'a') as outfp: data_to_save = '{:4.3f} -1 {:4.3f} {:06.3f}", "try until GOTO != s, because agent cannot choose the same target in", "as percentage but score measured based on rates pred0 = pred[0] pred1 =", "based on rates data1 = X[self.average_line][1] / 100. # data given as percentage", "(abs(pred0 - data0) + abs(pred1 - data1)) / 2. ) if score >", "and result files within estimator this is useful when using Grid or Random", "? ''' Get average result over nb_test_sessions last sessions ''' max_steps = self.max_steps", "< rewards[a]: r = 1 else: r = 0 ''' Update Q table", "parameters ''' self.__check_params(X) ''' Run QL ''' out_choices, out_vcrw = rl_3target_vc(self.alpha, self.tau, self.max_steps)", "parameter sample_index given to {0}. Default value (-1) should be overriden with a", "dist[i] + cumul: return i cumul += dist[i] ''' Define QL algorithm for", "given by vc ''' Intialize Q table ''' init_Qval = 1.1 Q =", "indicating whether to save log and result files within estimator this is useful", "= 1.1 Q = np.full( (len(states), len(actions)), init_Qval ) # optimistic initialization '''", "data1 = X[self.average_line][1] / 100. # data given as percentage but score measured", "softmax(opts[:], tau) while a==s: # try until GOTO != s, because agent cannot", "state ''' s = a ''' Update loop variable ''' step += 1", "str(self.sample_index) + \"_run_\" + str(self.run) data_to_save = np.transpose((out_choices, out_vcrw)) np.savetxt(datafile, data_to_save, fmt='%d') def", "delta = alpha*( r - Q[s][a] ) # gamma = 0 Q[s][a] +=", "the distance between prediction and data \"\"\" score = 0 pred = self.predict(X)", "1: logfile = \"results/score_a_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a') as", "success rate, u-turn rate, and complexity of the QL agent. \"\"\" try: getattr(self,", "= 200 # number of trials in one session self.nb_test_sessions = 10 #", "Save output data ''' out_choices.append(a) str_choices = str_choices + str(a) if r <=", "''' Check parameters ''' self.__check_params(X) ''' Run QL ''' out_choices, out_vcrw = rl_3target_vc(self.alpha,", "or (self.alpha - 0 < 0.0000001): print \"Error: Invalid value for parameter alpha", "\"C\"] RW_A = 1. RW_B = 0. RW_C = 1. rewards = [RW_A,", "These are private methods \"\"\" def __check_params(self, X): \"\"\" This is called by", "if (self.alpha - 1 > 0.0000001) or (self.alpha - 0 < 0.0000001): print", "= 0 for i in range(0, nb_test_sessions): last_step = max_steps - i*lensession first_step", "random.uniform(0, 1) cumul = 0 for i in range(0, len(dist)): if d <", "1. rewards = [RW_A, RW_B, RW_C] ''' Define output data variables ''' out_choices", "draw_from_discrete_proba(dist) ''' Get reward: GOTO_X -> RW_X ''' draw = random.uniform(0, 1) if", "has to be fitted, otherwise -1 means the average will be computed online", "''' Add hard-coded parameters ''' self.max_steps = 10000 # number of trials per", "== 1: datafile = \"log/fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) data_to_save =", "np.bincount(rw_in_session)[1] rw_rate = nb_rw * 1. / lensession # ut nb_ut = 0", "for k in range(2, lensession): if s_in_session[k] == s_in_session[k-2]: nb_ut += 1 ut_rate", "= self.predict(X) if self.average_line == -1: nb_datapoints = len(X) data0 = 0. data1", "val in values.items(): #print(\"{} = {}\".format(arg,val)) def fit(self, X, y=None): \"\"\" This is", "rates data1 = X[self.average_line][1] / 100. # data given as percentage but score", "{:d} {:4.3f} {:06.3f} {:d} {:4.3f} {:4.3f}\\n'.format(closest_score, closest_index, self.alpha, self.tau, closest_index, pred0, pred1) outfp.write(data_to_save)", "mean_ut_rate += ut_rate mean_rw_rate /= nb_test_sessions mean_ut_rate /= nb_test_sessions return [mean_rw_rate, mean_ut_rate] def", "ret.append(math.exp(opts[i]/tau)) norm += ret[i] for i in range(0,len(opts)): ret[i] /= norm return ret", "ut nb_ut = 0 for k in range(2, lensession): if s_in_session[k] == s_in_session[k-2]:", "GOTO_B, GOTO_C] labels = [\"A\", 'B', \"C\"] RW_A = 1. RW_B = 0.", "rl_3target_vc(self.alpha, self.tau, self.max_steps) ''' Set attributes ''' self.rw_ = out_vcrw self.s_ = out_choices", "alpha=0.1, tau=5.0, average_line=-1, sample_index=-1, run=1, log_results_internally=1, log_sequences_internally=1): \"\"\" This is the constructor Parameters", "# optimistic initialization ''' Start simulation ''' s = IN_A step = 0", "= IN_A step = 0 while step < max_steps: ''' Act using softmax", "---------- alpha, tau : float QL parameters, resp. learning rate and softmax temperature", "> 0.0000001) or (self.alpha - 0 < 0.0000001): print \"Error: Invalid value for", "+= 1 ''' Save output data ''' out_choices.append(a) str_choices = str_choices + str(a)", "Parameters ---------- alpha, tau : float QL parameters, resp. learning rate and softmax", "BaseEstimator import inspect import numpy as np import random import math ''' Define", "-1) : print \"Error: Invalid value for parameter sample_index given to {0}. Default", "+ str(self.run) with open(logfile,'a') as outfp: data_to_save = '{:4.3f} {:d} {:4.3f} {:06.3f} {:d}", "str_choices + str(a) if r <= 0: out_vcrw.append(0) else: out_vcrw.append(1) return [out_choices, out_vcrw]", ": int flags indicating whether to save log and result files within estimator", "score_wrt_average(self, X, y=None): \"\"\" This is where the scor eof the estimator wrt", "the estimator wrt the average is computed. Here, the score is the distance", "{:4.3f} {:4.3f}\\n'.format(closest_score, closest_index, self.alpha, self.tau, closest_index, pred0, pred1) outfp.write(data_to_save) \"\"\" These are private", "= np.full( (len(states), len(actions)), init_Qval ) # optimistic initialization ''' Start simulation '''", "# rw nb_rw = np.bincount(rw_in_session)[1] rw_rate = nb_rw * 1. / lensession #", "for parameter tau given to {0}. Value must be > 0\".format(self) exit() if", "GOTO_X -> RW_X ''' draw = random.uniform(0, 1) if draw < rewards[a]: r", "''' if self.log_sequences_internally == 1: datafile = \"log/fit_\" + str(self.sample_index) + \"_run_\" +", "tau, max_steps): ''' Define states, actions and reward probabilities ''' IN_A = GOTO_A", "cumul = 0 for i in range(0, len(dist)): if d < dist[i] +", "BaseEstimator It overrides the methods fit(), predict() and score() \"\"\" def __init__(self, alpha=0.1,", "save log and result files within estimator this is useful when using Grid", "1. / lensession # ut nb_ut = 0 for k in range(2, lensession):", "should be overriden run : int index of run (if many executions per", "getattr(self, \"s_\") except AttributeError: raise RuntimeError(\"You must train estimator before predicting data!\") #", "data given as percentage but score measured based on rates data1 = X[self.average_line][1]", "\"Error: Invalid value for parameter tau given to {0}. Value must be >", "with open(logfile,'a') as outfp: data_to_save = '{:4.3f} {:d} {:4.3f} {:06.3f} {:d} {:4.3f} {:4.3f}\\n'.format(closest_score,", "as outfp: data_to_save = '{:4.3f} {:d} {:4.3f} {:06.3f} {:d} {:4.3f} {:4.3f}\\n'.format(closest_score, closest_index, self.alpha,", "pred1) outfp.write(data_to_save) return score def score_wrt_closest(self, X, y=None): closest_score = 0 closest_index =", "+ str(self.run) data_to_save = np.transpose((out_choices, out_vcrw)) np.savetxt(datafile, data_to_save, fmt='%d') def predict(self, X, y=None):", "- 1 > 0.0000001) or (self.alpha - 0 < 0.0000001): print \"Error: Invalid", "result over nb_test_sessions last sessions ''' max_steps = self.max_steps lensession = self.lensession nb_test_sessions", "np.full( (len(states), len(actions)), init_Qval ) # optimistic initialization ''' Start simulation ''' s", "# useful for vc out_vcrw = [] # append rewards given by vc", "= s opts = np.copy(Q[s][:]) opts[s] = -99 dist = softmax(opts[:], tau) while", "rw_rate mean_ut_rate += ut_rate mean_rw_rate /= nb_test_sessions mean_ut_rate /= nb_test_sessions return [mean_rw_rate, mean_ut_rate]", "the score is the distance between prediction and data \"\"\" score = 0", "values = inspect.getargvalues(inspect.currentframe()) values.pop(\"self\") for arg, val in values.items(): setattr(self, arg, val) '''", "+= rw_rate mean_ut_rate += ut_rate mean_rw_rate /= nb_test_sessions mean_ut_rate /= nb_test_sessions return [mean_rw_rate,", "r = 0 ''' Update Q table ''' delta = alpha*( r -", "return i cumul += dist[i] ''' Define QL algorithm for this problem '''", "to save log and result files within estimator this is useful when using", "QL parameters, resp. learning rate and softmax temperature average_line : int if one", "for i in range(0, nb_datapoints): if i != self.average_line : data0 = X[i][0]", "= str_choices + str(a) if r <= 0: out_vcrw.append(0) else: out_vcrw.append(1) return [out_choices,", "based on rates pred0 = pred[0] pred1 = pred[1] score = 1 -", "Define softmax function ''' def softmax(opts, tau): norm = 0 ret = []", "\"Error: Invalid value for parameter sample_index given to {0}. Default value (-1) should", "but score measured based on rates else: data0 = X[self.average_line][0] / 100. #", "measured based on rates data1 = X[self.average_line][1] / 100. # data given as", "= -99 dist = softmax(opts[:], tau) while a==s: # try until GOTO !=", "\"Error: Invalid value for parameter alpha given to {0}. Value must be in", "''' out_choices = [] # append choices str_choices = \"\" # useful for", "y=None): \"\"\" This is where the output data is predicted. Here, it amounts", "complexity of the QL agent. \"\"\" try: getattr(self, \"rw_\") getattr(self, \"s_\") except AttributeError:", "s = a ''' Update loop variable ''' step += 1 ''' Save", "norm return ret ''' Define function for random draw form discrete proba dist", "constructor Parameters ---------- alpha, tau : float QL parameters, resp. learning rate and", "to the average or has to be fitted, otherwise -1 means the average", "rewards = [RW_A, RW_B, RW_C] ''' Define output data variables ''' out_choices =", "''' Save data ''' if self.log_sequences_internally == 1: datafile = \"log/fit_\" + str(self.sample_index)", "vc ''' Intialize Q table ''' init_Qval = 1.1 Q = np.full( (len(states),", "= pred[0] pred1 = pred[1] score = 1 - ( (abs(pred0 - data0)", "< max_steps: ''' Act using softmax policy ''' a = s opts =", "for random draw form discrete proba dist ''' def draw_from_discrete_proba(dist): d = random.uniform(0,", "computed online sample_index : int index of current estimator, the default value -1", "init_Qval ) # optimistic initialization ''' Start simulation ''' s = IN_A step", "and complexity of the QL agent. \"\"\" try: getattr(self, \"rw_\") getattr(self, \"s_\") except", "log_sequences_internally=1): \"\"\" This is the constructor Parameters ---------- alpha, tau : float QL", "closest_score: closest_score = score closest_index = i if self.log_results_internally == 1: logfile =", "Update loop variable ''' step += 1 ''' Save output data ''' out_choices.append(a)", "softmax function ''' def softmax(opts, tau): norm = 0 ret = [] for", "predict(self, X, y=None): \"\"\" This is where the output data is predicted. Here,", "predicting data!\") # use check_is_fitted(self, ['X_', 'y_']) instead ? ''' Get average result", "a Q-Learning estimator using softmax policy It has a constructor and it inherits", "append rewards given by vc ''' Intialize Q table ''' init_Qval = 1.1", "final results of the run ''' Print attributes ''' #for arg, val in", "run ''' Print attributes ''' #for arg, val in values.items(): #print(\"{} = {}\".format(arg,val))", "= 0. for i in range(0, nb_datapoints): data0 += X[i][0] data1 += X[i][1]", "[] for i in range(0,len(opts)): ret.append(math.exp(opts[i]/tau)) norm += ret[i] for i in range(0,len(opts)):", "from BaseEstimator It overrides the methods fit(), predict() and score() \"\"\" def __init__(self,", "is where the output data is predicted. Here, it amounts to evaluate the", "r <= 0: out_vcrw.append(0) else: out_vcrw.append(1) return [out_choices, out_vcrw] class QLEstimator(BaseEstimator): \"\"\" This", "(if many executions per paramset) log_results_internally, log_sequences_internally : int flags indicating whether to", "Start simulation ''' s = IN_A step = 0 while step < max_steps:", "Define output data variables ''' out_choices = [] # append choices str_choices =", "nb_ut * 1. / (lensession-2) mean_rw_rate += rw_rate mean_ut_rate += ut_rate mean_rw_rate /=", "try: getattr(self, \"rw_\") getattr(self, \"s_\") except AttributeError: raise RuntimeError(\"You must train estimator before", "has a constructor and it inherits the get_params and set_params methods from BaseEstimator", "pred0 = pred[0] pred1 = pred[1] nb_datapoints = len(X) for i in range(0,", "''' Intialize Q table ''' init_Qval = 1.1 Q = np.full( (len(states), len(actions)),", "''' init_Qval = 1.1 Q = np.full( (len(states), len(actions)), init_Qval ) # optimistic", "in range(0, nb_datapoints): if i != self.average_line : data0 = X[i][0] / 100.", "data_to_save = '{:4.3f} -1 {:4.3f} {:06.3f} -1 {:4.3f} {:4.3f} {:4.3f} {:4.3f}\\n'.format(score, self.alpha, self.tau,", "# data given as percentage but score measured based on rates data1 /=", "> 0\".format(self) exit() if (self.sample_index == -1) : print \"Error: Invalid value for", "Optimization has built-in log functions \"\"\" ''' Initialize the estimator with contructor arguments", "paramset) log_results_internally, log_sequences_internally : int flags indicating whether to save log and result", "as the final results of the run ''' Print attributes ''' #for arg,", "for this problem ''' def rl_3target_vc(alpha, tau, max_steps): ''' Define states, actions and", "# use check_is_fitted(self, ['X_', 'y_']) instead ? ''' Get average result over nb_test_sessions", "{:4.3f}\\n'.format(score, self.alpha, self.tau, data0, data1, pred0, pred1) outfp.write(data_to_save) return score def score_wrt_closest(self, X,", "[0,1].\".format(self) exit() if (self.tau - 0 < 0.0000001): print \"Error: Invalid value for", "- 0 < 0.0000001): print \"Error: Invalid value for parameter tau given to", "1) cumul = 0 for i in range(0, len(dist)): if d < dist[i]", "of the line in the dataset corresponds to the average or has to", "are private methods \"\"\" def __check_params(self, X): \"\"\" This is called by fit()", "random import math ''' Define softmax function ''' def softmax(opts, tau): norm =", "exit() if (self.tau - 0 < 0.0000001): print \"Error: Invalid value for parameter", "functions \"\"\" ''' Initialize the estimator with contructor arguments ''' args, _, _,", "i*lensession first_step = last_step - lensession rw_in_session = self.rw_[first_step:last_step] s_in_session = self.s_[first_step:last_step] #", "out_vcrw.append(1) return [out_choices, out_vcrw] class QLEstimator(BaseEstimator): \"\"\" This is my toy example of", "nb_test_sessions = self.nb_test_sessions mean_rw_rate = 0 mean_ut_rate = 0 for i in range(0,", "''' def draw_from_discrete_proba(dist): d = random.uniform(0, 1) cumul = 0 for i in", "It has a constructor and it inherits the get_params and set_params methods from", "for i in range(0,len(opts)): ret.append(math.exp(opts[i]/tau)) norm += ret[i] for i in range(0,len(opts)): ret[i]", "lensession): if s_in_session[k] == s_in_session[k-2]: nb_ut += 1 ut_rate = nb_ut * 1.", "attributes ''' self.rw_ = out_vcrw self.s_ = out_choices ''' Save data ''' if", "is the distance between prediction and data \"\"\" score = 0 pred =", "append choices str_choices = \"\" # useful for vc out_vcrw = [] #", "return ret ''' Define function for random draw form discrete proba dist '''", "= out_choices ''' Save data ''' if self.log_sequences_internally == 1: datafile = \"log/fit_\"", "is called by fit() to check parameters \"\"\" if (self.alpha - 1 >", "Define QL algorithm for this problem ''' def rl_3target_vc(alpha, tau, max_steps): ''' Define", "QL is run and the results are saved \"\"\" ''' Check parameters '''", "0. RW_C = 1. rewards = [RW_A, RW_B, RW_C] ''' Define output data", "if self.average_line == -1: nb_datapoints = len(X) data0 = 0. data1 = 0.", "import BaseEstimator import inspect import numpy as np import random import math '''", "float QL parameters, resp. learning rate and softmax temperature average_line : int if", "X[i][1] data0 /= (nb_datapoints * 100.) # data given as percentage but score", "\"\"\" ''' Check parameters ''' self.__check_params(X) ''' Run QL ''' out_choices, out_vcrw =", "if draw < rewards[a]: r = 1 else: r = 0 ''' Update", "of the QL agent. \"\"\" try: getattr(self, \"rw_\") getattr(self, \"s_\") except AttributeError: raise", "raise RuntimeError(\"You must train estimator before predicting data!\") # use check_is_fitted(self, ['X_', 'y_'])", "nb_test_sessions): last_step = max_steps - i*lensession first_step = last_step - lensession rw_in_session =", "0 ''' Update Q table ''' delta = alpha*( r - Q[s][a] )", "last sessions ''' max_steps = self.max_steps lensession = self.lensession nb_test_sessions = self.nb_test_sessions mean_rw_rate", "= [] # append choices str_choices = \"\" # useful for vc out_vcrw", "- Q[s][a] ) # gamma = 0 Q[s][a] += delta ''' Update state", "flags indicating whether to save log and result files within estimator this is", "0 ret = [] for i in range(0,len(opts)): ret.append(math.exp(opts[i]/tau)) norm += ret[i] for", "''' Get average result over nb_test_sessions last sessions ''' max_steps = self.max_steps lensession", "in range(0, nb_test_sessions): last_step = max_steps - i*lensession first_step = last_step - lensession", "built-in log functions \"\"\" ''' Initialize the estimator with contructor arguments ''' args,", "on rates else: data0 = X[self.average_line][0] / 100. # data given as percentage", "per paramset) log_results_internally, log_sequences_internally : int flags indicating whether to save log and", "pred[1] score = 1 - ( (abs(pred0 - data0) + abs(pred1 - data1))", "data!\") # use check_is_fitted(self, ['X_', 'y_']) instead ? ''' Get average result over", "draw_from_discrete_proba(dist): d = random.uniform(0, 1) cumul = 0 for i in range(0, len(dist)):", "range(2, lensession): if s_in_session[k] == s_in_session[k-2]: nb_ut += 1 ut_rate = nb_ut *", "{:4.3f} {:4.3f} {:4.3f}\\n'.format(score, self.alpha, self.tau, data0, data1, pred0, pred1) outfp.write(data_to_save) return score def", "= [] # append rewards given by vc ''' Intialize Q table '''", "200 # number of trials in one session self.nb_test_sessions = 10 # number", "nb_datapoints = len(X) for i in range(0, nb_datapoints): if i != self.average_line :", "alpha given to {0}. Value must be in [0,1].\".format(self) exit() if (self.tau -", "estimator using softmax policy It has a constructor and it inherits the get_params", "because agent cannot choose the same target in two consecutive trials a =", "learning rate and softmax temperature average_line : int if one of the line", "saved \"\"\" ''' Check parameters ''' self.__check_params(X) ''' Run QL ''' out_choices, out_vcrw", "instead ? ''' Get average result over nb_test_sessions last sessions ''' max_steps =", "rw_in_session = self.rw_[first_step:last_step] s_in_session = self.s_[first_step:last_step] # rw nb_rw = np.bincount(rw_in_session)[1] rw_rate =", "log_results_internally=1, log_sequences_internally=1): \"\"\" This is the constructor Parameters ---------- alpha, tau : float", "def score_wrt_closest(self, X, y=None): closest_score = 0 closest_index = -1 pred = self.predict(X)", "i != self.average_line : data0 = X[i][0] / 100. data1 = X[i][1] /", "/ 2. ) if self.log_results_internally == 1: logfile = \"results/score_a_fit_\" + str(self.sample_index) +", "{:06.3f} {:d} {:4.3f} {:4.3f}\\n'.format(closest_score, closest_index, self.alpha, self.tau, closest_index, pred0, pred1) outfp.write(data_to_save) \"\"\" These", "methods fit(), predict() and score() \"\"\" def __init__(self, alpha=0.1, tau=5.0, average_line=-1, sample_index=-1, run=1,", "Save data ''' if self.log_sequences_internally == 1: datafile = \"log/fit_\" + str(self.sample_index) +", "return [mean_rw_rate, mean_ut_rate] def score_wrt_average(self, X, y=None): \"\"\" This is where the scor", "if r <= 0: out_vcrw.append(0) else: out_vcrw.append(1) return [out_choices, out_vcrw] class QLEstimator(BaseEstimator): \"\"\"", "of run (if many executions per paramset) log_results_internally, log_sequences_internally : int flags indicating", "lensession # ut nb_ut = 0 for k in range(2, lensession): if s_in_session[k]", "# ut nb_ut = 0 for k in range(2, lensession): if s_in_session[k] ==", "Value must be > 0\".format(self) exit() if (self.sample_index == -1) : print \"Error:", "return score def score_wrt_closest(self, X, y=None): closest_score = 0 closest_index = -1 pred", "''' Update loop variable ''' step += 1 ''' Save output data '''", "is useful when using Grid or Random Search Optimization methods however Bayesian Optimization", "i in range(0,len(opts)): ret[i] /= norm return ret ''' Define function for random", "= 1. RW_B = 0. RW_C = 1. rewards = [RW_A, RW_B, RW_C]", "__init__(self, alpha=0.1, tau=5.0, average_line=-1, sample_index=-1, run=1, log_results_internally=1, log_sequences_internally=1): \"\"\" This is the constructor", "X, y=None): \"\"\" This is where the output data is predicted. Here, it", "between prediction and data \"\"\" score = 0 pred = self.predict(X) if self.average_line", "''' delta = alpha*( r - Q[s][a] ) # gamma = 0 Q[s][a]", "data given as percentage but score measured based on rates pred0 = pred[0]", "parameter alpha given to {0}. Value must be in [0,1].\".format(self) exit() if (self.tau", "X, y=None): \"\"\" This is where the QL is run and the results", "- i*lensession first_step = last_step - lensession rw_in_session = self.rw_[first_step:last_step] s_in_session = self.s_[first_step:last_step]", "must be > 0\".format(self) exit() if (self.sample_index == -1) : print \"Error: Invalid", "trials in one session self.nb_test_sessions = 10 # number of sessions at the", "k in range(2, lensession): if s_in_session[k] == s_in_session[k-2]: nb_ut += 1 ut_rate =", "- data0) + abs(pred1 - data1)) / 2. ) if self.log_results_internally == 1:", "score_wrt_closest(self, X, y=None): closest_score = 0 closest_index = -1 pred = self.predict(X) pred0", "arguments ''' args, _, _, values = inspect.getargvalues(inspect.currentframe()) values.pop(\"self\") for arg, val in", "(self.alpha - 1 > 0.0000001) or (self.alpha - 0 < 0.0000001): print \"Error:", "logfile = \"results/score_a_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a') as outfp:", "X, y=None): closest_score = 0 closest_index = -1 pred = self.predict(X) pred0 =", "ut_rate = nb_ut * 1. / (lensession-2) mean_rw_rate += rw_rate mean_ut_rate += ut_rate", "step < max_steps: ''' Act using softmax policy ''' a = s opts", "[] # append rewards given by vc ''' Intialize Q table ''' init_Qval", "int index of current estimator, the default value -1 should be overriden run", "Value must be in [0,1].\".format(self) exit() if (self.tau - 0 < 0.0000001): print", "= i if self.log_results_internally == 1: logfile = \"results/score_c_fit_\" + str(self.sample_index) + \"_run_\"", "Initialize the estimator with contructor arguments ''' args, _, _, values = inspect.getargvalues(inspect.currentframe())", "number of sessions at the end of run of which the average is", "0.0000001): print \"Error: Invalid value for parameter tau given to {0}. Value must", "is run and the results are saved \"\"\" ''' Check parameters ''' self.__check_params(X)", "d = random.uniform(0, 1) cumul = 0 for i in range(0, len(dist)): if", "check_is_fitted(self, ['X_', 'y_']) instead ? ''' Get average result over nb_test_sessions last sessions", "str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a') as outfp: data_to_save = '{:4.3f} -1", "s opts = np.copy(Q[s][:]) opts[s] = -99 dist = softmax(opts[:], tau) while a==s:", "= [] for i in range(0,len(opts)): ret.append(math.exp(opts[i]/tau)) norm += ret[i] for i in", "sample_index=-1, run=1, log_results_internally=1, log_sequences_internally=1): \"\"\" This is the constructor Parameters ---------- alpha, tau", "max_steps = self.max_steps lensession = self.lensession nb_test_sessions = self.nb_test_sessions mean_rw_rate = 0 mean_ut_rate", "'y_']) instead ? ''' Get average result over nb_test_sessions last sessions ''' max_steps", "i if self.log_results_internally == 1: logfile = \"results/score_c_fit_\" + str(self.sample_index) + \"_run_\" +", "Here, it amounts to evaluate the success rate, u-turn rate, and complexity of", "softmax temperature average_line : int if one of the line in the dataset", "prediction and data \"\"\" score = 0 pred = self.predict(X) if self.average_line ==", "nb_datapoints): if i != self.average_line : data0 = X[i][0] / 100. data1 =", "closest_score = score closest_index = i if self.log_results_internally == 1: logfile = \"results/score_c_fit_\"", "data0 = X[self.average_line][0] / 100. # data given as percentage but score measured", "sessions at the end of run of which the average is considered as", "train estimator before predicting data!\") # use check_is_fitted(self, ['X_', 'y_']) instead ? '''", "score measured based on rates data1 = X[self.average_line][1] / 100. # data given", "percentage but score measured based on rates else: data0 = X[self.average_line][0] / 100.", "print \"Error: Invalid value for parameter tau given to {0}. Value must be", "fit(self, X, y=None): \"\"\" This is where the QL is run and the", ") # gamma = 0 Q[s][a] += delta ''' Update state ''' s", "''' IN_A = GOTO_A = 0 IN_B = GOTO_B = 1 IN_C =", "\"_run_\" + str(self.run) data_to_save = np.transpose((out_choices, out_vcrw)) np.savetxt(datafile, data_to_save, fmt='%d') def predict(self, X,", "the average is computed. Here, the score is the distance between prediction and", "np.transpose((out_choices, out_vcrw)) np.savetxt(datafile, data_to_save, fmt='%d') def predict(self, X, y=None): \"\"\" This is where", "for parameter alpha given to {0}. Value must be in [0,1].\".format(self) exit() if", "Optimization methods however Bayesian Optimization has built-in log functions \"\"\" ''' Initialize the", "# data given as percentage but score measured based on rates pred0 =", "\"log/fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) data_to_save = np.transpose((out_choices, out_vcrw)) np.savetxt(datafile, data_to_save,", "+ abs(pred1 - data1)) / 2. ) if self.log_results_internally == 1: logfile =", "before predicting data!\") # use check_is_fitted(self, ['X_', 'y_']) instead ? ''' Get average", "ret ''' Define function for random draw form discrete proba dist ''' def", "RW_C] ''' Define output data variables ''' out_choices = [] # append choices", "open(logfile,'a') as outfp: data_to_save = '{:4.3f} -1 {:4.3f} {:06.3f} -1 {:4.3f} {:4.3f} {:4.3f}", "given to {0}. Default value (-1) should be overriden with a positive value.\".format(self)", "which the average is considered as the final results of the run '''", "[\"A\", 'B', \"C\"] RW_A = 1. RW_B = 0. RW_C = 1. rewards", "using Grid or Random Search Optimization methods however Bayesian Optimization has built-in log", "1: logfile = \"results/score_c_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a') as", "''' args, _, _, values = inspect.getargvalues(inspect.currentframe()) values.pop(\"self\") for arg, val in values.items():", "score is the distance between prediction and data \"\"\" score = 0 pred", "percentage but score measured based on rates data1 /= (nb_datapoints * 100.) #", "self.tau, closest_index, pred0, pred1) outfp.write(data_to_save) \"\"\" These are private methods \"\"\" def __check_params(self,", "i in range(0,len(opts)): ret.append(math.exp(opts[i]/tau)) norm += ret[i] for i in range(0,len(opts)): ret[i] /=", "Search Optimization methods however Bayesian Optimization has built-in log functions \"\"\" ''' Initialize", "AttributeError: raise RuntimeError(\"You must train estimator before predicting data!\") # use check_is_fitted(self, ['X_',", "self.log_results_internally == 1: logfile = \"results/score_a_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) with", "Invalid value for parameter tau given to {0}. Value must be > 0\".format(self)", "pred1) outfp.write(data_to_save) \"\"\" These are private methods \"\"\" def __check_params(self, X): \"\"\" This", "labels = [\"A\", 'B', \"C\"] RW_A = 1. RW_B = 0. RW_C =", "IN_A = GOTO_A = 0 IN_B = GOTO_B = 1 IN_C = GOTO_C", "the results are saved \"\"\" ''' Check parameters ''' self.__check_params(X) ''' Run QL", "/ (lensession-2) mean_rw_rate += rw_rate mean_ut_rate += ut_rate mean_rw_rate /= nb_test_sessions mean_ut_rate /=", "score closest_index = i if self.log_results_internally == 1: logfile = \"results/score_c_fit_\" + str(self.sample_index)", "= 0 IN_B = GOTO_B = 1 IN_C = GOTO_C = 2 states", "data1)) / 2. ) if score > closest_score: closest_score = score closest_index =", "/= norm return ret ''' Define function for random draw form discrete proba", "mean_rw_rate += rw_rate mean_ut_rate += ut_rate mean_rw_rate /= nb_test_sessions mean_ut_rate /= nb_test_sessions return", "dist = softmax(opts[:], tau) while a==s: # try until GOTO != s, because", "= GOTO_A = 0 IN_B = GOTO_B = 1 IN_C = GOTO_C =", "-1 means the average will be computed online sample_index : int index of", "parameters ''' self.max_steps = 10000 # number of trials per run self.lensession =", "results are saved \"\"\" ''' Check parameters ''' self.__check_params(X) ''' Run QL '''", "= [\"A\", 'B', \"C\"] RW_A = 1. RW_B = 0. RW_C = 1.", "ret[i] for i in range(0,len(opts)): ret[i] /= norm return ret ''' Define function", "data_to_save, fmt='%d') def predict(self, X, y=None): \"\"\" This is where the output data", "import random import math ''' Define softmax function ''' def softmax(opts, tau): norm", "self.log_results_internally == 1: logfile = \"results/score_c_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) with", "''' Update Q table ''' delta = alpha*( r - Q[s][a] ) #", "< dist[i] + cumul: return i cumul += dist[i] ''' Define QL algorithm", "= 0 Q[s][a] += delta ''' Update state ''' s = a '''", "i in range(0, nb_datapoints): if i != self.average_line : data0 = X[i][0] /", "\"\" # useful for vc out_vcrw = [] # append rewards given by", "out_choices = [] # append choices str_choices = \"\" # useful for vc", "class QLEstimator(BaseEstimator): \"\"\" This is my toy example of a Q-Learning estimator using", "= GOTO_B = 1 IN_C = GOTO_C = 2 states = [IN_A, IN_B,", "\"\"\" This is the constructor Parameters ---------- alpha, tau : float QL parameters,", "inspect import numpy as np import random import math ''' Define softmax function", "dist[i] ''' Define QL algorithm for this problem ''' def rl_3target_vc(alpha, tau, max_steps):", "of a Q-Learning estimator using softmax policy It has a constructor and it", "= np.bincount(rw_in_session)[1] rw_rate = nb_rw * 1. / lensession # ut nb_ut =", "dist ''' def draw_from_discrete_proba(dist): d = random.uniform(0, 1) cumul = 0 for i", "files within estimator this is useful when using Grid or Random Search Optimization", "estimator wrt the average is computed. Here, the score is the distance between", "self.alpha, self.tau, closest_index, pred0, pred1) outfp.write(data_to_save) \"\"\" These are private methods \"\"\" def", "self.average_line : data0 = X[i][0] / 100. data1 = X[i][1] / 100. score", "to {0}. Value must be > 0\".format(self) exit() if (self.sample_index == -1) :", "two consecutive trials a = draw_from_discrete_proba(dist) ''' Get reward: GOTO_X -> RW_X '''", "percentage but score measured based on rates data1 = X[self.average_line][1] / 100. #", "/ 100. score = 1 - ( (abs(pred0 - data0) + abs(pred1 -", "to evaluate the success rate, u-turn rate, and complexity of the QL agent.", "= a ''' Update loop variable ''' step += 1 ''' Save output", "-1 {:4.3f} {:06.3f} -1 {:4.3f} {:4.3f} {:4.3f} {:4.3f}\\n'.format(score, self.alpha, self.tau, data0, data1, pred0,", "be fitted, otherwise -1 means the average will be computed online sample_index :", "self.average_line == -1: nb_datapoints = len(X) data0 = 0. data1 = 0. for", "X): \"\"\" This is called by fit() to check parameters \"\"\" if (self.alpha", "''' Define QL algorithm for this problem ''' def rl_3target_vc(alpha, tau, max_steps): '''", "from sklearn.base import BaseEstimator import inspect import numpy as np import random import", "-1 should be overriden run : int index of run (if many executions", "a ''' Update loop variable ''' step += 1 ''' Save output data", "def rl_3target_vc(alpha, tau, max_steps): ''' Define states, actions and reward probabilities ''' IN_A", "whether to save log and result files within estimator this is useful when", "arg, val) ''' Add hard-coded parameters ''' self.max_steps = 10000 # number of", "Get average result over nb_test_sessions last sessions ''' max_steps = self.max_steps lensession =", "corresponds to the average or has to be fitted, otherwise -1 means the", "self.predict(X) if self.average_line == -1: nb_datapoints = len(X) data0 = 0. data1 =", "data1 = 0. for i in range(0, nb_datapoints): data0 += X[i][0] data1 +=", "data0 += X[i][0] data1 += X[i][1] data0 /= (nb_datapoints * 100.) # data", "for arg, val in values.items(): setattr(self, arg, val) ''' Add hard-coded parameters '''", "0 < 0.0000001): print \"Error: Invalid value for parameter alpha given to {0}.", "states, actions and reward probabilities ''' IN_A = GOTO_A = 0 IN_B =", "probabilities ''' IN_A = GOTO_A = 0 IN_B = GOTO_B = 1 IN_C", "fit(), predict() and score() \"\"\" def __init__(self, alpha=0.1, tau=5.0, average_line=-1, sample_index=-1, run=1, log_results_internally=1,", "default value -1 should be overriden run : int index of run (if", "reward probabilities ''' IN_A = GOTO_A = 0 IN_B = GOTO_B = 1", "and set_params methods from BaseEstimator It overrides the methods fit(), predict() and score()", "has built-in log functions \"\"\" ''' Initialize the estimator with contructor arguments '''", "''' self.__check_params(X) ''' Run QL ''' out_choices, out_vcrw = rl_3target_vc(self.alpha, self.tau, self.max_steps) '''", "softmax(opts, tau): norm = 0 ret = [] for i in range(0,len(opts)): ret.append(math.exp(opts[i]/tau))", "Act using softmax policy ''' a = s opts = np.copy(Q[s][:]) opts[s] =", "Bayesian Optimization has built-in log functions \"\"\" ''' Initialize the estimator with contructor", "number of trials per run self.lensession = 200 # number of trials in", "\"\"\" try: getattr(self, \"rw_\") getattr(self, \"s_\") except AttributeError: raise RuntimeError(\"You must train estimator", "in range(0, nb_datapoints): data0 += X[i][0] data1 += X[i][1] data0 /= (nb_datapoints *", "constructor and it inherits the get_params and set_params methods from BaseEstimator It overrides", "''' self.max_steps = 10000 # number of trials per run self.lensession = 200", "run : int index of run (if many executions per paramset) log_results_internally, log_sequences_internally", "\"_run_\" + str(self.run) with open(logfile,'a') as outfp: data_to_save = '{:4.3f} {:d} {:4.3f} {:06.3f}", "the QL agent. \"\"\" try: getattr(self, \"rw_\") getattr(self, \"s_\") except AttributeError: raise RuntimeError(\"You", "of trials in one session self.nb_test_sessions = 10 # number of sessions at", "getattr(self, \"rw_\") getattr(self, \"s_\") except AttributeError: raise RuntimeError(\"You must train estimator before predicting", "self.s_[first_step:last_step] # rw nb_rw = np.bincount(rw_in_session)[1] rw_rate = nb_rw * 1. / lensession", "average_line : int if one of the line in the dataset corresponds to", "trials per run self.lensession = 200 # number of trials in one session", "data \"\"\" score = 0 pred = self.predict(X) if self.average_line == -1: nb_datapoints", "> closest_score: closest_score = score closest_index = i if self.log_results_internally == 1: logfile", "self.s_ = out_choices ''' Save data ''' if self.log_sequences_internally == 1: datafile =", "same target in two consecutive trials a = draw_from_discrete_proba(dist) ''' Get reward: GOTO_X", "= len(X) data0 = 0. data1 = 0. for i in range(0, nb_datapoints):", "estimator before predicting data!\") # use check_is_fitted(self, ['X_', 'y_']) instead ? ''' Get", "pred1 = pred[1] nb_datapoints = len(X) for i in range(0, nb_datapoints): if i", "This is where the QL is run and the results are saved \"\"\"", "as percentage but score measured based on rates data1 /= (nb_datapoints * 100.)", "0 closest_index = -1 pred = self.predict(X) pred0 = pred[0] pred1 = pred[1]", "def predict(self, X, y=None): \"\"\" This is where the output data is predicted.", "GOTO_C] labels = [\"A\", 'B', \"C\"] RW_A = 1. RW_B = 0. RW_C", "Intialize Q table ''' init_Qval = 1.1 Q = np.full( (len(states), len(actions)), init_Qval", "rl_3target_vc(alpha, tau, max_steps): ''' Define states, actions and reward probabilities ''' IN_A =", "norm += ret[i] for i in range(0,len(opts)): ret[i] /= norm return ret '''", "the default value -1 should be overriden run : int index of run", "policy ''' a = s opts = np.copy(Q[s][:]) opts[s] = -99 dist =", "pred0 = pred[0] pred1 = pred[1] score = 1 - ( (abs(pred0 -", "variable ''' step += 1 ''' Save output data ''' out_choices.append(a) str_choices =", "based on rates data1 /= (nb_datapoints * 100.) # data given as percentage", "{:4.3f} {:4.3f}\\n'.format(score, self.alpha, self.tau, data0, data1, pred0, pred1) outfp.write(data_to_save) return score def score_wrt_closest(self,", "- lensession rw_in_session = self.rw_[first_step:last_step] s_in_session = self.s_[first_step:last_step] # rw nb_rw = np.bincount(rw_in_session)[1]", "'{:4.3f} -1 {:4.3f} {:06.3f} -1 {:4.3f} {:4.3f} {:4.3f} {:4.3f}\\n'.format(score, self.alpha, self.tau, data0, data1,", "int if one of the line in the dataset corresponds to the average", "this is useful when using Grid or Random Search Optimization methods however Bayesian", "''' Start simulation ''' s = IN_A step = 0 while step <", "''' s = a ''' Update loop variable ''' step += 1 '''", "algorithm for this problem ''' def rl_3target_vc(alpha, tau, max_steps): ''' Define states, actions", "data_to_save = '{:4.3f} {:d} {:4.3f} {:06.3f} {:d} {:4.3f} {:4.3f}\\n'.format(closest_score, closest_index, self.alpha, self.tau, closest_index,", "rates else: data0 = X[self.average_line][0] / 100. # data given as percentage but", "np.savetxt(datafile, data_to_save, fmt='%d') def predict(self, X, y=None): \"\"\" This is where the output", "\"\"\" ''' Initialize the estimator with contructor arguments ''' args, _, _, values", "amounts to evaluate the success rate, u-turn rate, and complexity of the QL", "X, y=None): \"\"\" This is where the scor eof the estimator wrt the", "data variables ''' out_choices = [] # append choices str_choices = \"\" #", "= \"results/score_a_fit_\" + str(self.sample_index) + \"_run_\" + str(self.run) with open(logfile,'a') as outfp: data_to_save", "use check_is_fitted(self, ['X_', 'y_']) instead ? ''' Get average result over nb_test_sessions last", "RW_C = 1. rewards = [RW_A, RW_B, RW_C] ''' Define output data variables", "QLEstimator(BaseEstimator): \"\"\" This is my toy example of a Q-Learning estimator using softmax" ]
[ "= 0 soma = 0 for c in range(1, 501, 2): if c", "if c % 3 ==0: soma = soma + c cont = cont", "2): if c % 3 ==0: soma = soma + c cont =", "cont = 0 soma = 0 for c in range(1, 501, 2): if", "+ c cont = cont + 1 print(f'A soma de todos os dos", "= 0 for c in range(1, 501, 2): if c % 3 ==0:", "soma = soma + c cont = cont + 1 print(f'A soma de", "for c in range(1, 501, 2): if c % 3 ==0: soma =", "= cont + 1 print(f'A soma de todos os dos {cont} numeros impares", "in range(1, 501, 2): if c % 3 ==0: soma = soma +", "3 ==0: soma = soma + c cont = cont + 1 print(f'A", "soma = 0 for c in range(1, 501, 2): if c % 3", "501, 2): if c % 3 ==0: soma = soma + c cont", "% 3 ==0: soma = soma + c cont = cont + 1", "soma + c cont = cont + 1 print(f'A soma de todos os", "+ 1 print(f'A soma de todos os dos {cont} numeros impares sera:{soma} ')", "= soma + c cont = cont + 1 print(f'A soma de todos", "cont = cont + 1 print(f'A soma de todos os dos {cont} numeros", "0 soma = 0 for c in range(1, 501, 2): if c %", "c % 3 ==0: soma = soma + c cont = cont +", "==0: soma = soma + c cont = cont + 1 print(f'A soma", "c cont = cont + 1 print(f'A soma de todos os dos {cont}", "cont + 1 print(f'A soma de todos os dos {cont} numeros impares sera:{soma}", "c in range(1, 501, 2): if c % 3 ==0: soma = soma", "range(1, 501, 2): if c % 3 ==0: soma = soma + c", "<reponame>Santos1000/Curso-Python cont = 0 soma = 0 for c in range(1, 501, 2):", "0 for c in range(1, 501, 2): if c % 3 ==0: soma" ]
[ "of first image. ''' first = np.array(self.video[0:self.video.shape[0]-1, :, :,]) second = np.array(self.video[1:self.video.shape[0], :,", "you want to have in te current image. Example: alpha = (0.5, 0.5)", "def show_image(X): if len(X.shape) == 3: cv2.imshow('image', X) else: for image in X:", "for image in X: image = cv2.resize(image, dimensions) return X def show_image(X): if", "de Junio del 2018 # 31 Mayo 2018 import numpy as np import", "as np import matplotlib.pyplot as plt from time import sleep import cv2 class", "np import matplotlib.pyplot as plt from time import sleep import cv2 class Recurrent_Photo:", "else: for image in X: cv2.imshow('X', image) cv2.waitKey(1) sleep(0.05) non_movement = Recurrent_Photo(50) print('Prepare", "np.abs(A - B) def resize_images(X, dimensions=(100, 75)): if len(X.shape) == 3: X =", "== 3: X = cv2.resize(X, dimensions) else: for image in X: image =", "testing ''' def __init__(self, iterations=100, resize=(1280, 720)): self.camera = cv2.VideoCapture(0) self.video = np.zeros([iterations,", ":]) diferences = self.get_diference( second, first ) for image in range(len(diferences)): diferences[image] =", "# 05 de Junio del 2018 # 31 Mayo 2018 import numpy as", "items ''' return np.abs(A - B) def resize_images(X, dimensions=(100, 75)): if len(X.shape) ==", "next movement...') sleep(2) movement = Recurrent_Photo(50) non_movement_recurrence = non_movement.get_recurrence() movement_recurrence = movement.get_recurrence() X", "the amount of superposition that you want to have in te current image.", "image in X: image = cv2.resize(image, dimensions) return X def show_image(X): if len(X.shape)", ") cv2.imshow('Prueba', self.video[iteration, :, :]) cv2.waitKey(1) self.camera.release() self.resize = resize def get_recurrence(self, alpha=(0.75555,", "first image. ''' first = np.array(self.video[0:self.video.shape[0]-1, :, :,]) second = np.array(self.video[1:self.video.shape[0], :, :])", "have the same intensity of first image. ''' first = np.array(self.video[0:self.video.shape[0]-1, :, :,])", ":, :]) cv2.waitKey(1) self.camera.release() self.resize = resize def get_recurrence(self, alpha=(0.75555, 0.25555)): ''' Alpha", "alpha[1] # Mirar ecuacion del cuaderno. return diferences def get_diference(self, A, B): '''", "only for testing ''' def __init__(self, iterations=100, resize=(1280, 720)): self.camera = cv2.VideoCapture(0) self.video", "range(iterations): self.video[iteration, :, :] = cv2.resize( (self.camera.read()[1]/255), # FIXME: AHORA TRABAJAMOS CON LOS", "self.camera = cv2.VideoCapture(0) self.video = np.zeros([iterations, resize[1], resize[0], 3]) for iteration in range(iterations):", "current image. Example: alpha = (0.5, 0.5) is neutral change, were the last", "neutral change, were the last image will have the same intensity of first", "''' def __init__(self, iterations=100, resize=(1280, 720)): self.camera = cv2.VideoCapture(0) self.video = np.zeros([iterations, resize[1],", "''' return np.abs(A - B) def resize_images(X, dimensions=(100, 75)): if len(X.shape) == 3:", "image. Example: alpha = (0.5, 0.5) is neutral change, were the last image", "sleep(2) movement = Recurrent_Photo(50) non_movement_recurrence = non_movement.get_recurrence() movement_recurrence = movement.get_recurrence() X = resize_images(non_movement_recurrence)", "Photo only for testing ''' def __init__(self, iterations=100, resize=(1280, 720)): self.camera = cv2.VideoCapture(0)", "cv2.imshow('Prueba', self.video[iteration, :, :]) cv2.waitKey(1) self.camera.release() self.resize = resize def get_recurrence(self, alpha=(0.75555, 0.25555)):", "def get_recurrence(self, alpha=(0.75555, 0.25555)): ''' Alpha are 2 float numbers represented by the", "plt from time import sleep import cv2 class Recurrent_Photo: ''' Recurrent Photo only", "iteration in range(iterations): self.video[iteration, :, :] = cv2.resize( (self.camera.read()[1]/255), # FIXME: AHORA TRABAJAMOS", "diferences[image] = diferences[image-1]* alpha[0] + diferences[image]* alpha[1] # Mirar ecuacion del cuaderno. return", "import matplotlib.pyplot as plt from time import sleep import cv2 class Recurrent_Photo: '''", "the last image will have the same intensity of first image. ''' first", "numbers represented by the amount of superposition that you want to have in", "''' Get diference from two items ''' return np.abs(A - B) def resize_images(X,", "show_image(X): if len(X.shape) == 3: cv2.imshow('image', X) else: for image in X: cv2.imshow('X',", "Mayo 2018 import numpy as np import matplotlib.pyplot as plt from time import", "self.video = np.zeros([iterations, resize[1], resize[0], 3]) for iteration in range(iterations): self.video[iteration, :, :]", "= (0.5, 0.5) is neutral change, were the last image will have the", "range(len(diferences)): diferences[image] = diferences[image-1]* alpha[0] + diferences[image]* alpha[1] # Mirar ecuacion del cuaderno.", "is neutral change, were the last image will have the same intensity of", "for image in range(len(diferences)): diferences[image] = diferences[image-1]* alpha[0] + diferences[image]* alpha[1] # Mirar", "Junio del 2018 # 31 Mayo 2018 import numpy as np import matplotlib.pyplot", "def __init__(self, iterations=100, resize=(1280, 720)): self.camera = cv2.VideoCapture(0) self.video = np.zeros([iterations, resize[1], resize[0],", "if len(X.shape) == 3: X = cv2.resize(X, dimensions) else: for image in X:", "np.array(self.video[1:self.video.shape[0], :, :]) diferences = self.get_diference( second, first ) for image in range(len(diferences)):", "CANALES resize ) cv2.imshow('Prueba', self.video[iteration, :, :]) cv2.waitKey(1) self.camera.release() self.resize = resize def", "second, first ) for image in range(len(diferences)): diferences[image] = diferences[image-1]* alpha[0] + diferences[image]*", "self.video[iteration, :, :]) cv2.waitKey(1) self.camera.release() self.resize = resize def get_recurrence(self, alpha=(0.75555, 0.25555)): '''", "sleep import cv2 class Recurrent_Photo: ''' Recurrent Photo only for testing ''' def", "are 2 float numbers represented by the amount of superposition that you want", "self.get_diference( second, first ) for image in range(len(diferences)): diferences[image] = diferences[image-1]* alpha[0] +", "else: for image in X: image = cv2.resize(image, dimensions) return X def show_image(X):", "cv2.imshow('X', image) cv2.waitKey(1) sleep(0.05) non_movement = Recurrent_Photo(50) print('Prepare next movement...') sleep(2) movement =", "B) def resize_images(X, dimensions=(100, 75)): if len(X.shape) == 3: X = cv2.resize(X, dimensions)", "cv2.waitKey(1) sleep(0.05) non_movement = Recurrent_Photo(50) print('Prepare next movement...') sleep(2) movement = Recurrent_Photo(50) non_movement_recurrence", "FIXME: AHORA TRABAJAMOS CON LOS TRES CANALES resize ) cv2.imshow('Prueba', self.video[iteration, :, :])", "movement...') sleep(2) movement = Recurrent_Photo(50) non_movement_recurrence = non_movement.get_recurrence() movement_recurrence = movement.get_recurrence() X =", "TRES CANALES resize ) cv2.imshow('Prueba', self.video[iteration, :, :]) cv2.waitKey(1) self.camera.release() self.resize = resize", "''' Recurrent Photo only for testing ''' def __init__(self, iterations=100, resize=(1280, 720)): self.camera", "same intensity of first image. ''' first = np.array(self.video[0:self.video.shape[0]-1, :, :,]) second =", "cv2.resize(X, dimensions) else: for image in X: image = cv2.resize(image, dimensions) return X", "cv2.resize( (self.camera.read()[1]/255), # FIXME: AHORA TRABAJAMOS CON LOS TRES CANALES resize ) cv2.imshow('Prueba',", "in X: cv2.imshow('X', image) cv2.waitKey(1) sleep(0.05) non_movement = Recurrent_Photo(50) print('Prepare next movement...') sleep(2)", "Recurrent_Photo(50) non_movement_recurrence = non_movement.get_recurrence() movement_recurrence = movement.get_recurrence() X = resize_images(non_movement_recurrence) Y = resize_images(movement_recurrence)", "resize def get_recurrence(self, alpha=(0.75555, 0.25555)): ''' Alpha are 2 float numbers represented by", "amount of superposition that you want to have in te current image. Example:", "dimensions) return X def show_image(X): if len(X.shape) == 3: cv2.imshow('image', X) else: for", "''' Alpha are 2 float numbers represented by the amount of superposition that", "if len(X.shape) == 3: cv2.imshow('image', X) else: for image in X: cv2.imshow('X', image)", ":, :]) diferences = self.get_diference( second, first ) for image in range(len(diferences)): diferences[image]", "alpha=(0.75555, 0.25555)): ''' Alpha are 2 float numbers represented by the amount of", ":]) cv2.waitKey(1) self.camera.release() self.resize = resize def get_recurrence(self, alpha=(0.75555, 0.25555)): ''' Alpha are", "te current image. Example: alpha = (0.5, 0.5) is neutral change, were the", "last image will have the same intensity of first image. ''' first =", "for iteration in range(iterations): self.video[iteration, :, :] = cv2.resize( (self.camera.read()[1]/255), # FIXME: AHORA", ":, :] = cv2.resize( (self.camera.read()[1]/255), # FIXME: AHORA TRABAJAMOS CON LOS TRES CANALES", "self.video[iteration, :, :] = cv2.resize( (self.camera.read()[1]/255), # FIXME: AHORA TRABAJAMOS CON LOS TRES", "intensity of first image. ''' first = np.array(self.video[0:self.video.shape[0]-1, :, :,]) second = np.array(self.video[1:self.video.shape[0],", "= cv2.resize(X, dimensions) else: for image in X: image = cv2.resize(image, dimensions) return", "diferences = self.get_diference( second, first ) for image in range(len(diferences)): diferences[image] = diferences[image-1]*", "will have the same intensity of first image. ''' first = np.array(self.video[0:self.video.shape[0]-1, :,", "def resize_images(X, dimensions=(100, 75)): if len(X.shape) == 3: X = cv2.resize(X, dimensions) else:", "def get_diference(self, A, B): ''' Get diference from two items ''' return np.abs(A", "dimensions=(100, 75)): if len(X.shape) == 3: X = cv2.resize(X, dimensions) else: for image", "= cv2.resize( (self.camera.read()[1]/255), # FIXME: AHORA TRABAJAMOS CON LOS TRES CANALES resize )", "of superposition that you want to have in te current image. Example: alpha", "diferences[image]* alpha[1] # Mirar ecuacion del cuaderno. return diferences def get_diference(self, A, B):", "from two items ''' return np.abs(A - B) def resize_images(X, dimensions=(100, 75)): if", "= self.get_diference( second, first ) for image in range(len(diferences)): diferences[image] = diferences[image-1]* alpha[0]", "in range(len(diferences)): diferences[image] = diferences[image-1]* alpha[0] + diferences[image]* alpha[1] # Mirar ecuacion del", "float numbers represented by the amount of superposition that you want to have", "= Recurrent_Photo(50) non_movement_recurrence = non_movement.get_recurrence() movement_recurrence = movement.get_recurrence() X = resize_images(non_movement_recurrence) Y =", "cv2.VideoCapture(0) self.video = np.zeros([iterations, resize[1], resize[0], 3]) for iteration in range(iterations): self.video[iteration, :,", "LOS TRES CANALES resize ) cv2.imshow('Prueba', self.video[iteration, :, :]) cv2.waitKey(1) self.camera.release() self.resize =", "image) cv2.waitKey(1) sleep(0.05) non_movement = Recurrent_Photo(50) print('Prepare next movement...') sleep(2) movement = Recurrent_Photo(50)", "iterations=100, resize=(1280, 720)): self.camera = cv2.VideoCapture(0) self.video = np.zeros([iterations, resize[1], resize[0], 3]) for", "import sleep import cv2 class Recurrent_Photo: ''' Recurrent Photo only for testing '''", "get_recurrence(self, alpha=(0.75555, 0.25555)): ''' Alpha are 2 float numbers represented by the amount", "alpha = (0.5, 0.5) is neutral change, were the last image will have", "represented by the amount of superposition that you want to have in te", "resize=(1280, 720)): self.camera = cv2.VideoCapture(0) self.video = np.zeros([iterations, resize[1], resize[0], 3]) for iteration", "# FIXME: AHORA TRABAJAMOS CON LOS TRES CANALES resize ) cv2.imshow('Prueba', self.video[iteration, :,", ":] = cv2.resize( (self.camera.read()[1]/255), # FIXME: AHORA TRABAJAMOS CON LOS TRES CANALES resize", "# 31 Mayo 2018 import numpy as np import matplotlib.pyplot as plt from", "__init__(self, iterations=100, resize=(1280, 720)): self.camera = cv2.VideoCapture(0) self.video = np.zeros([iterations, resize[1], resize[0], 3])", "change, were the last image will have the same intensity of first image.", "''' first = np.array(self.video[0:self.video.shape[0]-1, :, :,]) second = np.array(self.video[1:self.video.shape[0], :, :]) diferences =", "cuaderno. return diferences def get_diference(self, A, B): ''' Get diference from two items", "0.5) is neutral change, were the last image will have the same intensity", "X) else: for image in X: cv2.imshow('X', image) cv2.waitKey(1) sleep(0.05) non_movement = Recurrent_Photo(50)", "= np.array(self.video[1:self.video.shape[0], :, :]) diferences = self.get_diference( second, first ) for image in", "in te current image. Example: alpha = (0.5, 0.5) is neutral change, were", "cv2.resize(image, dimensions) return X def show_image(X): if len(X.shape) == 3: cv2.imshow('image', X) else:", "import numpy as np import matplotlib.pyplot as plt from time import sleep import", "cv2 class Recurrent_Photo: ''' Recurrent Photo only for testing ''' def __init__(self, iterations=100,", "movement = Recurrent_Photo(50) non_movement_recurrence = non_movement.get_recurrence() movement_recurrence = movement.get_recurrence() X = resize_images(non_movement_recurrence) Y", "class Recurrent_Photo: ''' Recurrent Photo only for testing ''' def __init__(self, iterations=100, resize=(1280,", "720)): self.camera = cv2.VideoCapture(0) self.video = np.zeros([iterations, resize[1], resize[0], 3]) for iteration in", "= np.zeros([iterations, resize[1], resize[0], 3]) for iteration in range(iterations): self.video[iteration, :, :] =", "Recurrent Photo only for testing ''' def __init__(self, iterations=100, resize=(1280, 720)): self.camera =", "self.camera.release() self.resize = resize def get_recurrence(self, alpha=(0.75555, 0.25555)): ''' Alpha are 2 float", "ecuacion del cuaderno. return diferences def get_diference(self, A, B): ''' Get diference from", "2018 # 31 Mayo 2018 import numpy as np import matplotlib.pyplot as plt", "resize[0], 3]) for iteration in range(iterations): self.video[iteration, :, :] = cv2.resize( (self.camera.read()[1]/255), #", "numpy as np import matplotlib.pyplot as plt from time import sleep import cv2", "return np.abs(A - B) def resize_images(X, dimensions=(100, 75)): if len(X.shape) == 3: X", "X def show_image(X): if len(X.shape) == 3: cv2.imshow('image', X) else: for image in", "diference from two items ''' return np.abs(A - B) def resize_images(X, dimensions=(100, 75)):", "# Mirar ecuacion del cuaderno. return diferences def get_diference(self, A, B): ''' Get", "resize[1], resize[0], 3]) for iteration in range(iterations): self.video[iteration, :, :] = cv2.resize( (self.camera.read()[1]/255),", "np.zeros([iterations, resize[1], resize[0], 3]) for iteration in range(iterations): self.video[iteration, :, :] = cv2.resize(", "3]) for iteration in range(iterations): self.video[iteration, :, :] = cv2.resize( (self.camera.read()[1]/255), # FIXME:", "0.25555)): ''' Alpha are 2 float numbers represented by the amount of superposition", "self.resize = resize def get_recurrence(self, alpha=(0.75555, 0.25555)): ''' Alpha are 2 float numbers", "first = np.array(self.video[0:self.video.shape[0]-1, :, :,]) second = np.array(self.video[1:self.video.shape[0], :, :]) diferences = self.get_diference(", "print('Prepare next movement...') sleep(2) movement = Recurrent_Photo(50) non_movement_recurrence = non_movement.get_recurrence() movement_recurrence = movement.get_recurrence()", "np.array(self.video[0:self.video.shape[0]-1, :, :,]) second = np.array(self.video[1:self.video.shape[0], :, :]) diferences = self.get_diference( second, first", "Mirar ecuacion del cuaderno. return diferences def get_diference(self, A, B): ''' Get diference", "image. ''' first = np.array(self.video[0:self.video.shape[0]-1, :, :,]) second = np.array(self.video[1:self.video.shape[0], :, :]) diferences", "Get diference from two items ''' return np.abs(A - B) def resize_images(X, dimensions=(100,", "that you want to have in te current image. Example: alpha = (0.5,", "31 Mayo 2018 import numpy as np import matplotlib.pyplot as plt from time", "B): ''' Get diference from two items ''' return np.abs(A - B) def", "want to have in te current image. Example: alpha = (0.5, 0.5) is", "= cv2.VideoCapture(0) self.video = np.zeros([iterations, resize[1], resize[0], 3]) for iteration in range(iterations): self.video[iteration,", "matplotlib.pyplot as plt from time import sleep import cv2 class Recurrent_Photo: ''' Recurrent", "3: X = cv2.resize(X, dimensions) else: for image in X: image = cv2.resize(image,", "resize_images(X, dimensions=(100, 75)): if len(X.shape) == 3: X = cv2.resize(X, dimensions) else: for", "the same intensity of first image. ''' first = np.array(self.video[0:self.video.shape[0]-1, :, :,]) second", "return X def show_image(X): if len(X.shape) == 3: cv2.imshow('image', X) else: for image", "== 3: cv2.imshow('image', X) else: for image in X: cv2.imshow('X', image) cv2.waitKey(1) sleep(0.05)", "from time import sleep import cv2 class Recurrent_Photo: ''' Recurrent Photo only for", "to have in te current image. Example: alpha = (0.5, 0.5) is neutral", "diferences[image-1]* alpha[0] + diferences[image]* alpha[1] # Mirar ecuacion del cuaderno. return diferences def", "return diferences def get_diference(self, A, B): ''' Get diference from two items '''", "for image in X: cv2.imshow('X', image) cv2.waitKey(1) sleep(0.05) non_movement = Recurrent_Photo(50) print('Prepare next", "Alpha are 2 float numbers represented by the amount of superposition that you", "by the amount of superposition that you want to have in te current", "len(X.shape) == 3: X = cv2.resize(X, dimensions) else: for image in X: image", "del cuaderno. return diferences def get_diference(self, A, B): ''' Get diference from two", "AHORA TRABAJAMOS CON LOS TRES CANALES resize ) cv2.imshow('Prueba', self.video[iteration, :, :]) cv2.waitKey(1)", "Recurrent_Photo(50) print('Prepare next movement...') sleep(2) movement = Recurrent_Photo(50) non_movement_recurrence = non_movement.get_recurrence() movement_recurrence =", "2018 import numpy as np import matplotlib.pyplot as plt from time import sleep", "2 float numbers represented by the amount of superposition that you want to", "CON LOS TRES CANALES resize ) cv2.imshow('Prueba', self.video[iteration, :, :]) cv2.waitKey(1) self.camera.release() self.resize", "3: cv2.imshow('image', X) else: for image in X: cv2.imshow('X', image) cv2.waitKey(1) sleep(0.05) non_movement", "- B) def resize_images(X, dimensions=(100, 75)): if len(X.shape) == 3: X = cv2.resize(X,", "time import sleep import cv2 class Recurrent_Photo: ''' Recurrent Photo only for testing", "len(X.shape) == 3: cv2.imshow('image', X) else: for image in X: cv2.imshow('X', image) cv2.waitKey(1)", "in range(iterations): self.video[iteration, :, :] = cv2.resize( (self.camera.read()[1]/255), # FIXME: AHORA TRABAJAMOS CON", "05 de Junio del 2018 # 31 Mayo 2018 import numpy as np", "image will have the same intensity of first image. ''' first = np.array(self.video[0:self.video.shape[0]-1,", "Example: alpha = (0.5, 0.5) is neutral change, were the last image will", ":,]) second = np.array(self.video[1:self.video.shape[0], :, :]) diferences = self.get_diference( second, first ) for", "as plt from time import sleep import cv2 class Recurrent_Photo: ''' Recurrent Photo", "non_movement = Recurrent_Photo(50) print('Prepare next movement...') sleep(2) movement = Recurrent_Photo(50) non_movement_recurrence = non_movement.get_recurrence()", ") for image in range(len(diferences)): diferences[image] = diferences[image-1]* alpha[0] + diferences[image]* alpha[1] #", "second = np.array(self.video[1:self.video.shape[0], :, :]) diferences = self.get_diference( second, first ) for image", "alpha[0] + diferences[image]* alpha[1] # Mirar ecuacion del cuaderno. return diferences def get_diference(self,", "superposition that you want to have in te current image. Example: alpha =", "(0.5, 0.5) is neutral change, were the last image will have the same", "import cv2 class Recurrent_Photo: ''' Recurrent Photo only for testing ''' def __init__(self,", "for testing ''' def __init__(self, iterations=100, resize=(1280, 720)): self.camera = cv2.VideoCapture(0) self.video =", "(self.camera.read()[1]/255), # FIXME: AHORA TRABAJAMOS CON LOS TRES CANALES resize ) cv2.imshow('Prueba', self.video[iteration,", "X = cv2.resize(X, dimensions) else: for image in X: image = cv2.resize(image, dimensions)", "sleep(0.05) non_movement = Recurrent_Photo(50) print('Prepare next movement...') sleep(2) movement = Recurrent_Photo(50) non_movement_recurrence =", "del 2018 # 31 Mayo 2018 import numpy as np import matplotlib.pyplot as", "image in range(len(diferences)): diferences[image] = diferences[image-1]* alpha[0] + diferences[image]* alpha[1] # Mirar ecuacion", "cv2.waitKey(1) self.camera.release() self.resize = resize def get_recurrence(self, alpha=(0.75555, 0.25555)): ''' Alpha are 2", "in X: image = cv2.resize(image, dimensions) return X def show_image(X): if len(X.shape) ==", "were the last image will have the same intensity of first image. '''", "= diferences[image-1]* alpha[0] + diferences[image]* alpha[1] # Mirar ecuacion del cuaderno. return diferences", "cv2.imshow('image', X) else: for image in X: cv2.imshow('X', image) cv2.waitKey(1) sleep(0.05) non_movement =", "TRABAJAMOS CON LOS TRES CANALES resize ) cv2.imshow('Prueba', self.video[iteration, :, :]) cv2.waitKey(1) self.camera.release()", "Recurrent_Photo: ''' Recurrent Photo only for testing ''' def __init__(self, iterations=100, resize=(1280, 720)):", "X: cv2.imshow('X', image) cv2.waitKey(1) sleep(0.05) non_movement = Recurrent_Photo(50) print('Prepare next movement...') sleep(2) movement", ":, :,]) second = np.array(self.video[1:self.video.shape[0], :, :]) diferences = self.get_diference( second, first )", "get_diference(self, A, B): ''' Get diference from two items ''' return np.abs(A -", "A, B): ''' Get diference from two items ''' return np.abs(A - B)", "75)): if len(X.shape) == 3: X = cv2.resize(X, dimensions) else: for image in", "image = cv2.resize(image, dimensions) return X def show_image(X): if len(X.shape) == 3: cv2.imshow('image',", "image in X: cv2.imshow('X', image) cv2.waitKey(1) sleep(0.05) non_movement = Recurrent_Photo(50) print('Prepare next movement...')", "have in te current image. Example: alpha = (0.5, 0.5) is neutral change,", "dimensions) else: for image in X: image = cv2.resize(image, dimensions) return X def", "= Recurrent_Photo(50) print('Prepare next movement...') sleep(2) movement = Recurrent_Photo(50) non_movement_recurrence = non_movement.get_recurrence() movement_recurrence", "first ) for image in range(len(diferences)): diferences[image] = diferences[image-1]* alpha[0] + diferences[image]* alpha[1]", "+ diferences[image]* alpha[1] # Mirar ecuacion del cuaderno. return diferences def get_diference(self, A,", "= cv2.resize(image, dimensions) return X def show_image(X): if len(X.shape) == 3: cv2.imshow('image', X)", "diferences def get_diference(self, A, B): ''' Get diference from two items ''' return", "two items ''' return np.abs(A - B) def resize_images(X, dimensions=(100, 75)): if len(X.shape)", "= resize def get_recurrence(self, alpha=(0.75555, 0.25555)): ''' Alpha are 2 float numbers represented", "resize ) cv2.imshow('Prueba', self.video[iteration, :, :]) cv2.waitKey(1) self.camera.release() self.resize = resize def get_recurrence(self,", "= np.array(self.video[0:self.video.shape[0]-1, :, :,]) second = np.array(self.video[1:self.video.shape[0], :, :]) diferences = self.get_diference( second,", "X: image = cv2.resize(image, dimensions) return X def show_image(X): if len(X.shape) == 3:" ]
[ "MechType class ContextFlags(BitString): _map = { 0: 'delegFlag', 1: 'mutualFlag', 2: 'replayFlag', 3:", "_map = { '1.3.6.1.4.1.311.2.2.10': 'NTLMSSP - Microsoft NTLM Security Support Provider', '1.2.840.48018.1.2.2' :", "0: 'delegFlag', 1: 'mutualFlag', 2: 'replayFlag', 3: 'sequenceFlag', 4: 'anonFlag', 5: 'confFlag', 6:", "[ ('negState', NegState, {'tag_type': TAG, 'tag': 0, 'optional': True}), ('supportedMech', MechType, {'tag_type': TAG,", "'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 4, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt", "disgrace of a protocol design. class KRB5Token: def __init__(self, data = None, tok_id", "= 2 class MechType(ObjectIdentifier): _map = { '1.3.6.1.4.1.311.2.2.10': 'NTLMSSP - Microsoft NTLM Security", "from_bytes(data): return KRB5Token.from_buffer(io.BytesIO(data)) @staticmethod def from_buffer(buff): t = KRB5Token() buff.read(1) length = -1", "'1.2.840.113554.1.2.2' : 'KRB5 - Kerberos 5', '1.2.840.113554.1.2.2.3': 'KRB5 - Kerberos 5 - User", "import enum import os import io TAG = 'explicit' # class UNIVERSAL =", "Any, Boolean import enum import os import io TAG = 'explicit' # class", "Mechanism', } class MechTypes(SequenceOf): _child_spec = MechType class ContextFlags(BitString): _map = { 0:", "class KRB5Token: def __init__(self, data = None, tok_id = b'\\x01\\x00'): self.tok_id = tok_id", "True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 3, 'optional': True}), ] class NegotiationToken(Choice): _alternatives", "('responseToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag':", "class NegTokenInit2(Sequence): #explicit = (APPLICATION, 0) _fields = [ ('mechTypes', MechTypes, {'tag_type': TAG,", "= data @staticmethod def from_bytes(data): return KRB5Token.from_buffer(io.BytesIO(data)) @staticmethod def from_buffer(buff): t = KRB5Token()", "class UNIVERSAL = 0 APPLICATION = 1 CONTEXT = 2 class MechType(ObjectIdentifier): _map", "[ ('hintName', GeneralString, {'explicit': 0, 'optional': True}), ('hintAddress', OctetString, {'explicit': 1, 'optional': True}),", "TAG = 'explicit' # class UNIVERSAL = 0 APPLICATION = 1 CONTEXT =", "signed = False) input('length: %s' % length) oid_asn1 = buff.read(11) t.tok_id = int.from_bytes(buff.read(2),", "import os import io TAG = 'explicit' # class UNIVERSAL = 0 APPLICATION", "length) oid_asn1 = buff.read(11) t.tok_id = int.from_bytes(buff.read(2), 'big', signed = False) t.data =", "'optional': True}), ('responseToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}), ('mechListMIC', OctetString, {'tag_type':", "len(self.data)) t += bytes.fromhex('06092a864886f712010202') #OID length + OID for kerberos t += self.tok_id", "2 tag = 0 _fields = [ ('NegotiationToken', NegotiationToken), ] ### I have", "] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.1 # EXTENDED IN: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472 class NegTokenInit2(Sequence): #explicit = (APPLICATION,", "4, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.2 class NegTokenResp(Sequence): #explicit = (APPLICATION, 1)", "is tandardized :( class GSSType(ObjectIdentifier): _map = { #'': 'SNMPv2-SMI::enterprises.311.2.2.30', '1.3.6.1.5.5.2': 'SPNEGO', }", "} # https://tools.ietf.org/html/rfc2743#page-81 # You may think this is ASN1. But it truth,", "7) // 8, 'big') t = (0x80 | len(lb)).to_bytes(1, 'big', signed = False)", "class NegTokenResp(Sequence): #explicit = (APPLICATION, 1) _fields = [ ('negState', NegState, {'tag_type': TAG,", "self.data = data @staticmethod def from_bytes(data): return KRB5Token.from_buffer(io.BytesIO(data)) @staticmethod def from_buffer(buff): t =", "+ 2 + len(self.data)) t += bytes.fromhex('06092a864886f712010202') #OID length + OID for kerberos", "idea where this is tandardized :( class GSSType(ObjectIdentifier): _map = { #'': 'SNMPv2-SMI::enterprises.311.2.2.30',", "= 2 tag = 0 _fields = [ ('NegotiationToken', NegotiationToken), ] ### I", "= 1 tag = 0 _fields = [ ('type', GSSType, {'optional': False}), ('value',", "= { 0: 'delegFlag', 1: 'mutualFlag', 2: 'replayFlag', 3: 'sequenceFlag', 4: 'anonFlag', 5:", "Sequence, SequenceOf, Enumerated, GeneralString, OctetString, BitString, Choice, Any, Boolean import enum import os", "NegTokenResp, {'explicit': (CONTEXT, 1) } ), ] class GSS_SPNEGO(Sequence): class_ = 2 tag", "= { 'SPNEGO': NegotiationToken, } # https://tools.ietf.org/html/rfc2743#page-81 # You may think this is", "'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.1 # EXTENDED IN: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472 class NegTokenInit2(Sequence): #explicit", ":( class GSSType(ObjectIdentifier): _map = { #'': 'SNMPv2-SMI::enterprises.311.2.2.30', '1.3.6.1.5.5.2': 'SPNEGO', } class GSSAPI(Sequence):", "= int.from_bytes(buff.read(x), 'big', signed = False) input('length: %s' % length) oid_asn1 = buff.read(11)", "OctetString, BitString, Choice, Any, Boolean import enum import os import io TAG =", "class MechType(ObjectIdentifier): _map = { '1.3.6.1.4.1.311.2.2.10': 'NTLMSSP - Microsoft NTLM Security Support Provider',", "Negotiation Security Mechanism', } class MechTypes(SequenceOf): _child_spec = MechType class ContextFlags(BitString): _map =", "input(t.tok_id ) return t def length_encode(self, x): if x <= 127: return x.to_bytes(1,", "('hintName', GeneralString, {'explicit': 0, 'optional': True}), ('hintAddress', OctetString, {'explicit': 1, 'optional': True}), ]", "ASN1. But it truth, it's not. # Below is a fucking disgrace of", "), ('negTokenResp', NegTokenResp, {'explicit': (CONTEXT, 1) } ), ] class GSS_SPNEGO(Sequence): class_ =", "[ ('type', GSSType, {'optional': False}), ('value', Any, {'optional': False}), ] _oid_pair = ('type',", "'tag': 4, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.2 class NegTokenResp(Sequence): #explicit = (APPLICATION,", "self.length_encode(11 + 2 + len(self.data)) t += bytes.fromhex('06092a864886f712010202') #OID length + OID for", "= b'\\x01\\x00'): self.tok_id = tok_id self.data = data @staticmethod def from_bytes(data): return KRB5Token.from_buffer(io.BytesIO(data))", "('negTokenResp', NegTokenResp, {'explicit': (CONTEXT, 1) } ), ] class GSS_SPNEGO(Sequence): class_ = 2", "data = None, tok_id = b'\\x01\\x00'): self.tok_id = tok_id self.data = data @staticmethod", "{'explicit': (CONTEXT, 0) } ), ('negTokenResp', NegTokenResp, {'explicit': (CONTEXT, 1) } ), ]", "= int.from_bytes(buff.read(2), 'big', signed = False) t.data = buff.read(length-13) input(t.tok_id ) return t", "t = (0x80 | len(lb)).to_bytes(1, 'big', signed = False) return t+lb def to_bytes(self):", "it's not. # Below is a fucking disgrace of a protocol design. class", "import io TAG = 'explicit' # class UNIVERSAL = 0 APPLICATION = 1", "TAG, 'tag': 1, 'optional': True}), ('mechToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}),", "tok_id self.data = data @staticmethod def from_bytes(data): return KRB5Token.from_buffer(io.BytesIO(data)) @staticmethod def from_buffer(buff): t", "KRB5Token.from_buffer(io.BytesIO(data)) @staticmethod def from_buffer(buff): t = KRB5Token() buff.read(1) length = -1 x =", "'optional': True}), ('negHints', NegHints, {'tag_type': TAG, 'tag': 3, 'optional': True}), ('mechListMIC', OctetString, {'tag_type':", "os import io TAG = 'explicit' # class UNIVERSAL = 0 APPLICATION =", "OctetString, {'tag_type': TAG, 'tag': 3, 'optional': True}), ] class NegotiationToken(Choice): _alternatives = [", "def __init__(self, data = None, tok_id = b'\\x01\\x00'): self.tok_id = tok_id self.data =", "2, 'optional': True}), ('negHints', NegHints, {'tag_type': TAG, 'tag': 3, 'optional': True}), ('mechListMIC', OctetString,", "if x <= 127: return x.to_bytes(1, 'big', signed = False) else: lb =", "x.to_bytes((x.bit_length() + 7) // 8, 'big') t = (0x80 | len(lb)).to_bytes(1, 'big', signed", "len(lb)).to_bytes(1, 'big', signed = False) return t+lb def to_bytes(self): t = b'\\x60' #", "('reqFlags', ContextFlags, {'tag_type': TAG, 'tag': 1, 'optional': True}), ('mechToken', OctetString, {'tag_type': TAG, 'tag':", "_map = { #'': 'SNMPv2-SMI::enterprises.311.2.2.30', '1.3.6.1.5.5.2': 'SPNEGO', } class GSSAPI(Sequence): class_ = 1", "https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472 class NegTokenInit2(Sequence): #explicit = (APPLICATION, 0) _fields = [ ('mechTypes', MechTypes, {'tag_type':", "{ 0: 'accept-completed', 1: 'accept-incomplete', 2: 'reject', 3: 'request-mic', } class NegHints(Sequence): _fields", "5', '1.2.840.113554.1.2.2.3': 'KRB5 - Kerberos 5 - User to User', '1.3.6.1.4.1.311.2.2.30': 'NEGOEX -", "{'tag_type': TAG, 'tag': 3, 'optional': True}), ] class NegotiationToken(Choice): _alternatives = [ ('negTokenInit',", "input(x) if x <= 127: length = x else: x &= ~0x80 input(x)", "True}), ('responseToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG,", "Kerberos 5 - User to User', '1.3.6.1.4.1.311.2.2.30': 'NEGOEX - SPNEGO Extended Negotiation Security", "5 - User to User', '1.3.6.1.4.1.311.2.2.30': 'NEGOEX - SPNEGO Extended Negotiation Security Mechanism',", "0, 'optional': True}), ('supportedMech', MechType, {'tag_type': TAG, 'tag': 1, 'optional': True}), ('responseToken', OctetString,", "[ ('NegotiationToken', NegotiationToken), ] ### I have 0 idea where this is tandardized", "0) _fields = [ ('mechTypes', MechTypes, {'tag_type': TAG, 'tag': 0}), ('reqFlags', ContextFlags, {'tag_type':", "_fields = [ ('hintName', GeneralString, {'explicit': 0, 'optional': True}), ('hintAddress', OctetString, {'explicit': 1,", "None, tok_id = b'\\x01\\x00'): self.tok_id = tok_id self.data = data @staticmethod def from_bytes(data):", "} class GSSAPI(Sequence): class_ = 1 tag = 0 _fields = [ ('type',", "class NegHints(Sequence): _fields = [ ('hintName', GeneralString, {'explicit': 0, 'optional': True}), ('hintAddress', OctetString,", "class NegState(Enumerated): _map = { 0: 'accept-completed', 1: 'accept-incomplete', 2: 'reject', 3: 'request-mic',", "tag = 0 _fields = [ ('type', GSSType, {'optional': False}), ('value', Any, {'optional':", "'replayFlag', 3: 'sequenceFlag', 4: 'anonFlag', 5: 'confFlag', 6: 'integFlag', } class NegState(Enumerated): _map", "x = int.from_bytes(buff.read(1), 'big', signed = False) input(x) if x <= 127: length", "'optional': True}), ('mechToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}), ('negHints', NegHints, {'tag_type':", "'optional': True}), ] class NegotiationToken(Choice): _alternatives = [ ('negTokenInit', NegTokenInit2, {'explicit': (CONTEXT, 0)", "NegTokenInit2(Sequence): #explicit = (APPLICATION, 0) _fields = [ ('mechTypes', MechTypes, {'tag_type': TAG, 'tag':", "NegotiationToken, } # https://tools.ietf.org/html/rfc2743#page-81 # You may think this is ASN1. But it", "{ 0: 'delegFlag', 1: 'mutualFlag', 2: 'replayFlag', 3: 'sequenceFlag', 4: 'anonFlag', 5: 'confFlag',", "length + OID for kerberos t += self.tok_id t += self.data return t", "- Kerberos 5', '1.2.840.113554.1.2.2.3': 'KRB5 - Kerberos 5 - User to User', '1.3.6.1.4.1.311.2.2.30':", "bytes.fromhex('06092a864886f712010202') #OID length + OID for kerberos t += self.tok_id t += self.data", "= [ ('type', GSSType, {'optional': False}), ('value', Any, {'optional': False}), ] _oid_pair =", "enum import os import io TAG = 'explicit' # class UNIVERSAL = 0", "), ] class GSS_SPNEGO(Sequence): class_ = 2 tag = 0 _fields = [", "OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 3,", "GeneralString, OctetString, BitString, Choice, Any, Boolean import enum import os import io TAG", "- Kerberos 5 - User to User', '1.3.6.1.4.1.311.2.2.30': 'NEGOEX - SPNEGO Extended Negotiation", "= [ ('NegotiationToken', NegotiationToken), ] ### I have 0 idea where this is", "protocol design. class KRB5Token: def __init__(self, data = None, tok_id = b'\\x01\\x00'): self.tok_id", "True}), ('mechToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}), ('negHints', NegHints, {'tag_type': TAG,", "Extended Negotiation Security Mechanism', } class MechTypes(SequenceOf): _child_spec = MechType class ContextFlags(BitString): _map", "{'explicit': 1, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.1 # EXTENDED IN: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472 class", "length = int.from_bytes(buff.read(x), 'big', signed = False) input('length: %s' % length) oid_asn1 =", "Author: # <NAME> (@skelsec) # # https://www.rfc-editor.org/rfc/rfc4178.txt from asn1crypto.core import ObjectIdentifier, Sequence, SequenceOf,", "def from_buffer(buff): t = KRB5Token() buff.read(1) length = -1 x = int.from_bytes(buff.read(1), 'big',", "of a protocol design. class KRB5Token: def __init__(self, data = None, tok_id =", "length_encode(self, x): if x <= 127: return x.to_bytes(1, 'big', signed = False) else:", "False) else: lb = x.to_bytes((x.bit_length() + 7) // 8, 'big') t = (0x80", "# <NAME> (@skelsec) # # https://www.rfc-editor.org/rfc/rfc4178.txt from asn1crypto.core import ObjectIdentifier, Sequence, SequenceOf, Enumerated,", "127: return x.to_bytes(1, 'big', signed = False) else: lb = x.to_bytes((x.bit_length() + 7)", "'1.3.6.1.4.1.311.2.2.30': 'NEGOEX - SPNEGO Extended Negotiation Security Mechanism', } class MechTypes(SequenceOf): _child_spec =", ": 'MS KRB5 - Microsoft Kerberos 5', '1.2.840.113554.1.2.2' : 'KRB5 - Kerberos 5',", "('negState', NegState, {'tag_type': TAG, 'tag': 0, 'optional': True}), ('supportedMech', MechType, {'tag_type': TAG, 'tag':", "3: 'request-mic', } class NegHints(Sequence): _fields = [ ('hintName', GeneralString, {'explicit': 0, 'optional':", "~0x80 input(x) length = int.from_bytes(buff.read(x), 'big', signed = False) input('length: %s' % length)", "'optional': True}), ('hintAddress', OctetString, {'explicit': 1, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.1 #", "('hintAddress', OctetString, {'explicit': 1, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.1 # EXTENDED IN:", "= int.from_bytes(buff.read(1), 'big', signed = False) input(x) if x <= 127: length =", "(@skelsec) # # https://www.rfc-editor.org/rfc/rfc4178.txt from asn1crypto.core import ObjectIdentifier, Sequence, SequenceOf, Enumerated, GeneralString, OctetString,", "OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}), ('negHints', NegHints, {'tag_type': TAG, 'tag': 3,", "Microsoft Kerberos 5', '1.2.840.113554.1.2.2' : 'KRB5 - Kerberos 5', '1.2.840.113554.1.2.2.3': 'KRB5 - Kerberos", "buff.read(length-13) input(t.tok_id ) return t def length_encode(self, x): if x <= 127: return", "3, 'optional': True}), ] class NegotiationToken(Choice): _alternatives = [ ('negTokenInit', NegTokenInit2, {'explicit': (CONTEXT,", "GeneralString, {'explicit': 0, 'optional': True}), ('hintAddress', OctetString, {'explicit': 1, 'optional': True}), ] #", "False) return t+lb def to_bytes(self): t = b'\\x60' # t += self.length_encode(11 +", "{'tag_type': TAG, 'tag': 2, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 3, 'optional':", "Below is a fucking disgrace of a protocol design. class KRB5Token: def __init__(self,", "is ASN1. But it truth, it's not. # Below is a fucking disgrace", "# t += self.length_encode(11 + 2 + len(self.data)) t += bytes.fromhex('06092a864886f712010202') #OID length", "def to_bytes(self): t = b'\\x60' # t += self.length_encode(11 + 2 + len(self.data))", "// 8, 'big') t = (0x80 | len(lb)).to_bytes(1, 'big', signed = False) return", "8, 'big') t = (0x80 | len(lb)).to_bytes(1, 'big', signed = False) return t+lb", "'request-mic', } class NegHints(Sequence): _fields = [ ('hintName', GeneralString, {'explicit': 0, 'optional': True}),", "6: 'integFlag', } class NegState(Enumerated): _map = { 0: 'accept-completed', 1: 'accept-incomplete', 2:", "= MechType class ContextFlags(BitString): _map = { 0: 'delegFlag', 1: 'mutualFlag', 2: 'replayFlag',", "User to User', '1.3.6.1.4.1.311.2.2.30': 'NEGOEX - SPNEGO Extended Negotiation Security Mechanism', } class", "Kerberos 5', '1.2.840.113554.1.2.2.3': 'KRB5 - Kerberos 5 - User to User', '1.3.6.1.4.1.311.2.2.30': 'NEGOEX", "1, 'optional': True}), ('mechToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}), ('negHints', NegHints,", "{ '1.3.6.1.4.1.311.2.2.10': 'NTLMSSP - Microsoft NTLM Security Support Provider', '1.2.840.48018.1.2.2' : 'MS KRB5", "#!/usr/bin/env python3 # # Author: # <NAME> (@skelsec) # # https://www.rfc-editor.org/rfc/rfc4178.txt from asn1crypto.core", "But it truth, it's not. # Below is a fucking disgrace of a", "= False) input(x) if x <= 127: length = x else: x &=", "False}), ] _oid_pair = ('type', 'value') _oid_specs = { 'SPNEGO': NegotiationToken, } #", "True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.2 class NegTokenResp(Sequence): #explicit = (APPLICATION, 1) _fields =", "import ObjectIdentifier, Sequence, SequenceOf, Enumerated, GeneralString, OctetString, BitString, Choice, Any, Boolean import enum", "(APPLICATION, 0) _fields = [ ('mechTypes', MechTypes, {'tag_type': TAG, 'tag': 0}), ('reqFlags', ContextFlags,", "{'tag_type': TAG, 'tag': 0}), ('reqFlags', ContextFlags, {'tag_type': TAG, 'tag': 1, 'optional': True}), ('mechToken',", "Any, {'optional': False}), ] _oid_pair = ('type', 'value') _oid_specs = { 'SPNEGO': NegotiationToken,", "input('length: %s' % length) oid_asn1 = buff.read(11) t.tok_id = int.from_bytes(buff.read(2), 'big', signed =", "2 + len(self.data)) t += bytes.fromhex('06092a864886f712010202') #OID length + OID for kerberos t", "'tag': 3, 'optional': True}), ] class NegotiationToken(Choice): _alternatives = [ ('negTokenInit', NegTokenInit2, {'explicit':", "'MS KRB5 - Microsoft Kerberos 5', '1.2.840.113554.1.2.2' : 'KRB5 - Kerberos 5', '1.2.840.113554.1.2.2.3':", "('value', Any, {'optional': False}), ] _oid_pair = ('type', 'value') _oid_specs = { 'SPNEGO':", "OctetString, {'tag_type': TAG, 'tag': 4, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.2 class NegTokenResp(Sequence):", "'value') _oid_specs = { 'SPNEGO': NegotiationToken, } # https://tools.ietf.org/html/rfc2743#page-81 # You may think", "(APPLICATION, 1) _fields = [ ('negState', NegState, {'tag_type': TAG, 'tag': 0, 'optional': True}),", "True}), ] class NegotiationToken(Choice): _alternatives = [ ('negTokenInit', NegTokenInit2, {'explicit': (CONTEXT, 0) }", "design. class KRB5Token: def __init__(self, data = None, tok_id = b'\\x01\\x00'): self.tok_id =", "APPLICATION = 1 CONTEXT = 2 class MechType(ObjectIdentifier): _map = { '1.3.6.1.4.1.311.2.2.10': 'NTLMSSP", "t += bytes.fromhex('06092a864886f712010202') #OID length + OID for kerberos t += self.tok_id t", "{'tag_type': TAG, 'tag': 0, 'optional': True}), ('supportedMech', MechType, {'tag_type': TAG, 'tag': 1, 'optional':", "else: x &= ~0x80 input(x) length = int.from_bytes(buff.read(x), 'big', signed = False) input('length:", "GSS_SPNEGO(Sequence): class_ = 2 tag = 0 _fields = [ ('NegotiationToken', NegotiationToken), ]", "# Author: # <NAME> (@skelsec) # # https://www.rfc-editor.org/rfc/rfc4178.txt from asn1crypto.core import ObjectIdentifier, Sequence,", "'big', signed = False) else: lb = x.to_bytes((x.bit_length() + 7) // 8, 'big')", "'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 3, 'optional': True}), ] class NegotiationToken(Choice):", "NegTokenResp(Sequence): #explicit = (APPLICATION, 1) _fields = [ ('negState', NegState, {'tag_type': TAG, 'tag':", "a protocol design. class KRB5Token: def __init__(self, data = None, tok_id = b'\\x01\\x00'):", "signed = False) input(x) if x <= 127: length = x else: x", "# Below is a fucking disgrace of a protocol design. class KRB5Token: def", "#explicit = (APPLICATION, 1) _fields = [ ('negState', NegState, {'tag_type': TAG, 'tag': 0,", "{'tag_type': TAG, 'tag': 1, 'optional': True}), ('mechToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional':", "Support Provider', '1.2.840.48018.1.2.2' : 'MS KRB5 - Microsoft Kerberos 5', '1.2.840.113554.1.2.2' : 'KRB5", "%s' % length) oid_asn1 = buff.read(11) t.tok_id = int.from_bytes(buff.read(2), 'big', signed = False)", "0: 'accept-completed', 1: 'accept-incomplete', 2: 'reject', 3: 'request-mic', } class NegHints(Sequence): _fields =", "Security Support Provider', '1.2.840.48018.1.2.2' : 'MS KRB5 - Microsoft Kerberos 5', '1.2.840.113554.1.2.2' :", "class ContextFlags(BitString): _map = { 0: 'delegFlag', 1: 'mutualFlag', 2: 'replayFlag', 3: 'sequenceFlag',", "x <= 127: return x.to_bytes(1, 'big', signed = False) else: lb = x.to_bytes((x.bit_length()", "'tag': 0, 'optional': True}), ('supportedMech', MechType, {'tag_type': TAG, 'tag': 1, 'optional': True}), ('responseToken',", "MechType, {'tag_type': TAG, 'tag': 1, 'optional': True}), ('responseToken', OctetString, {'tag_type': TAG, 'tag': 2,", "length = x else: x &= ~0x80 input(x) length = int.from_bytes(buff.read(x), 'big', signed", "'tag': 0}), ('reqFlags', ContextFlags, {'tag_type': TAG, 'tag': 1, 'optional': True}), ('mechToken', OctetString, {'tag_type':", "{ 'SPNEGO': NegotiationToken, } # https://tools.ietf.org/html/rfc2743#page-81 # You may think this is ASN1.", "'sequenceFlag', 4: 'anonFlag', 5: 'confFlag', 6: 'integFlag', } class NegState(Enumerated): _map = {", "NegotiationToken), ] ### I have 0 idea where this is tandardized :( class", "signed = False) return t+lb def to_bytes(self): t = b'\\x60' # t +=", "MechTypes, {'tag_type': TAG, 'tag': 0}), ('reqFlags', ContextFlags, {'tag_type': TAG, 'tag': 1, 'optional': True}),", "1) _fields = [ ('negState', NegState, {'tag_type': TAG, 'tag': 0, 'optional': True}), ('supportedMech',", "TAG, 'tag': 0, 'optional': True}), ('supportedMech', MechType, {'tag_type': TAG, 'tag': 1, 'optional': True}),", "% length) oid_asn1 = buff.read(11) t.tok_id = int.from_bytes(buff.read(2), 'big', signed = False) t.data", "= 0 APPLICATION = 1 CONTEXT = 2 class MechType(ObjectIdentifier): _map = {", "NegTokenInit2, {'explicit': (CONTEXT, 0) } ), ('negTokenResp', NegTokenResp, {'explicit': (CONTEXT, 1) } ),", "KRB5Token: def __init__(self, data = None, tok_id = b'\\x01\\x00'): self.tok_id = tok_id self.data", "1 tag = 0 _fields = [ ('type', GSSType, {'optional': False}), ('value', Any,", "+ len(self.data)) t += bytes.fromhex('06092a864886f712010202') #OID length + OID for kerberos t +=", "+= self.length_encode(11 + 2 + len(self.data)) t += bytes.fromhex('06092a864886f712010202') #OID length + OID", "('negTokenInit', NegTokenInit2, {'explicit': (CONTEXT, 0) } ), ('negTokenResp', NegTokenResp, {'explicit': (CONTEXT, 1) }", "a fucking disgrace of a protocol design. class KRB5Token: def __init__(self, data =", "SequenceOf, Enumerated, GeneralString, OctetString, BitString, Choice, Any, Boolean import enum import os import", "= (APPLICATION, 1) _fields = [ ('negState', NegState, {'tag_type': TAG, 'tag': 0, 'optional':", "= KRB5Token() buff.read(1) length = -1 x = int.from_bytes(buff.read(1), 'big', signed = False)", "_oid_pair = ('type', 'value') _oid_specs = { 'SPNEGO': NegotiationToken, } # https://tools.ietf.org/html/rfc2743#page-81 #", "ContextFlags, {'tag_type': TAG, 'tag': 1, 'optional': True}), ('mechToken', OctetString, {'tag_type': TAG, 'tag': 2,", "class_ = 2 tag = 0 _fields = [ ('NegotiationToken', NegotiationToken), ] ###", "it truth, it's not. # Below is a fucking disgrace of a protocol", "'accept-completed', 1: 'accept-incomplete', 2: 'reject', 3: 'request-mic', } class NegHints(Sequence): _fields = [", "{'tag_type': TAG, 'tag': 1, 'optional': True}), ('responseToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional':", "truth, it's not. # Below is a fucking disgrace of a protocol design.", "where this is tandardized :( class GSSType(ObjectIdentifier): _map = { #'': 'SNMPv2-SMI::enterprises.311.2.2.30', '1.3.6.1.5.5.2':", "False}), ('value', Any, {'optional': False}), ] _oid_pair = ('type', 'value') _oid_specs = {", "'tag': 1, 'optional': True}), ('mechToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}), ('negHints',", "IN: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472 class NegTokenInit2(Sequence): #explicit = (APPLICATION, 0) _fields = [ ('mechTypes', MechTypes,", "1, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.1 # EXTENDED IN: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472 class NegTokenInit2(Sequence):", "2: 'reject', 3: 'request-mic', } class NegHints(Sequence): _fields = [ ('hintName', GeneralString, {'explicit':", "this is ASN1. But it truth, it's not. # Below is a fucking", "4: 'anonFlag', 5: 'confFlag', 6: 'integFlag', } class NegState(Enumerated): _map = { 0:", "b'\\x01\\x00'): self.tok_id = tok_id self.data = data @staticmethod def from_bytes(data): return KRB5Token.from_buffer(io.BytesIO(data)) @staticmethod", "<NAME> (@skelsec) # # https://www.rfc-editor.org/rfc/rfc4178.txt from asn1crypto.core import ObjectIdentifier, Sequence, SequenceOf, Enumerated, GeneralString,", "('mechToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}), ('negHints', NegHints, {'tag_type': TAG, 'tag':", "'confFlag', 6: 'integFlag', } class NegState(Enumerated): _map = { 0: 'accept-completed', 1: 'accept-incomplete',", "_oid_specs = { 'SPNEGO': NegotiationToken, } # https://tools.ietf.org/html/rfc2743#page-81 # You may think this", "is a fucking disgrace of a protocol design. class KRB5Token: def __init__(self, data", "False) t.data = buff.read(length-13) input(t.tok_id ) return t def length_encode(self, x): if x", "NegHints, {'tag_type': TAG, 'tag': 3, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 4,", "'tag': 3, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 4, 'optional': True}), ]", "class GSSAPI(Sequence): class_ = 1 tag = 0 _fields = [ ('type', GSSType,", "1) } ), ] class GSS_SPNEGO(Sequence): class_ = 2 tag = 0 _fields", "= 0 _fields = [ ('type', GSSType, {'optional': False}), ('value', Any, {'optional': False}),", "signed = False) else: lb = x.to_bytes((x.bit_length() + 7) // 8, 'big') t", "= False) return t+lb def to_bytes(self): t = b'\\x60' # t += self.length_encode(11", "= 0 _fields = [ ('NegotiationToken', NegotiationToken), ] ### I have 0 idea", "] ### I have 0 idea where this is tandardized :( class GSSType(ObjectIdentifier):", "5', '1.2.840.113554.1.2.2' : 'KRB5 - Kerberos 5', '1.2.840.113554.1.2.2.3': 'KRB5 - Kerberos 5 -", "NegotiationToken(Choice): _alternatives = [ ('negTokenInit', NegTokenInit2, {'explicit': (CONTEXT, 0) } ), ('negTokenResp', NegTokenResp,", "t += self.length_encode(11 + 2 + len(self.data)) t += bytes.fromhex('06092a864886f712010202') #OID length +", "length = -1 x = int.from_bytes(buff.read(1), 'big', signed = False) input(x) if x", "'tag': 2, 'optional': True}), ('negHints', NegHints, {'tag_type': TAG, 'tag': 3, 'optional': True}), ('mechListMIC',", "True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.1 # EXTENDED IN: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472 class NegTokenInit2(Sequence): #explicit =", "Kerberos 5', '1.2.840.113554.1.2.2' : 'KRB5 - Kerberos 5', '1.2.840.113554.1.2.2.3': 'KRB5 - Kerberos 5", "'big', signed = False) input(x) if x <= 127: length = x else:", "#OID length + OID for kerberos t += self.tok_id t += self.data return", "# # Author: # <NAME> (@skelsec) # # https://www.rfc-editor.org/rfc/rfc4178.txt from asn1crypto.core import ObjectIdentifier,", "'big', signed = False) return t+lb def to_bytes(self): t = b'\\x60' # t", "} ), ('negTokenResp', NegTokenResp, {'explicit': (CONTEXT, 1) } ), ] class GSS_SPNEGO(Sequence): class_", "= 1 CONTEXT = 2 class MechType(ObjectIdentifier): _map = { '1.3.6.1.4.1.311.2.2.10': 'NTLMSSP -", "4.2.1 # EXTENDED IN: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472 class NegTokenInit2(Sequence): #explicit = (APPLICATION, 0) _fields =", "0}), ('reqFlags', ContextFlags, {'tag_type': TAG, 'tag': 1, 'optional': True}), ('mechToken', OctetString, {'tag_type': TAG,", "<= 127: length = x else: x &= ~0x80 input(x) length = int.from_bytes(buff.read(x),", "= False) t.data = buff.read(length-13) input(t.tok_id ) return t def length_encode(self, x): if", "this is tandardized :( class GSSType(ObjectIdentifier): _map = { #'': 'SNMPv2-SMI::enterprises.311.2.2.30', '1.3.6.1.5.5.2': 'SPNEGO',", "def from_bytes(data): return KRB5Token.from_buffer(io.BytesIO(data)) @staticmethod def from_buffer(buff): t = KRB5Token() buff.read(1) length =", "<= 127: return x.to_bytes(1, 'big', signed = False) else: lb = x.to_bytes((x.bit_length() +", "] class GSS_SPNEGO(Sequence): class_ = 2 tag = 0 _fields = [ ('NegotiationToken',", "https://tools.ietf.org/html/rfc2743#page-81 # You may think this is ASN1. But it truth, it's not.", "'SNMPv2-SMI::enterprises.311.2.2.30', '1.3.6.1.5.5.2': 'SPNEGO', } class GSSAPI(Sequence): class_ = 1 tag = 0 _fields", "_fields = [ ('negState', NegState, {'tag_type': TAG, 'tag': 0, 'optional': True}), ('supportedMech', MechType,", "_map = { 0: 'delegFlag', 1: 'mutualFlag', 2: 'replayFlag', 3: 'sequenceFlag', 4: 'anonFlag',", "to User', '1.3.6.1.4.1.311.2.2.30': 'NEGOEX - SPNEGO Extended Negotiation Security Mechanism', } class MechTypes(SequenceOf):", "{'optional': False}), ] _oid_pair = ('type', 'value') _oid_specs = { 'SPNEGO': NegotiationToken, }", "} ), ] class GSS_SPNEGO(Sequence): class_ = 2 tag = 0 _fields =", "__init__(self, data = None, tok_id = b'\\x01\\x00'): self.tok_id = tok_id self.data = data", "https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.2 class NegTokenResp(Sequence): #explicit = (APPLICATION, 1) _fields = [ ('negState', NegState,", "SPNEGO Extended Negotiation Security Mechanism', } class MechTypes(SequenceOf): _child_spec = MechType class ContextFlags(BitString):", "True}), ('negHints', NegHints, {'tag_type': TAG, 'tag': 3, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG,", "_fields = [ ('NegotiationToken', NegotiationToken), ] ### I have 0 idea where this", "3: 'sequenceFlag', 4: 'anonFlag', 5: 'confFlag', 6: 'integFlag', } class NegState(Enumerated): _map =", "input(x) length = int.from_bytes(buff.read(x), 'big', signed = False) input('length: %s' % length) oid_asn1", "'big', signed = False) input('length: %s' % length) oid_asn1 = buff.read(11) t.tok_id =", "- Microsoft Kerberos 5', '1.2.840.113554.1.2.2' : 'KRB5 - Kerberos 5', '1.2.840.113554.1.2.2.3': 'KRB5 -", "BitString, Choice, Any, Boolean import enum import os import io TAG = 'explicit'", "self.tok_id = tok_id self.data = data @staticmethod def from_bytes(data): return KRB5Token.from_buffer(io.BytesIO(data)) @staticmethod def", "True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 4, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.2", "Microsoft NTLM Security Support Provider', '1.2.840.48018.1.2.2' : 'MS KRB5 - Microsoft Kerberos 5',", "may think this is ASN1. But it truth, it's not. # Below is", "x else: x &= ~0x80 input(x) length = int.from_bytes(buff.read(x), 'big', signed = False)", "4.2.2 class NegTokenResp(Sequence): #explicit = (APPLICATION, 1) _fields = [ ('negState', NegState, {'tag_type':", "= [ ('negState', NegState, {'tag_type': TAG, 'tag': 0, 'optional': True}), ('supportedMech', MechType, {'tag_type':", "{'explicit': 0, 'optional': True}), ('hintAddress', OctetString, {'explicit': 1, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt", "ContextFlags(BitString): _map = { 0: 'delegFlag', 1: 'mutualFlag', 2: 'replayFlag', 3: 'sequenceFlag', 4:", "@staticmethod def from_bytes(data): return KRB5Token.from_buffer(io.BytesIO(data)) @staticmethod def from_buffer(buff): t = KRB5Token() buff.read(1) length", "CONTEXT = 2 class MechType(ObjectIdentifier): _map = { '1.3.6.1.4.1.311.2.2.10': 'NTLMSSP - Microsoft NTLM", "class GSS_SPNEGO(Sequence): class_ = 2 tag = 0 _fields = [ ('NegotiationToken', NegotiationToken),", "#'': 'SNMPv2-SMI::enterprises.311.2.2.30', '1.3.6.1.5.5.2': 'SPNEGO', } class GSSAPI(Sequence): class_ = 1 tag = 0", "UNIVERSAL = 0 APPLICATION = 1 CONTEXT = 2 class MechType(ObjectIdentifier): _map =", "1: 'accept-incomplete', 2: 'reject', 3: 'request-mic', } class NegHints(Sequence): _fields = [ ('hintName',", "think this is ASN1. But it truth, it's not. # Below is a", "3, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 4, 'optional': True}), ] #", "buff.read(11) t.tok_id = int.from_bytes(buff.read(2), 'big', signed = False) t.data = buff.read(length-13) input(t.tok_id )", "def length_encode(self, x): if x <= 127: return x.to_bytes(1, 'big', signed = False)", "tag = 0 _fields = [ ('NegotiationToken', NegotiationToken), ] ### I have 0", "from_buffer(buff): t = KRB5Token() buff.read(1) length = -1 x = int.from_bytes(buff.read(1), 'big', signed", "# https://www.rfc-editor.org/rfc/rfc4178.txt from asn1crypto.core import ObjectIdentifier, Sequence, SequenceOf, Enumerated, GeneralString, OctetString, BitString, Choice,", "{'optional': False}), ('value', Any, {'optional': False}), ] _oid_pair = ('type', 'value') _oid_specs =", "'NEGOEX - SPNEGO Extended Negotiation Security Mechanism', } class MechTypes(SequenceOf): _child_spec = MechType", "return t def length_encode(self, x): if x <= 127: return x.to_bytes(1, 'big', signed", "} class NegHints(Sequence): _fields = [ ('hintName', GeneralString, {'explicit': 0, 'optional': True}), ('hintAddress',", "+= bytes.fromhex('06092a864886f712010202') #OID length + OID for kerberos t += self.tok_id t +=", "= (0x80 | len(lb)).to_bytes(1, 'big', signed = False) return t+lb def to_bytes(self): t", "{'tag_type': TAG, 'tag': 2, 'optional': True}), ('negHints', NegHints, {'tag_type': TAG, 'tag': 3, 'optional':", "= [ ('hintName', GeneralString, {'explicit': 0, 'optional': True}), ('hintAddress', OctetString, {'explicit': 1, 'optional':", "0 idea where this is tandardized :( class GSSType(ObjectIdentifier): _map = { #'':", "'delegFlag', 1: 'mutualFlag', 2: 'replayFlag', 3: 'sequenceFlag', 4: 'anonFlag', 5: 'confFlag', 6: 'integFlag',", "0 _fields = [ ('NegotiationToken', NegotiationToken), ] ### I have 0 idea where", "t.data = buff.read(length-13) input(t.tok_id ) return t def length_encode(self, x): if x <=", "data @staticmethod def from_bytes(data): return KRB5Token.from_buffer(io.BytesIO(data)) @staticmethod def from_buffer(buff): t = KRB5Token() buff.read(1)", "# class UNIVERSAL = 0 APPLICATION = 1 CONTEXT = 2 class MechType(ObjectIdentifier):", "1, 'optional': True}), ('responseToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}), ('mechListMIC', OctetString,", "(CONTEXT, 0) } ), ('negTokenResp', NegTokenResp, {'explicit': (CONTEXT, 1) } ), ] class", "= b'\\x60' # t += self.length_encode(11 + 2 + len(self.data)) t += bytes.fromhex('06092a864886f712010202')", "_fields = [ ('mechTypes', MechTypes, {'tag_type': TAG, 'tag': 0}), ('reqFlags', ContextFlags, {'tag_type': TAG,", "lb = x.to_bytes((x.bit_length() + 7) // 8, 'big') t = (0x80 | len(lb)).to_bytes(1,", "https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.1 # EXTENDED IN: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472 class NegTokenInit2(Sequence): #explicit = (APPLICATION, 0) _fields", "t = b'\\x60' # t += self.length_encode(11 + 2 + len(self.data)) t +=", "+ 7) // 8, 'big') t = (0x80 | len(lb)).to_bytes(1, 'big', signed =", "if x <= 127: length = x else: x &= ~0x80 input(x) length", "5: 'confFlag', 6: 'integFlag', } class NegState(Enumerated): _map = { 0: 'accept-completed', 1:", "'tag': 2, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 3, 'optional': True}), ]", "int.from_bytes(buff.read(2), 'big', signed = False) t.data = buff.read(length-13) input(t.tok_id ) return t def", "[ ('negTokenInit', NegTokenInit2, {'explicit': (CONTEXT, 0) } ), ('negTokenResp', NegTokenResp, {'explicit': (CONTEXT, 1)", "{'tag_type': TAG, 'tag': 4, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.2 class NegTokenResp(Sequence): #explicit", "'NTLMSSP - Microsoft NTLM Security Support Provider', '1.2.840.48018.1.2.2' : 'MS KRB5 - Microsoft", "(0x80 | len(lb)).to_bytes(1, 'big', signed = False) return t+lb def to_bytes(self): t =", "KRB5Token() buff.read(1) length = -1 x = int.from_bytes(buff.read(1), 'big', signed = False) input(x)", "'1.3.6.1.4.1.311.2.2.10': 'NTLMSSP - Microsoft NTLM Security Support Provider', '1.2.840.48018.1.2.2' : 'MS KRB5 -", "Choice, Any, Boolean import enum import os import io TAG = 'explicit' #", "# You may think this is ASN1. But it truth, it's not. #", "0 _fields = [ ('type', GSSType, {'optional': False}), ('value', Any, {'optional': False}), ]", "TAG, 'tag': 4, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.2 class NegTokenResp(Sequence): #explicit =", "= ('type', 'value') _oid_specs = { 'SPNEGO': NegotiationToken, } # https://tools.ietf.org/html/rfc2743#page-81 # You", "t = KRB5Token() buff.read(1) length = -1 x = int.from_bytes(buff.read(1), 'big', signed =", "TAG, 'tag': 1, 'optional': True}), ('responseToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}),", "buff.read(1) length = -1 x = int.from_bytes(buff.read(1), 'big', signed = False) input(x) if", "x &= ~0x80 input(x) length = int.from_bytes(buff.read(x), 'big', signed = False) input('length: %s'", "_alternatives = [ ('negTokenInit', NegTokenInit2, {'explicit': (CONTEXT, 0) } ), ('negTokenResp', NegTokenResp, {'explicit':", "NegState(Enumerated): _map = { 0: 'accept-completed', 1: 'accept-incomplete', 2: 'reject', 3: 'request-mic', }", "io TAG = 'explicit' # class UNIVERSAL = 0 APPLICATION = 1 CONTEXT", "signed = False) t.data = buff.read(length-13) input(t.tok_id ) return t def length_encode(self, x):", "t def length_encode(self, x): if x <= 127: return x.to_bytes(1, 'big', signed =", "fucking disgrace of a protocol design. class KRB5Token: def __init__(self, data = None,", "= buff.read(length-13) input(t.tok_id ) return t def length_encode(self, x): if x <= 127:", "- User to User', '1.3.6.1.4.1.311.2.2.30': 'NEGOEX - SPNEGO Extended Negotiation Security Mechanism', }", "'integFlag', } class NegState(Enumerated): _map = { 0: 'accept-completed', 1: 'accept-incomplete', 2: 'reject',", "tandardized :( class GSSType(ObjectIdentifier): _map = { #'': 'SNMPv2-SMI::enterprises.311.2.2.30', '1.3.6.1.5.5.2': 'SPNEGO', } class", "'1.2.840.48018.1.2.2' : 'MS KRB5 - Microsoft Kerberos 5', '1.2.840.113554.1.2.2' : 'KRB5 - Kerberos", "# https://tools.ietf.org/html/rfc2743#page-81 # You may think this is ASN1. But it truth, it's", "TAG, 'tag': 3, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 4, 'optional': True}),", "_fields = [ ('type', GSSType, {'optional': False}), ('value', Any, {'optional': False}), ] _oid_pair", "('mechTypes', MechTypes, {'tag_type': TAG, 'tag': 0}), ('reqFlags', ContextFlags, {'tag_type': TAG, 'tag': 1, 'optional':", "'optional': True}), ('supportedMech', MechType, {'tag_type': TAG, 'tag': 1, 'optional': True}), ('responseToken', OctetString, {'tag_type':", "= tok_id self.data = data @staticmethod def from_bytes(data): return KRB5Token.from_buffer(io.BytesIO(data)) @staticmethod def from_buffer(buff):", "False) input('length: %s' % length) oid_asn1 = buff.read(11) t.tok_id = int.from_bytes(buff.read(2), 'big', signed", "= [ ('negTokenInit', NegTokenInit2, {'explicit': (CONTEXT, 0) } ), ('negTokenResp', NegTokenResp, {'explicit': (CONTEXT,", "'mutualFlag', 2: 'replayFlag', 3: 'sequenceFlag', 4: 'anonFlag', 5: 'confFlag', 6: 'integFlag', } class", "= False) input('length: %s' % length) oid_asn1 = buff.read(11) t.tok_id = int.from_bytes(buff.read(2), 'big',", "'KRB5 - Kerberos 5 - User to User', '1.3.6.1.4.1.311.2.2.30': 'NEGOEX - SPNEGO Extended", "class MechTypes(SequenceOf): _child_spec = MechType class ContextFlags(BitString): _map = { 0: 'delegFlag', 1:", "= None, tok_id = b'\\x01\\x00'): self.tok_id = tok_id self.data = data @staticmethod def", "= buff.read(11) t.tok_id = int.from_bytes(buff.read(2), 'big', signed = False) t.data = buff.read(length-13) input(t.tok_id", "[ ('mechTypes', MechTypes, {'tag_type': TAG, 'tag': 0}), ('reqFlags', ContextFlags, {'tag_type': TAG, 'tag': 1,", "127: length = x else: x &= ~0x80 input(x) length = int.from_bytes(buff.read(x), 'big',", "KRB5 - Microsoft Kerberos 5', '1.2.840.113554.1.2.2' : 'KRB5 - Kerberos 5', '1.2.840.113554.1.2.2.3': 'KRB5", "_child_spec = MechType class ContextFlags(BitString): _map = { 0: 'delegFlag', 1: 'mutualFlag', 2:", "True}), ('hintAddress', OctetString, {'explicit': 1, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.1 # EXTENDED", "class_ = 1 tag = 0 _fields = [ ('type', GSSType, {'optional': False}),", "= { 0: 'accept-completed', 1: 'accept-incomplete', 2: 'reject', 3: 'request-mic', } class NegHints(Sequence):", "TAG, 'tag': 2, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 3, 'optional': True}),", "'reject', 3: 'request-mic', } class NegHints(Sequence): _fields = [ ('hintName', GeneralString, {'explicit': 0,", "ObjectIdentifier, Sequence, SequenceOf, Enumerated, GeneralString, OctetString, BitString, Choice, Any, Boolean import enum import", "not. # Below is a fucking disgrace of a protocol design. class KRB5Token:", "b'\\x60' # t += self.length_encode(11 + 2 + len(self.data)) t += bytes.fromhex('06092a864886f712010202') #OID", "0 APPLICATION = 1 CONTEXT = 2 class MechType(ObjectIdentifier): _map = { '1.3.6.1.4.1.311.2.2.10':", "Enumerated, GeneralString, OctetString, BitString, Choice, Any, Boolean import enum import os import io", "('NegotiationToken', NegotiationToken), ] ### I have 0 idea where this is tandardized :(", "} class NegState(Enumerated): _map = { 0: 'accept-completed', 1: 'accept-incomplete', 2: 'reject', 3:", "{'explicit': (CONTEXT, 1) } ), ] class GSS_SPNEGO(Sequence): class_ = 2 tag =", "python3 # # Author: # <NAME> (@skelsec) # # https://www.rfc-editor.org/rfc/rfc4178.txt from asn1crypto.core import", "= { '1.3.6.1.4.1.311.2.2.10': 'NTLMSSP - Microsoft NTLM Security Support Provider', '1.2.840.48018.1.2.2' : 'MS", "You may think this is ASN1. But it truth, it's not. # Below", "False) input(x) if x <= 127: length = x else: x &= ~0x80", "else: lb = x.to_bytes((x.bit_length() + 7) // 8, 'big') t = (0x80 |", "MechTypes(SequenceOf): _child_spec = MechType class ContextFlags(BitString): _map = { 0: 'delegFlag', 1: 'mutualFlag',", "('supportedMech', MechType, {'tag_type': TAG, 'tag': 1, 'optional': True}), ('responseToken', OctetString, {'tag_type': TAG, 'tag':", "- SPNEGO Extended Negotiation Security Mechanism', } class MechTypes(SequenceOf): _child_spec = MechType class", "| len(lb)).to_bytes(1, 'big', signed = False) return t+lb def to_bytes(self): t = b'\\x60'", "int.from_bytes(buff.read(x), 'big', signed = False) input('length: %s' % length) oid_asn1 = buff.read(11) t.tok_id", ": 'KRB5 - Kerberos 5', '1.2.840.113554.1.2.2.3': 'KRB5 - Kerberos 5 - User to", "https://www.rfc-editor.org/rfc/rfc4178.txt from asn1crypto.core import ObjectIdentifier, Sequence, SequenceOf, Enumerated, GeneralString, OctetString, BitString, Choice, Any,", "True}), ('supportedMech', MechType, {'tag_type': TAG, 'tag': 1, 'optional': True}), ('responseToken', OctetString, {'tag_type': TAG,", "'SPNEGO': NegotiationToken, } # https://tools.ietf.org/html/rfc2743#page-81 # You may think this is ASN1. But", "class NegotiationToken(Choice): _alternatives = [ ('negTokenInit', NegTokenInit2, {'explicit': (CONTEXT, 0) } ), ('negTokenResp',", "= (APPLICATION, 0) _fields = [ ('mechTypes', MechTypes, {'tag_type': TAG, 'tag': 0}), ('reqFlags',", "NegHints(Sequence): _fields = [ ('hintName', GeneralString, {'explicit': 0, 'optional': True}), ('hintAddress', OctetString, {'explicit':", "GSSType(ObjectIdentifier): _map = { #'': 'SNMPv2-SMI::enterprises.311.2.2.30', '1.3.6.1.5.5.2': 'SPNEGO', } class GSSAPI(Sequence): class_ =", "return KRB5Token.from_buffer(io.BytesIO(data)) @staticmethod def from_buffer(buff): t = KRB5Token() buff.read(1) length = -1 x", "-1 x = int.from_bytes(buff.read(1), 'big', signed = False) input(x) if x <= 127:", "2 class MechType(ObjectIdentifier): _map = { '1.3.6.1.4.1.311.2.2.10': 'NTLMSSP - Microsoft NTLM Security Support", "TAG, 'tag': 3, 'optional': True}), ] class NegotiationToken(Choice): _alternatives = [ ('negTokenInit', NegTokenInit2,", "I have 0 idea where this is tandardized :( class GSSType(ObjectIdentifier): _map =", "asn1crypto.core import ObjectIdentifier, Sequence, SequenceOf, Enumerated, GeneralString, OctetString, BitString, Choice, Any, Boolean import", "] class NegotiationToken(Choice): _alternatives = [ ('negTokenInit', NegTokenInit2, {'explicit': (CONTEXT, 0) } ),", "'accept-incomplete', 2: 'reject', 3: 'request-mic', } class NegHints(Sequence): _fields = [ ('hintName', GeneralString,", "1 CONTEXT = 2 class MechType(ObjectIdentifier): _map = { '1.3.6.1.4.1.311.2.2.10': 'NTLMSSP - Microsoft", "# https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.1 # EXTENDED IN: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472 class NegTokenInit2(Sequence): #explicit = (APPLICATION, 0)", "#explicit = (APPLICATION, 0) _fields = [ ('mechTypes', MechTypes, {'tag_type': TAG, 'tag': 0}),", "x): if x <= 127: return x.to_bytes(1, 'big', signed = False) else: lb", "'big') t = (0x80 | len(lb)).to_bytes(1, 'big', signed = False) return t+lb def", "MechType(ObjectIdentifier): _map = { '1.3.6.1.4.1.311.2.2.10': 'NTLMSSP - Microsoft NTLM Security Support Provider', '1.2.840.48018.1.2.2'", "] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.2 class NegTokenResp(Sequence): #explicit = (APPLICATION, 1) _fields = [", "int.from_bytes(buff.read(1), 'big', signed = False) input(x) if x <= 127: length = x", "('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 4, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.2 class", "class GSSType(ObjectIdentifier): _map = { #'': 'SNMPv2-SMI::enterprises.311.2.2.30', '1.3.6.1.5.5.2': 'SPNEGO', } class GSSAPI(Sequence): class_", "# # https://www.rfc-editor.org/rfc/rfc4178.txt from asn1crypto.core import ObjectIdentifier, Sequence, SequenceOf, Enumerated, GeneralString, OctetString, BitString,", "_map = { 0: 'accept-completed', 1: 'accept-incomplete', 2: 'reject', 3: 'request-mic', } class", "Provider', '1.2.840.48018.1.2.2' : 'MS KRB5 - Microsoft Kerberos 5', '1.2.840.113554.1.2.2' : 'KRB5 -", "return x.to_bytes(1, 'big', signed = False) else: lb = x.to_bytes((x.bit_length() + 7) //", "x <= 127: length = x else: x &= ~0x80 input(x) length =", "('type', GSSType, {'optional': False}), ('value', Any, {'optional': False}), ] _oid_pair = ('type', 'value')", "0, 'optional': True}), ('hintAddress', OctetString, {'explicit': 1, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.1", "from asn1crypto.core import ObjectIdentifier, Sequence, SequenceOf, Enumerated, GeneralString, OctetString, BitString, Choice, Any, Boolean", "User', '1.3.6.1.4.1.311.2.2.30': 'NEGOEX - SPNEGO Extended Negotiation Security Mechanism', } class MechTypes(SequenceOf): _child_spec", "1: 'mutualFlag', 2: 'replayFlag', 3: 'sequenceFlag', 4: 'anonFlag', 5: 'confFlag', 6: 'integFlag', }", "= x.to_bytes((x.bit_length() + 7) // 8, 'big') t = (0x80 | len(lb)).to_bytes(1, 'big',", "have 0 idea where this is tandardized :( class GSSType(ObjectIdentifier): _map = {", "'anonFlag', 5: 'confFlag', 6: 'integFlag', } class NegState(Enumerated): _map = { 0: 'accept-completed',", "@staticmethod def from_buffer(buff): t = KRB5Token() buff.read(1) length = -1 x = int.from_bytes(buff.read(1),", "x.to_bytes(1, 'big', signed = False) else: lb = x.to_bytes((x.bit_length() + 7) // 8,", "TAG, 'tag': 0}), ('reqFlags', ContextFlags, {'tag_type': TAG, 'tag': 1, 'optional': True}), ('mechToken', OctetString,", "return t+lb def to_bytes(self): t = b'\\x60' # t += self.length_encode(11 + 2", "= x else: x &= ~0x80 input(x) length = int.from_bytes(buff.read(x), 'big', signed =", "0) } ), ('negTokenResp', NegTokenResp, {'explicit': (CONTEXT, 1) } ), ] class GSS_SPNEGO(Sequence):", "Security Mechanism', } class MechTypes(SequenceOf): _child_spec = MechType class ContextFlags(BitString): _map = {", "# https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.2 class NegTokenResp(Sequence): #explicit = (APPLICATION, 1) _fields = [ ('negState',", "= 'explicit' # class UNIVERSAL = 0 APPLICATION = 1 CONTEXT = 2", "'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.2 class NegTokenResp(Sequence): #explicit = (APPLICATION, 1) _fields", "tok_id = b'\\x01\\x00'): self.tok_id = tok_id self.data = data @staticmethod def from_bytes(data): return", ") return t def length_encode(self, x): if x <= 127: return x.to_bytes(1, 'big',", "OctetString, {'explicit': 1, 'optional': True}), ] # https://www.rfc-editor.org/rfc/rfc4178.txt 4.2.1 # EXTENDED IN: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472", "oid_asn1 = buff.read(11) t.tok_id = int.from_bytes(buff.read(2), 'big', signed = False) t.data = buff.read(length-13)", "] _oid_pair = ('type', 'value') _oid_specs = { 'SPNEGO': NegotiationToken, } # https://tools.ietf.org/html/rfc2743#page-81", "t+lb def to_bytes(self): t = b'\\x60' # t += self.length_encode(11 + 2 +", "'KRB5 - Kerberos 5', '1.2.840.113554.1.2.2.3': 'KRB5 - Kerberos 5 - User to User',", "NegState, {'tag_type': TAG, 'tag': 0, 'optional': True}), ('supportedMech', MechType, {'tag_type': TAG, 'tag': 1,", "'explicit' # class UNIVERSAL = 0 APPLICATION = 1 CONTEXT = 2 class", "'1.3.6.1.5.5.2': 'SPNEGO', } class GSSAPI(Sequence): class_ = 1 tag = 0 _fields =", "'big', signed = False) t.data = buff.read(length-13) input(t.tok_id ) return t def length_encode(self,", "### I have 0 idea where this is tandardized :( class GSSType(ObjectIdentifier): _map", "2, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 3, 'optional': True}), ] class", "NTLM Security Support Provider', '1.2.840.48018.1.2.2' : 'MS KRB5 - Microsoft Kerberos 5', '1.2.840.113554.1.2.2'", "'tag': 1, 'optional': True}), ('responseToken', OctetString, {'tag_type': TAG, 'tag': 2, 'optional': True}), ('mechListMIC',", "{'tag_type': TAG, 'tag': 3, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 4, 'optional':", "- Microsoft NTLM Security Support Provider', '1.2.840.48018.1.2.2' : 'MS KRB5 - Microsoft Kerberos", "2: 'replayFlag', 3: 'sequenceFlag', 4: 'anonFlag', 5: 'confFlag', 6: 'integFlag', } class NegState(Enumerated):", "'1.2.840.113554.1.2.2.3': 'KRB5 - Kerberos 5 - User to User', '1.3.6.1.4.1.311.2.2.30': 'NEGOEX - SPNEGO", "&= ~0x80 input(x) length = int.from_bytes(buff.read(x), 'big', signed = False) input('length: %s' %", "GSSType, {'optional': False}), ('value', Any, {'optional': False}), ] _oid_pair = ('type', 'value') _oid_specs", "TAG, 'tag': 2, 'optional': True}), ('negHints', NegHints, {'tag_type': TAG, 'tag': 3, 'optional': True}),", "('negHints', NegHints, {'tag_type': TAG, 'tag': 3, 'optional': True}), ('mechListMIC', OctetString, {'tag_type': TAG, 'tag':", "= { #'': 'SNMPv2-SMI::enterprises.311.2.2.30', '1.3.6.1.5.5.2': 'SPNEGO', } class GSSAPI(Sequence): class_ = 1 tag", "= -1 x = int.from_bytes(buff.read(1), 'big', signed = False) input(x) if x <=", "t.tok_id = int.from_bytes(buff.read(2), 'big', signed = False) t.data = buff.read(length-13) input(t.tok_id ) return", "to_bytes(self): t = b'\\x60' # t += self.length_encode(11 + 2 + len(self.data)) t", "'SPNEGO', } class GSSAPI(Sequence): class_ = 1 tag = 0 _fields = [", "# EXTENDED IN: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472 class NegTokenInit2(Sequence): #explicit = (APPLICATION, 0) _fields = [", "{ #'': 'SNMPv2-SMI::enterprises.311.2.2.30', '1.3.6.1.5.5.2': 'SPNEGO', } class GSSAPI(Sequence): class_ = 1 tag =", "EXTENDED IN: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472 class NegTokenInit2(Sequence): #explicit = (APPLICATION, 0) _fields = [ ('mechTypes',", "= False) else: lb = x.to_bytes((x.bit_length() + 7) // 8, 'big') t =", "('type', 'value') _oid_specs = { 'SPNEGO': NegotiationToken, } # https://tools.ietf.org/html/rfc2743#page-81 # You may", "(CONTEXT, 1) } ), ] class GSS_SPNEGO(Sequence): class_ = 2 tag = 0", "} class MechTypes(SequenceOf): _child_spec = MechType class ContextFlags(BitString): _map = { 0: 'delegFlag',", "Boolean import enum import os import io TAG = 'explicit' # class UNIVERSAL", "('mechListMIC', OctetString, {'tag_type': TAG, 'tag': 3, 'optional': True}), ] class NegotiationToken(Choice): _alternatives =", "= [ ('mechTypes', MechTypes, {'tag_type': TAG, 'tag': 0}), ('reqFlags', ContextFlags, {'tag_type': TAG, 'tag':", "GSSAPI(Sequence): class_ = 1 tag = 0 _fields = [ ('type', GSSType, {'optional':" ]
[ "def build_and_push_image(): settings = get_settings(os.environ) sts_client = get_sts_client(settings) ecr_clients = get_ecr_clients(settings) docker_client =", "tag in settings['tags']: for repo in repos: image.tag( repository=repo['uri'], tag=tag ) def push_image(docker_client,", "region_name=region )) return clients def get_sts_client(settings): return boto3.client('sts', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'] ) def exit_with_error(message,", "login_to_registries(docker_client, repos): for repo in repos: login = repo['login'] docker_client.login( login['username'], login['password'], registry=login['registry']", "went wrong:', message.format(*args), file=sys.stderr, flush=True) sys.exit(1) def get_aws_account_id(sts_client): return sts_client.get_caller_identity().get('Account') def get_regions(env): regions", "message.format(*args), file=sys.stderr, flush=True) sys.exit(1) def get_aws_account_id(sts_client): return sts_client.get_caller_identity().get('Account') def get_regions(env): regions = env.get('PLUGIN_REGION')", "env.get('DRONE_REPO_LINK'), 'tags': get_tags(env) } def get_ecr_login(ecr_client, registry_id): response = ecr_client.get_authorization_token(registryIds=[registry_id]) registry = response['authorizationData'][0]['proxyEndpoint']", "} ) return image def tag_image(image, settings, repos): for tag in settings['tags']: for", "repo in repos: docker_client.images.push( repository=repo['uri'], tag=tag ) def build_and_push_image(): settings = get_settings(os.environ) sts_client", "login_to_registries(docker_client, repos) print('Logged in. Building image...', flush=True) try: image = build_image(docker_client, settings) except", "get_docker_client() print('Finding AWS account id...') aws_account_id = get_aws_account_id(sts_client) print('AWS account id is {0}.'.format(aws_account_id))", "build_date, 'CI_VCS_URL': settings['repo_link'], 'CI_VCS_REF': settings['commit'] }, labels={ 'org.label-schema.schema-version': '1.0', 'org.label-schema.build-date': build_date, 'org.label-schema.vcs-url': settings['repo_link'],", "= response['authorizationData'][0]['proxyEndpoint'] token = response['authorizationData'][0]['authorizationToken'] username, password = base64.b64decode(token).decode().split(':') return { 'username': username,", "}) return repos def login_to_registries(docker_client, repos): for repo in repos: login = repo['login']", "image...', flush=True) tag_image(image, settings, repos) print('Tagged. Pushing image tags to registries...', flush=True) push_image(docker_client,", "build_tag = ':'.join((settings['repo'], settings['tags'][0])) build_date = datetime.now(timezone.utc).astimezone().isoformat() image, *_ = docker_client.images.build( path=\"./\", tag=build_tag,", "tag) print('Tagging image...', flush=True) tag_image(image, settings, repos) print('Tagged. Pushing image tags to registries...',", "settings['commit'] } ) return image def tag_image(image, settings, repos): for tag in settings['tags']:", "base64 from datetime import datetime, timezone def get_docker_client(): return docker.from_env() def get_ecr_clients(settings): clients", "line in e.build_log: if 'stream' in line: print(line['stream'].strip()) raise print('Build finished.') print('Tags:') for", "env.get('PLUGIN_ACCESS_KEY_ID'), 'secret_access_key': env.get('PLUGIN_SECRET_ACCESS_KEY'), 'regions': get_regions(env), 'repo': get_repo(env), 'dockerfile': get_dockerfile(env), 'commit': env.get('DRONE_COMMIT'), 'repo_link': env.get('DRONE_REPO_LINK'),", "'org.label-schema.vcs-ref': settings['commit'] } ) return image def tag_image(image, settings, repos): for tag in", "tag_image(image, settings, repos): for tag in settings['tags']: for repo in repos: image.tag( repository=repo['uri'],", "datetime, timezone def get_docker_client(): return docker.from_env() def get_ecr_clients(settings): clients = [] for region", "settings, repos): for tag in settings['tags']: for repo in repos: image.tag( repository=repo['uri'], tag=tag", "repos) print('Logged in. Building image...', flush=True) try: image = build_image(docker_client, settings) except docker.errors.BuildError", "in to registries...', flush=True) login_to_registries(docker_client, repos) print('Logged in. Building image...', flush=True) try: image", "in settings['tags']: print('- ', tag) print('Tagging image...', flush=True) tag_image(image, settings, repos) print('Tagged. Pushing", "sts_client.get_caller_identity().get('Account') def get_regions(env): regions = env.get('PLUGIN_REGION') if not regions: return None return regions.split(',')", "repos): for repo in repos: login = repo['login'] docker_client.login( login['username'], login['password'], registry=login['registry'] )", "*args): print('Something went wrong:', message.format(*args), file=sys.stderr, flush=True) sys.exit(1) def get_aws_account_id(sts_client): return sts_client.get_caller_identity().get('Account') def", "for repo in repos: image.tag( repository=repo['uri'], tag=tag ) def push_image(docker_client, settings, repos): for", "'./Dockerfile') def get_tags(env): user_tags = env.get('PLUGIN_TAGS') tags = [tag for tag in user_tags.split(',')]", "'CI_VCS_URL': settings['repo_link'], 'CI_VCS_REF': settings['commit'] }, labels={ 'org.label-schema.schema-version': '1.0', 'org.label-schema.build-date': build_date, 'org.label-schema.vcs-url': settings['repo_link'], 'org.label-schema.vcs-ref':", "print('Build finished.') print('Tags:') for tag in settings['tags']: print('- ', tag) print('Tagging image...', flush=True)", "base64.b64decode(token).decode().split(':') return { 'username': username, 'password': password, 'registry': registry } def get_repos(settings, ecr_clients,", "in. Building image...', flush=True) try: image = build_image(docker_client, settings) except docker.errors.BuildError as e:", "settings['tags']: print('- ', tag) print('Tagging image...', flush=True) tag_image(image, settings, repos) print('Tagged. Pushing image", "user_tags.split(',')] return tags def get_settings(env): return { 'access_key_id': env.get('PLUGIN_ACCESS_KEY_ID'), 'secret_access_key': env.get('PLUGIN_SECRET_ACCESS_KEY'), 'regions': get_regions(env),", "'repo_link': env.get('DRONE_REPO_LINK'), 'tags': get_tags(env) } def get_ecr_login(ecr_client, registry_id): response = ecr_client.get_authorization_token(registryIds=[registry_id]) registry =", "in user_tags.split(',')] return tags def get_settings(env): return { 'access_key_id': env.get('PLUGIN_ACCESS_KEY_ID'), 'secret_access_key': env.get('PLUGIN_SECRET_ACCESS_KEY'), 'regions':", "get_sts_client(settings): return boto3.client('sts', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'] ) def exit_with_error(message, *args): print('Something went wrong:', message.format(*args),", "return clients def get_sts_client(settings): return boto3.client('sts', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'] ) def exit_with_error(message, *args): print('Something", "env.get('DRONE_REPO_NAME')) def get_dockerfile(env): return env.get('PLUGIN_DOCKERFILE', './Dockerfile') def get_tags(env): user_tags = env.get('PLUGIN_TAGS') tags =", "repo['uri']) print('Logging in to registries...', flush=True) login_to_registries(docker_client, repos) print('Logged in. Building image...', flush=True)", "finished.') print('Tags:') for tag in settings['tags']: print('- ', tag) print('Tagging image...', flush=True) tag_image(image,", "for tag in settings['tags']: print('- ', tag) print('Tagging image...', flush=True) tag_image(image, settings, repos)", "get_docker_client(): return docker.from_env() def get_ecr_clients(settings): clients = [] for region in settings['regions']: clients.append(boto3.client('ecr',", "regions = env.get('PLUGIN_REGION') if not regions: return None return regions.split(',') def get_repo(env): return", "def get_dockerfile(env): return env.get('PLUGIN_DOCKERFILE', './Dockerfile') def get_tags(env): user_tags = env.get('PLUGIN_TAGS') tags = [tag", "response = client.describe_repositories( registryId=aws_account_id, repositoryNames=[settings['repo']] ) repo = response['repositories'][0] repos.append({ 'registry_id': repo['registryId'], 'name':", "print('Repo name is', settings['repo'], flush=True) print('Regions:') for region in settings['regions']: print('- ', region)", ") def exit_with_error(message, *args): print('Something went wrong:', message.format(*args), file=sys.stderr, flush=True) sys.exit(1) def get_aws_account_id(sts_client):", "def login_to_registries(docker_client, repos): for repo in repos: login = repo['login'] docker_client.login( login['username'], login['password'],", "'org.label-schema.build-date': build_date, 'org.label-schema.vcs-url': settings['repo_link'], 'org.label-schema.vcs-ref': settings['commit'] } ) return image def tag_image(image, settings,", "def get_tags(env): user_tags = env.get('PLUGIN_TAGS') tags = [tag for tag in user_tags.split(',')] return", "flush=True) repos = get_repos(settings, ecr_clients, aws_account_id) print('Fetched repos info.') print('Repos:') for repo in", "name is', settings['repo'], flush=True) print('Regions:') for region in settings['regions']: print('- ', region) print('Fetching", "docker.errors.BuildError as e: for line in e.build_log: if 'stream' in line: print(line['stream'].strip()) raise", "line: print(line['stream'].strip()) raise print('Build finished.') print('Tags:') for tag in settings['tags']: print('- ', tag)", "return boto3.client('sts', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'] ) def exit_with_error(message, *args): print('Something went wrong:', message.format(*args), file=sys.stderr,", "ecr_clients = get_ecr_clients(settings) docker_client = get_docker_client() print('Finding AWS account id...') aws_account_id = get_aws_account_id(sts_client)", "def get_regions(env): regions = env.get('PLUGIN_REGION') if not regions: return None return regions.split(',') def", "e.build_log: if 'stream' in line: print(line['stream'].strip()) raise print('Build finished.') print('Tags:') for tag in", "print('Regions:') for region in settings['regions']: print('- ', region) print('Fetching repos info from ECR", "clients.append(boto3.client('ecr', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'], region_name=region )) return clients def get_sts_client(settings): return boto3.client('sts', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key']", "'repo': get_repo(env), 'dockerfile': get_dockerfile(env), 'commit': env.get('DRONE_COMMIT'), 'repo_link': env.get('DRONE_REPO_LINK'), 'tags': get_tags(env) } def get_ecr_login(ecr_client,", "repos = [] for client in ecr_clients: response = client.describe_repositories( registryId=aws_account_id, repositoryNames=[settings['repo']] )", "token = response['authorizationData'][0]['authorizationToken'] username, password = base64.b64decode(token).decode().split(':') return { 'username': username, 'password': password,", "info from ECR across regions...', flush=True) repos = get_repos(settings, ecr_clients, aws_account_id) print('Fetched repos", "registries...', flush=True) login_to_registries(docker_client, repos) print('Logged in. Building image...', flush=True) try: image = build_image(docker_client,", "settings['tags']: for repo in repos: docker_client.images.push( repository=repo['uri'], tag=tag ) def build_and_push_image(): settings =", "image tags to registries...', flush=True) push_image(docker_client, settings, repos) print('Pushed. All done.') if __name__", "for tag in settings['tags']: for repo in repos: docker_client.images.push( repository=repo['uri'], tag=tag ) def", "repos): for tag in settings['tags']: for repo in repos: docker_client.images.push( repository=repo['uri'], tag=tag )", "repos) print('Tagged. Pushing image tags to registries...', flush=True) push_image(docker_client, settings, repos) print('Pushed. All", "def push_image(docker_client, settings, repos): for tag in settings['tags']: for repo in repos: docker_client.images.push(", "print('Finding AWS account id...') aws_account_id = get_aws_account_id(sts_client) print('AWS account id is {0}.'.format(aws_account_id)) print('Repo", "'1.0', 'org.label-schema.build-date': build_date, 'org.label-schema.vcs-url': settings['repo_link'], 'org.label-schema.vcs-ref': settings['commit'] } ) return image def tag_image(image,", "dockerfile=settings['dockerfile'], rm=True, forcerm=True, buildargs={ 'CI_BUILD_DATE': build_date, 'CI_VCS_URL': settings['repo_link'], 'CI_VCS_REF': settings['commit'] }, labels={ 'org.label-schema.schema-version':", "settings = get_settings(os.environ) sts_client = get_sts_client(settings) ecr_clients = get_ecr_clients(settings) docker_client = get_docker_client() print('Finding", ") def push_image(docker_client, settings, repos): for tag in settings['tags']: for repo in repos:", "'secret_access_key': env.get('PLUGIN_SECRET_ACCESS_KEY'), 'regions': get_regions(env), 'repo': get_repo(env), 'dockerfile': get_dockerfile(env), 'commit': env.get('DRONE_COMMIT'), 'repo_link': env.get('DRONE_REPO_LINK'), 'tags':", "= ':'.join((settings['repo'], settings['tags'][0])) build_date = datetime.now(timezone.utc).astimezone().isoformat() image, *_ = docker_client.images.build( path=\"./\", tag=build_tag, dockerfile=settings['dockerfile'],", "wrong:', message.format(*args), file=sys.stderr, flush=True) sys.exit(1) def get_aws_account_id(sts_client): return sts_client.get_caller_identity().get('Account') def get_regions(env): regions =", "settings['regions']: print('- ', region) print('Fetching repos info from ECR across regions...', flush=True) repos", ") def build_image(docker_client, settings): build_tag = ':'.join((settings['repo'], settings['tags'][0])) build_date = datetime.now(timezone.utc).astimezone().isoformat() image, *_", "'dockerfile': get_dockerfile(env), 'commit': env.get('DRONE_COMMIT'), 'repo_link': env.get('DRONE_REPO_LINK'), 'tags': get_tags(env) } def get_ecr_login(ecr_client, registry_id): response", "repo['registryId']) }) return repos def login_to_registries(docker_client, repos): for repo in repos: login =", "aws_secret_access_key=settings['secret_access_key'], region_name=region )) return clients def get_sts_client(settings): return boto3.client('sts', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'] ) def", "ecr_clients, aws_account_id): repos = [] for client in ecr_clients: response = client.describe_repositories( registryId=aws_account_id,", "from datetime import datetime, timezone def get_docker_client(): return docker.from_env() def get_ecr_clients(settings): clients =", "print('- ', repo['uri']) print('Logging in to registries...', flush=True) login_to_registries(docker_client, repos) print('Logged in. Building", "None return regions.split(',') def get_repo(env): return env.get('PLUGIN_REPO', env.get('DRONE_REPO_NAME')) def get_dockerfile(env): return env.get('PLUGIN_DOCKERFILE', './Dockerfile')", "tags = [tag for tag in user_tags.split(',')] return tags def get_settings(env): return {", "in settings['regions']: print('- ', region) print('Fetching repos info from ECR across regions...', flush=True)", "= get_repos(settings, ecr_clients, aws_account_id) print('Fetched repos info.') print('Repos:') for repo in repos: print('-", "'commit': env.get('DRONE_COMMIT'), 'repo_link': env.get('DRONE_REPO_LINK'), 'tags': get_tags(env) } def get_ecr_login(ecr_client, registry_id): response = ecr_client.get_authorization_token(registryIds=[registry_id])", "get_repos(settings, ecr_clients, aws_account_id) print('Fetched repos info.') print('Repos:') for repo in repos: print('- ',", "username, password = base64.b64decode(token).decode().split(':') return { 'username': username, 'password': password, 'registry': registry }", "aws_account_id = get_aws_account_id(sts_client) print('AWS account id is {0}.'.format(aws_account_id)) print('Repo name is', settings['repo'], flush=True)", "print('Fetching repos info from ECR across regions...', flush=True) repos = get_repos(settings, ecr_clients, aws_account_id)", "= build_image(docker_client, settings) except docker.errors.BuildError as e: for line in e.build_log: if 'stream'", "repo = response['repositories'][0] repos.append({ 'registry_id': repo['registryId'], 'name': repo['repositoryName'], 'uri': repo['repositoryUri'], 'login': get_ecr_login(client, repo['registryId'])", "repos: print('- ', repo['uri']) print('Logging in to registries...', flush=True) login_to_registries(docker_client, repos) print('Logged in.", "def get_ecr_clients(settings): clients = [] for region in settings['regions']: clients.append(boto3.client('ecr', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'], region_name=region", "flush=True) try: image = build_image(docker_client, settings) except docker.errors.BuildError as e: for line in", "flush=True) tag_image(image, settings, repos) print('Tagged. Pushing image tags to registries...', flush=True) push_image(docker_client, settings,", "env.get('DRONE_COMMIT'), 'repo_link': env.get('DRONE_REPO_LINK'), 'tags': get_tags(env) } def get_ecr_login(ecr_client, registry_id): response = ecr_client.get_authorization_token(registryIds=[registry_id]) registry", "= [] for client in ecr_clients: response = client.describe_repositories( registryId=aws_account_id, repositoryNames=[settings['repo']] ) repo", "def tag_image(image, settings, repos): for tag in settings['tags']: for repo in repos: image.tag(", "settings['repo'], flush=True) print('Regions:') for region in settings['regions']: print('- ', region) print('Fetching repos info", "push_image(docker_client, settings, repos): for tag in settings['tags']: for repo in repos: docker_client.images.push( repository=repo['uri'],", "repo in repos: login = repo['login'] docker_client.login( login['username'], login['password'], registry=login['registry'] ) def build_image(docker_client,", "datetime.now(timezone.utc).astimezone().isoformat() image, *_ = docker_client.images.build( path=\"./\", tag=build_tag, dockerfile=settings['dockerfile'], rm=True, forcerm=True, buildargs={ 'CI_BUILD_DATE': build_date,", "image = build_image(docker_client, settings) except docker.errors.BuildError as e: for line in e.build_log: if", "return docker.from_env() def get_ecr_clients(settings): clients = [] for region in settings['regions']: clients.append(boto3.client('ecr', aws_access_key_id=settings['access_key_id'],", "file=sys.stderr, flush=True) sys.exit(1) def get_aws_account_id(sts_client): return sts_client.get_caller_identity().get('Account') def get_regions(env): regions = env.get('PLUGIN_REGION') if", "password = base64.b64decode(token).decode().split(':') return { 'username': username, 'password': password, 'registry': registry } def", "repository=repo['uri'], tag=tag ) def push_image(docker_client, settings, repos): for tag in settings['tags']: for repo", "labels={ 'org.label-schema.schema-version': '1.0', 'org.label-schema.build-date': build_date, 'org.label-schema.vcs-url': settings['repo_link'], 'org.label-schema.vcs-ref': settings['commit'] } ) return image", "repos: docker_client.images.push( repository=repo['uri'], tag=tag ) def build_and_push_image(): settings = get_settings(os.environ) sts_client = get_sts_client(settings)", "= [tag for tag in user_tags.split(',')] return tags def get_settings(env): return { 'access_key_id':", "repo['registryId'], 'name': repo['repositoryName'], 'uri': repo['repositoryUri'], 'login': get_ecr_login(client, repo['registryId']) }) return repos def login_to_registries(docker_client,", "account id is {0}.'.format(aws_account_id)) print('Repo name is', settings['repo'], flush=True) print('Regions:') for region in", "in repos: docker_client.images.push( repository=repo['uri'], tag=tag ) def build_and_push_image(): settings = get_settings(os.environ) sts_client =", "{ 'username': username, 'password': password, 'registry': registry } def get_repos(settings, ecr_clients, aws_account_id): repos", "try: image = build_image(docker_client, settings) except docker.errors.BuildError as e: for line in e.build_log:", "client in ecr_clients: response = client.describe_repositories( registryId=aws_account_id, repositoryNames=[settings['repo']] ) repo = response['repositories'][0] repos.append({", "user_tags = env.get('PLUGIN_TAGS') tags = [tag for tag in user_tags.split(',')] return tags def", "= datetime.now(timezone.utc).astimezone().isoformat() image, *_ = docker_client.images.build( path=\"./\", tag=build_tag, dockerfile=settings['dockerfile'], rm=True, forcerm=True, buildargs={ 'CI_BUILD_DATE':", "tag_image(image, settings, repos) print('Tagged. Pushing image tags to registries...', flush=True) push_image(docker_client, settings, repos)", "clients def get_sts_client(settings): return boto3.client('sts', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'] ) def exit_with_error(message, *args): print('Something went", "in settings['tags']: for repo in repos: docker_client.images.push( repository=repo['uri'], tag=tag ) def build_and_push_image(): settings", "region in settings['regions']: print('- ', region) print('Fetching repos info from ECR across regions...',", "in line: print(line['stream'].strip()) raise print('Build finished.') print('Tags:') for tag in settings['tags']: print('- ',", "print(line['stream'].strip()) raise print('Build finished.') print('Tags:') for tag in settings['tags']: print('- ', tag) print('Tagging", "aws_account_id) print('Fetched repos info.') print('Repos:') for repo in repos: print('- ', repo['uri']) print('Logging", "env.get('PLUGIN_TAGS') tags = [tag for tag in user_tags.split(',')] return tags def get_settings(env): return", "print('Something went wrong:', message.format(*args), file=sys.stderr, flush=True) sys.exit(1) def get_aws_account_id(sts_client): return sts_client.get_caller_identity().get('Account') def get_regions(env):", "}, labels={ 'org.label-schema.schema-version': '1.0', 'org.label-schema.build-date': build_date, 'org.label-schema.vcs-url': settings['repo_link'], 'org.label-schema.vcs-ref': settings['commit'] } ) return", "get_aws_account_id(sts_client): return sts_client.get_caller_identity().get('Account') def get_regions(env): regions = env.get('PLUGIN_REGION') if not regions: return None", "def get_ecr_login(ecr_client, registry_id): response = ecr_client.get_authorization_token(registryIds=[registry_id]) registry = response['authorizationData'][0]['proxyEndpoint'] token = response['authorizationData'][0]['authorizationToken'] username,", "Pushing image tags to registries...', flush=True) push_image(docker_client, settings, repos) print('Pushed. All done.') if", "repos info from ECR across regions...', flush=True) repos = get_repos(settings, ecr_clients, aws_account_id) print('Fetched", "response['authorizationData'][0]['proxyEndpoint'] token = response['authorizationData'][0]['authorizationToken'] username, password = base64.b64decode(token).decode().split(':') return { 'username': username, 'password':", "for line in e.build_log: if 'stream' in line: print(line['stream'].strip()) raise print('Build finished.') print('Tags:')", "import base64 from datetime import datetime, timezone def get_docker_client(): return docker.from_env() def get_ecr_clients(settings):", "is', settings['repo'], flush=True) print('Regions:') for region in settings['regions']: print('- ', region) print('Fetching repos", "get_aws_account_id(sts_client) print('AWS account id is {0}.'.format(aws_account_id)) print('Repo name is', settings['repo'], flush=True) print('Regions:') for", "print('- ', tag) print('Tagging image...', flush=True) tag_image(image, settings, repos) print('Tagged. Pushing image tags", "aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'], region_name=region )) return clients def get_sts_client(settings): return boto3.client('sts', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'] )", "tag in settings['tags']: print('- ', tag) print('Tagging image...', flush=True) tag_image(image, settings, repos) print('Tagged.", "registry } def get_repos(settings, ecr_clients, aws_account_id): repos = [] for client in ecr_clients:", "region) print('Fetching repos info from ECR across regions...', flush=True) repos = get_repos(settings, ecr_clients,", "'CI_VCS_REF': settings['commit'] }, labels={ 'org.label-schema.schema-version': '1.0', 'org.label-schema.build-date': build_date, 'org.label-schema.vcs-url': settings['repo_link'], 'org.label-schema.vcs-ref': settings['commit'] }", "'org.label-schema.vcs-url': settings['repo_link'], 'org.label-schema.vcs-ref': settings['commit'] } ) return image def tag_image(image, settings, repos): for", "for tag in user_tags.split(',')] return tags def get_settings(env): return { 'access_key_id': env.get('PLUGIN_ACCESS_KEY_ID'), 'secret_access_key':", ") return image def tag_image(image, settings, repos): for tag in settings['tags']: for repo", "return { 'username': username, 'password': password, 'registry': registry } def get_repos(settings, ecr_clients, aws_account_id):", "build_date, 'org.label-schema.vcs-url': settings['repo_link'], 'org.label-schema.vcs-ref': settings['commit'] } ) return image def tag_image(image, settings, repos):", "{ 'access_key_id': env.get('PLUGIN_ACCESS_KEY_ID'), 'secret_access_key': env.get('PLUGIN_SECRET_ACCESS_KEY'), 'regions': get_regions(env), 'repo': get_repo(env), 'dockerfile': get_dockerfile(env), 'commit': env.get('DRONE_COMMIT'),", "get_tags(env): user_tags = env.get('PLUGIN_TAGS') tags = [tag for tag in user_tags.split(',')] return tags", "settings, repos) print('Tagged. Pushing image tags to registries...', flush=True) push_image(docker_client, settings, repos) print('Pushed.", "regions.split(',') def get_repo(env): return env.get('PLUGIN_REPO', env.get('DRONE_REPO_NAME')) def get_dockerfile(env): return env.get('PLUGIN_DOCKERFILE', './Dockerfile') def get_tags(env):", "[] for client in ecr_clients: response = client.describe_repositories( registryId=aws_account_id, repositoryNames=[settings['repo']] ) repo =", "repos info.') print('Repos:') for repo in repos: print('- ', repo['uri']) print('Logging in to", "def get_settings(env): return { 'access_key_id': env.get('PLUGIN_ACCESS_KEY_ID'), 'secret_access_key': env.get('PLUGIN_SECRET_ACCESS_KEY'), 'regions': get_regions(env), 'repo': get_repo(env), 'dockerfile':", "get_dockerfile(env), 'commit': env.get('DRONE_COMMIT'), 'repo_link': env.get('DRONE_REPO_LINK'), 'tags': get_tags(env) } def get_ecr_login(ecr_client, registry_id): response =", "for repo in repos: docker_client.images.push( repository=repo['uri'], tag=tag ) def build_and_push_image(): settings = get_settings(os.environ)", "'password': password, 'registry': registry } def get_repos(settings, ecr_clients, aws_account_id): repos = [] for", "aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'] ) def exit_with_error(message, *args): print('Something went wrong:', message.format(*args), file=sys.stderr, flush=True) sys.exit(1)", "boto3.client('sts', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'] ) def exit_with_error(message, *args): print('Something went wrong:', message.format(*args), file=sys.stderr, flush=True)", "build_image(docker_client, settings): build_tag = ':'.join((settings['repo'], settings['tags'][0])) build_date = datetime.now(timezone.utc).astimezone().isoformat() image, *_ = docker_client.images.build(", "forcerm=True, buildargs={ 'CI_BUILD_DATE': build_date, 'CI_VCS_URL': settings['repo_link'], 'CI_VCS_REF': settings['commit'] }, labels={ 'org.label-schema.schema-version': '1.0', 'org.label-schema.build-date':", "= response['authorizationData'][0]['authorizationToken'] username, password = base64.b64decode(token).decode().split(':') return { 'username': username, 'password': password, 'registry':", "flush=True) print('Regions:') for region in settings['regions']: print('- ', region) print('Fetching repos info from", "env.get('PLUGIN_SECRET_ACCESS_KEY'), 'regions': get_regions(env), 'repo': get_repo(env), 'dockerfile': get_dockerfile(env), 'commit': env.get('DRONE_COMMIT'), 'repo_link': env.get('DRONE_REPO_LINK'), 'tags': get_tags(env)", "client.describe_repositories( registryId=aws_account_id, repositoryNames=[settings['repo']] ) repo = response['repositories'][0] repos.append({ 'registry_id': repo['registryId'], 'name': repo['repositoryName'], 'uri':", "get_sts_client(settings) ecr_clients = get_ecr_clients(settings) docker_client = get_docker_client() print('Finding AWS account id...') aws_account_id =", "env.get('PLUGIN_DOCKERFILE', './Dockerfile') def get_tags(env): user_tags = env.get('PLUGIN_TAGS') tags = [tag for tag in", "repo in repos: print('- ', repo['uri']) print('Logging in to registries...', flush=True) login_to_registries(docker_client, repos)", "tag in settings['tags']: for repo in repos: docker_client.images.push( repository=repo['uri'], tag=tag ) def build_and_push_image():", "repo['repositoryUri'], 'login': get_ecr_login(client, repo['registryId']) }) return repos def login_to_registries(docker_client, repos): for repo in", "settings['tags']: for repo in repos: image.tag( repository=repo['uri'], tag=tag ) def push_image(docker_client, settings, repos):", "print('Repos:') for repo in repos: print('- ', repo['uri']) print('Logging in to registries...', flush=True)", "login = repo['login'] docker_client.login( login['username'], login['password'], registry=login['registry'] ) def build_image(docker_client, settings): build_tag =", "tags to registries...', flush=True) push_image(docker_client, settings, repos) print('Pushed. All done.') if __name__ ==", "= get_settings(os.environ) sts_client = get_sts_client(settings) ecr_clients = get_ecr_clients(settings) docker_client = get_docker_client() print('Finding AWS", "response['authorizationData'][0]['authorizationToken'] username, password = base64.b64decode(token).decode().split(':') return { 'username': username, 'password': password, 'registry': registry", "image.tag( repository=repo['uri'], tag=tag ) def push_image(docker_client, settings, repos): for tag in settings['tags']: for", "print('Logged in. Building image...', flush=True) try: image = build_image(docker_client, settings) except docker.errors.BuildError as", "registryId=aws_account_id, repositoryNames=[settings['repo']] ) repo = response['repositories'][0] repos.append({ 'registry_id': repo['registryId'], 'name': repo['repositoryName'], 'uri': repo['repositoryUri'],", ") repo = response['repositories'][0] repos.append({ 'registry_id': repo['registryId'], 'name': repo['repositoryName'], 'uri': repo['repositoryUri'], 'login': get_ecr_login(client,", "repos def login_to_registries(docker_client, repos): for repo in repos: login = repo['login'] docker_client.login( login['username'],", "sys import base64 from datetime import datetime, timezone def get_docker_client(): return docker.from_env() def", "return image def tag_image(image, settings, repos): for tag in settings['tags']: for repo in", "sts_client = get_sts_client(settings) ecr_clients = get_ecr_clients(settings) docker_client = get_docker_client() print('Finding AWS account id...')", "password, 'registry': registry } def get_repos(settings, ecr_clients, aws_account_id): repos = [] for client", "get_regions(env), 'repo': get_repo(env), 'dockerfile': get_dockerfile(env), 'commit': env.get('DRONE_COMMIT'), 'repo_link': env.get('DRONE_REPO_LINK'), 'tags': get_tags(env) } def", "flush=True) sys.exit(1) def get_aws_account_id(sts_client): return sts_client.get_caller_identity().get('Account') def get_regions(env): regions = env.get('PLUGIN_REGION') if not", "def exit_with_error(message, *args): print('Something went wrong:', message.format(*args), file=sys.stderr, flush=True) sys.exit(1) def get_aws_account_id(sts_client): return", "', tag) print('Tagging image...', flush=True) tag_image(image, settings, repos) print('Tagged. Pushing image tags to", "'name': repo['repositoryName'], 'uri': repo['repositoryUri'], 'login': get_ecr_login(client, repo['registryId']) }) return repos def login_to_registries(docker_client, repos):", "docker_client.images.build( path=\"./\", tag=build_tag, dockerfile=settings['dockerfile'], rm=True, forcerm=True, buildargs={ 'CI_BUILD_DATE': build_date, 'CI_VCS_URL': settings['repo_link'], 'CI_VCS_REF': settings['commit']", "username, 'password': password, 'registry': registry } def get_repos(settings, ecr_clients, aws_account_id): repos = []", "id is {0}.'.format(aws_account_id)) print('Repo name is', settings['repo'], flush=True) print('Regions:') for region in settings['regions']:", "for repo in repos: login = repo['login'] docker_client.login( login['username'], login['password'], registry=login['registry'] ) def", "', repo['uri']) print('Logging in to registries...', flush=True) login_to_registries(docker_client, repos) print('Logged in. Building image...',", "flush=True) login_to_registries(docker_client, repos) print('Logged in. Building image...', flush=True) try: image = build_image(docker_client, settings)", "print('Tags:') for tag in settings['tags']: print('- ', tag) print('Tagging image...', flush=True) tag_image(image, settings,", "return repos def login_to_registries(docker_client, repos): for repo in repos: login = repo['login'] docker_client.login(", "tag in user_tags.split(',')] return tags def get_settings(env): return { 'access_key_id': env.get('PLUGIN_ACCESS_KEY_ID'), 'secret_access_key': env.get('PLUGIN_SECRET_ACCESS_KEY'),", "import sys import base64 from datetime import datetime, timezone def get_docker_client(): return docker.from_env()", "login['username'], login['password'], registry=login['registry'] ) def build_image(docker_client, settings): build_tag = ':'.join((settings['repo'], settings['tags'][0])) build_date =", "docker_client = get_docker_client() print('Finding AWS account id...') aws_account_id = get_aws_account_id(sts_client) print('AWS account id", "except docker.errors.BuildError as e: for line in e.build_log: if 'stream' in line: print(line['stream'].strip())", "env.get('PLUGIN_REPO', env.get('DRONE_REPO_NAME')) def get_dockerfile(env): return env.get('PLUGIN_DOCKERFILE', './Dockerfile') def get_tags(env): user_tags = env.get('PLUGIN_TAGS') tags", "timezone def get_docker_client(): return docker.from_env() def get_ecr_clients(settings): clients = [] for region in", "ecr_clients: response = client.describe_repositories( registryId=aws_account_id, repositoryNames=[settings['repo']] ) repo = response['repositories'][0] repos.append({ 'registry_id': repo['registryId'],", "if 'stream' in line: print(line['stream'].strip()) raise print('Build finished.') print('Tags:') for tag in settings['tags']:", "image, *_ = docker_client.images.build( path=\"./\", tag=build_tag, dockerfile=settings['dockerfile'], rm=True, forcerm=True, buildargs={ 'CI_BUILD_DATE': build_date, 'CI_VCS_URL':", "import os import sys import base64 from datetime import datetime, timezone def get_docker_client():", "def get_docker_client(): return docker.from_env() def get_ecr_clients(settings): clients = [] for region in settings['regions']:", "path=\"./\", tag=build_tag, dockerfile=settings['dockerfile'], rm=True, forcerm=True, buildargs={ 'CI_BUILD_DATE': build_date, 'CI_VCS_URL': settings['repo_link'], 'CI_VCS_REF': settings['commit'] },", "docker.from_env() def get_ecr_clients(settings): clients = [] for region in settings['regions']: clients.append(boto3.client('ecr', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'],", "'uri': repo['repositoryUri'], 'login': get_ecr_login(client, repo['registryId']) }) return repos def login_to_registries(docker_client, repos): for repo", "env.get('PLUGIN_REGION') if not regions: return None return regions.split(',') def get_repo(env): return env.get('PLUGIN_REPO', env.get('DRONE_REPO_NAME'))", "= docker_client.images.build( path=\"./\", tag=build_tag, dockerfile=settings['dockerfile'], rm=True, forcerm=True, buildargs={ 'CI_BUILD_DATE': build_date, 'CI_VCS_URL': settings['repo_link'], 'CI_VCS_REF':", "get_settings(env): return { 'access_key_id': env.get('PLUGIN_ACCESS_KEY_ID'), 'secret_access_key': env.get('PLUGIN_SECRET_ACCESS_KEY'), 'regions': get_regions(env), 'repo': get_repo(env), 'dockerfile': get_dockerfile(env),", "settings, repos): for tag in settings['tags']: for repo in repos: docker_client.images.push( repository=repo['uri'], tag=tag", "= repo['login'] docker_client.login( login['username'], login['password'], registry=login['registry'] ) def build_image(docker_client, settings): build_tag = ':'.join((settings['repo'],", "= response['repositories'][0] repos.append({ 'registry_id': repo['registryId'], 'name': repo['repositoryName'], 'uri': repo['repositoryUri'], 'login': get_ecr_login(client, repo['registryId']) })", "docker_client.login( login['username'], login['password'], registry=login['registry'] ) def build_image(docker_client, settings): build_tag = ':'.join((settings['repo'], settings['tags'][0])) build_date", "regions: return None return regions.split(',') def get_repo(env): return env.get('PLUGIN_REPO', env.get('DRONE_REPO_NAME')) def get_dockerfile(env): return", "'username': username, 'password': password, 'registry': registry } def get_repos(settings, ecr_clients, aws_account_id): repos =", "'regions': get_regions(env), 'repo': get_repo(env), 'dockerfile': get_dockerfile(env), 'commit': env.get('DRONE_COMMIT'), 'repo_link': env.get('DRONE_REPO_LINK'), 'tags': get_tags(env) }", "registry = response['authorizationData'][0]['proxyEndpoint'] token = response['authorizationData'][0]['authorizationToken'] username, password = base64.b64decode(token).decode().split(':') return { 'username':", "repos): for tag in settings['tags']: for repo in repos: image.tag( repository=repo['uri'], tag=tag )", "get_ecr_login(ecr_client, registry_id): response = ecr_client.get_authorization_token(registryIds=[registry_id]) registry = response['authorizationData'][0]['proxyEndpoint'] token = response['authorizationData'][0]['authorizationToken'] username, password", "= ecr_client.get_authorization_token(registryIds=[registry_id]) registry = response['authorizationData'][0]['proxyEndpoint'] token = response['authorizationData'][0]['authorizationToken'] username, password = base64.b64decode(token).decode().split(':') return", "print('Tagged. Pushing image tags to registries...', flush=True) push_image(docker_client, settings, repos) print('Pushed. All done.')", "exit_with_error(message, *args): print('Something went wrong:', message.format(*args), file=sys.stderr, flush=True) sys.exit(1) def get_aws_account_id(sts_client): return sts_client.get_caller_identity().get('Account')", "buildargs={ 'CI_BUILD_DATE': build_date, 'CI_VCS_URL': settings['repo_link'], 'CI_VCS_REF': settings['commit'] }, labels={ 'org.label-schema.schema-version': '1.0', 'org.label-schema.build-date': build_date,", "tags def get_settings(env): return { 'access_key_id': env.get('PLUGIN_ACCESS_KEY_ID'), 'secret_access_key': env.get('PLUGIN_SECRET_ACCESS_KEY'), 'regions': get_regions(env), 'repo': get_repo(env),", "tag=tag ) def build_and_push_image(): settings = get_settings(os.environ) sts_client = get_sts_client(settings) ecr_clients = get_ecr_clients(settings)", "Building image...', flush=True) try: image = build_image(docker_client, settings) except docker.errors.BuildError as e: for", "tag=tag ) def push_image(docker_client, settings, repos): for tag in settings['tags']: for repo in", "settings['commit'] }, labels={ 'org.label-schema.schema-version': '1.0', 'org.label-schema.build-date': build_date, 'org.label-schema.vcs-url': settings['repo_link'], 'org.label-schema.vcs-ref': settings['commit'] } )", "registry=login['registry'] ) def build_image(docker_client, settings): build_tag = ':'.join((settings['repo'], settings['tags'][0])) build_date = datetime.now(timezone.utc).astimezone().isoformat() image,", "build_date = datetime.now(timezone.utc).astimezone().isoformat() image, *_ = docker_client.images.build( path=\"./\", tag=build_tag, dockerfile=settings['dockerfile'], rm=True, forcerm=True, buildargs={", "for tag in settings['tags']: for repo in repos: image.tag( repository=repo['uri'], tag=tag ) def", "is {0}.'.format(aws_account_id)) print('Repo name is', settings['repo'], flush=True) print('Regions:') for region in settings['regions']: print('-", "for repo in repos: print('- ', repo['uri']) print('Logging in to registries...', flush=True) login_to_registries(docker_client,", "get_regions(env): regions = env.get('PLUGIN_REGION') if not regions: return None return regions.split(',') def get_repo(env):", "'CI_BUILD_DATE': build_date, 'CI_VCS_URL': settings['repo_link'], 'CI_VCS_REF': settings['commit'] }, labels={ 'org.label-schema.schema-version': '1.0', 'org.label-schema.build-date': build_date, 'org.label-schema.vcs-url':", "def get_sts_client(settings): return boto3.client('sts', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'] ) def exit_with_error(message, *args): print('Something went wrong:',", "print('Logging in to registries...', flush=True) login_to_registries(docker_client, repos) print('Logged in. Building image...', flush=True) try:", "def build_image(docker_client, settings): build_tag = ':'.join((settings['repo'], settings['tags'][0])) build_date = datetime.now(timezone.utc).astimezone().isoformat() image, *_ =", "build_and_push_image(): settings = get_settings(os.environ) sts_client = get_sts_client(settings) ecr_clients = get_ecr_clients(settings) docker_client = get_docker_client()", "boto3 import os import sys import base64 from datetime import datetime, timezone def", "repos = get_repos(settings, ecr_clients, aws_account_id) print('Fetched repos info.') print('Repos:') for repo in repos:", "os import sys import base64 from datetime import datetime, timezone def get_docker_client(): return", "get_repo(env): return env.get('PLUGIN_REPO', env.get('DRONE_REPO_NAME')) def get_dockerfile(env): return env.get('PLUGIN_DOCKERFILE', './Dockerfile') def get_tags(env): user_tags =", "'login': get_ecr_login(client, repo['registryId']) }) return repos def login_to_registries(docker_client, repos): for repo in repos:", "get_ecr_clients(settings) docker_client = get_docker_client() print('Finding AWS account id...') aws_account_id = get_aws_account_id(sts_client) print('AWS account", "settings['regions']: clients.append(boto3.client('ecr', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'], region_name=region )) return clients def get_sts_client(settings): return boto3.client('sts', aws_access_key_id=settings['access_key_id'],", "raise print('Build finished.') print('Tags:') for tag in settings['tags']: print('- ', tag) print('Tagging image...',", "settings['repo_link'], 'CI_VCS_REF': settings['commit'] }, labels={ 'org.label-schema.schema-version': '1.0', 'org.label-schema.build-date': build_date, 'org.label-schema.vcs-url': settings['repo_link'], 'org.label-schema.vcs-ref': settings['commit']", "for client in ecr_clients: response = client.describe_repositories( registryId=aws_account_id, repositoryNames=[settings['repo']] ) repo = response['repositories'][0]", "} def get_repos(settings, ecr_clients, aws_account_id): repos = [] for client in ecr_clients: response", "settings['tags'][0])) build_date = datetime.now(timezone.utc).astimezone().isoformat() image, *_ = docker_client.images.build( path=\"./\", tag=build_tag, dockerfile=settings['dockerfile'], rm=True, forcerm=True,", "sys.exit(1) def get_aws_account_id(sts_client): return sts_client.get_caller_identity().get('Account') def get_regions(env): regions = env.get('PLUGIN_REGION') if not regions:", "return tags def get_settings(env): return { 'access_key_id': env.get('PLUGIN_ACCESS_KEY_ID'), 'secret_access_key': env.get('PLUGIN_SECRET_ACCESS_KEY'), 'regions': get_regions(env), 'repo':", "repo['repositoryName'], 'uri': repo['repositoryUri'], 'login': get_ecr_login(client, repo['registryId']) }) return repos def login_to_registries(docker_client, repos): for", "return env.get('PLUGIN_REPO', env.get('DRONE_REPO_NAME')) def get_dockerfile(env): return env.get('PLUGIN_DOCKERFILE', './Dockerfile') def get_tags(env): user_tags = env.get('PLUGIN_TAGS')", "in repos: image.tag( repository=repo['uri'], tag=tag ) def push_image(docker_client, settings, repos): for tag in", "settings) except docker.errors.BuildError as e: for line in e.build_log: if 'stream' in line:", "get_dockerfile(env): return env.get('PLUGIN_DOCKERFILE', './Dockerfile') def get_tags(env): user_tags = env.get('PLUGIN_TAGS') tags = [tag for", "get_settings(os.environ) sts_client = get_sts_client(settings) ecr_clients = get_ecr_clients(settings) docker_client = get_docker_client() print('Finding AWS account", "for region in settings['regions']: print('- ', region) print('Fetching repos info from ECR across", "datetime import datetime, timezone def get_docker_client(): return docker.from_env() def get_ecr_clients(settings): clients = []", "repo in repos: image.tag( repository=repo['uri'], tag=tag ) def push_image(docker_client, settings, repos): for tag", "[] for region in settings['regions']: clients.append(boto3.client('ecr', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'], region_name=region )) return clients def", "image...', flush=True) try: image = build_image(docker_client, settings) except docker.errors.BuildError as e: for line", "region in settings['regions']: clients.append(boto3.client('ecr', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'], region_name=region )) return clients def get_sts_client(settings): return", "get_repo(env), 'dockerfile': get_dockerfile(env), 'commit': env.get('DRONE_COMMIT'), 'repo_link': env.get('DRONE_REPO_LINK'), 'tags': get_tags(env) } def get_ecr_login(ecr_client, registry_id):", "repos: image.tag( repository=repo['uri'], tag=tag ) def push_image(docker_client, settings, repos): for tag in settings['tags']:", "docker_client.images.push( repository=repo['uri'], tag=tag ) def build_and_push_image(): settings = get_settings(os.environ) sts_client = get_sts_client(settings) ecr_clients", "to registries...', flush=True) login_to_registries(docker_client, repos) print('Logged in. Building image...', flush=True) try: image =", "def get_repo(env): return env.get('PLUGIN_REPO', env.get('DRONE_REPO_NAME')) def get_dockerfile(env): return env.get('PLUGIN_DOCKERFILE', './Dockerfile') def get_tags(env): user_tags", "settings): build_tag = ':'.join((settings['repo'], settings['tags'][0])) build_date = datetime.now(timezone.utc).astimezone().isoformat() image, *_ = docker_client.images.build( path=\"./\",", "repositoryNames=[settings['repo']] ) repo = response['repositories'][0] repos.append({ 'registry_id': repo['registryId'], 'name': repo['repositoryName'], 'uri': repo['repositoryUri'], 'login':", "'registry': registry } def get_repos(settings, ecr_clients, aws_account_id): repos = [] for client in", "ECR across regions...', flush=True) repos = get_repos(settings, ecr_clients, aws_account_id) print('Fetched repos info.') print('Repos:')", "'registry_id': repo['registryId'], 'name': repo['repositoryName'], 'uri': repo['repositoryUri'], 'login': get_ecr_login(client, repo['registryId']) }) return repos def", "return sts_client.get_caller_identity().get('Account') def get_regions(env): regions = env.get('PLUGIN_REGION') if not regions: return None return", "build_image(docker_client, settings) except docker.errors.BuildError as e: for line in e.build_log: if 'stream' in", "settings['repo_link'], 'org.label-schema.vcs-ref': settings['commit'] } ) return image def tag_image(image, settings, repos): for tag", "if not regions: return None return regions.split(',') def get_repo(env): return env.get('PLUGIN_REPO', env.get('DRONE_REPO_NAME')) def", "= env.get('PLUGIN_REGION') if not regions: return None return regions.split(',') def get_repo(env): return env.get('PLUGIN_REPO',", "return None return regions.split(',') def get_repo(env): return env.get('PLUGIN_REPO', env.get('DRONE_REPO_NAME')) def get_dockerfile(env): return env.get('PLUGIN_DOCKERFILE',", "= get_aws_account_id(sts_client) print('AWS account id is {0}.'.format(aws_account_id)) print('Repo name is', settings['repo'], flush=True) print('Regions:')", "= get_docker_client() print('Finding AWS account id...') aws_account_id = get_aws_account_id(sts_client) print('AWS account id is", "registry_id): response = ecr_client.get_authorization_token(registryIds=[registry_id]) registry = response['authorizationData'][0]['proxyEndpoint'] token = response['authorizationData'][0]['authorizationToken'] username, password =", "'org.label-schema.schema-version': '1.0', 'org.label-schema.build-date': build_date, 'org.label-schema.vcs-url': settings['repo_link'], 'org.label-schema.vcs-ref': settings['commit'] } ) return image def", "def get_aws_account_id(sts_client): return sts_client.get_caller_identity().get('Account') def get_regions(env): regions = env.get('PLUGIN_REGION') if not regions: return", "from ECR across regions...', flush=True) repos = get_repos(settings, ecr_clients, aws_account_id) print('Fetched repos info.')", ")) return clients def get_sts_client(settings): return boto3.client('sts', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'] ) def exit_with_error(message, *args):", "id...') aws_account_id = get_aws_account_id(sts_client) print('AWS account id is {0}.'.format(aws_account_id)) print('Repo name is', settings['repo'],", "= get_sts_client(settings) ecr_clients = get_ecr_clients(settings) docker_client = get_docker_client() print('Finding AWS account id...') aws_account_id", "repos.append({ 'registry_id': repo['registryId'], 'name': repo['repositoryName'], 'uri': repo['repositoryUri'], 'login': get_ecr_login(client, repo['registryId']) }) return repos", "[tag for tag in user_tags.split(',')] return tags def get_settings(env): return { 'access_key_id': env.get('PLUGIN_ACCESS_KEY_ID'),", "not regions: return None return regions.split(',') def get_repo(env): return env.get('PLUGIN_REPO', env.get('DRONE_REPO_NAME')) def get_dockerfile(env):", "aws_account_id): repos = [] for client in ecr_clients: response = client.describe_repositories( registryId=aws_account_id, repositoryNames=[settings['repo']]", "print('- ', region) print('Fetching repos info from ECR across regions...', flush=True) repos =", "print('Fetched repos info.') print('Repos:') for repo in repos: print('- ', repo['uri']) print('Logging in", "print('AWS account id is {0}.'.format(aws_account_id)) print('Repo name is', settings['repo'], flush=True) print('Regions:') for region", "for region in settings['regions']: clients.append(boto3.client('ecr', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'], region_name=region )) return clients def get_sts_client(settings):", "'access_key_id': env.get('PLUGIN_ACCESS_KEY_ID'), 'secret_access_key': env.get('PLUGIN_SECRET_ACCESS_KEY'), 'regions': get_regions(env), 'repo': get_repo(env), 'dockerfile': get_dockerfile(env), 'commit': env.get('DRONE_COMMIT'), 'repo_link':", "in repos: print('- ', repo['uri']) print('Logging in to registries...', flush=True) login_to_registries(docker_client, repos) print('Logged", "get_ecr_login(client, repo['registryId']) }) return repos def login_to_registries(docker_client, repos): for repo in repos: login", "to registries...', flush=True) push_image(docker_client, settings, repos) print('Pushed. All done.') if __name__ == '__main__':", "as e: for line in e.build_log: if 'stream' in line: print(line['stream'].strip()) raise print('Build", "e: for line in e.build_log: if 'stream' in line: print(line['stream'].strip()) raise print('Build finished.')", "{0}.'.format(aws_account_id)) print('Repo name is', settings['repo'], flush=True) print('Regions:') for region in settings['regions']: print('- ',", "def get_repos(settings, ecr_clients, aws_account_id): repos = [] for client in ecr_clients: response =", "regions...', flush=True) repos = get_repos(settings, ecr_clients, aws_account_id) print('Fetched repos info.') print('Repos:') for repo", "= client.describe_repositories( registryId=aws_account_id, repositoryNames=[settings['repo']] ) repo = response['repositories'][0] repos.append({ 'registry_id': repo['registryId'], 'name': repo['repositoryName'],", "info.') print('Repos:') for repo in repos: print('- ', repo['uri']) print('Logging in to registries...',", "repos: login = repo['login'] docker_client.login( login['username'], login['password'], registry=login['registry'] ) def build_image(docker_client, settings): build_tag", "AWS account id...') aws_account_id = get_aws_account_id(sts_client) print('AWS account id is {0}.'.format(aws_account_id)) print('Repo name", "account id...') aws_account_id = get_aws_account_id(sts_client) print('AWS account id is {0}.'.format(aws_account_id)) print('Repo name is',", "', region) print('Fetching repos info from ECR across regions...', flush=True) repos = get_repos(settings,", "print('Tagging image...', flush=True) tag_image(image, settings, repos) print('Tagged. Pushing image tags to registries...', flush=True)", "get_repos(settings, ecr_clients, aws_account_id): repos = [] for client in ecr_clients: response = client.describe_repositories(", "in repos: login = repo['login'] docker_client.login( login['username'], login['password'], registry=login['registry'] ) def build_image(docker_client, settings):", "in settings['tags']: for repo in repos: image.tag( repository=repo['uri'], tag=tag ) def push_image(docker_client, settings,", "= get_ecr_clients(settings) docker_client = get_docker_client() print('Finding AWS account id...') aws_account_id = get_aws_account_id(sts_client) print('AWS", "return env.get('PLUGIN_DOCKERFILE', './Dockerfile') def get_tags(env): user_tags = env.get('PLUGIN_TAGS') tags = [tag for tag", "'stream' in line: print(line['stream'].strip()) raise print('Build finished.') print('Tags:') for tag in settings['tags']: print('-", "tag=build_tag, dockerfile=settings['dockerfile'], rm=True, forcerm=True, buildargs={ 'CI_BUILD_DATE': build_date, 'CI_VCS_URL': settings['repo_link'], 'CI_VCS_REF': settings['commit'] }, labels={", "ecr_clients, aws_account_id) print('Fetched repos info.') print('Repos:') for repo in repos: print('- ', repo['uri'])", "docker import boto3 import os import sys import base64 from datetime import datetime,", "import datetime, timezone def get_docker_client(): return docker.from_env() def get_ecr_clients(settings): clients = [] for", "= base64.b64decode(token).decode().split(':') return { 'username': username, 'password': password, 'registry': registry } def get_repos(settings,", "import docker import boto3 import os import sys import base64 from datetime import", "return { 'access_key_id': env.get('PLUGIN_ACCESS_KEY_ID'), 'secret_access_key': env.get('PLUGIN_SECRET_ACCESS_KEY'), 'regions': get_regions(env), 'repo': get_repo(env), 'dockerfile': get_dockerfile(env), 'commit':", "*_ = docker_client.images.build( path=\"./\", tag=build_tag, dockerfile=settings['dockerfile'], rm=True, forcerm=True, buildargs={ 'CI_BUILD_DATE': build_date, 'CI_VCS_URL': settings['repo_link'],", "aws_secret_access_key=settings['secret_access_key'] ) def exit_with_error(message, *args): print('Something went wrong:', message.format(*args), file=sys.stderr, flush=True) sys.exit(1) def", "':'.join((settings['repo'], settings['tags'][0])) build_date = datetime.now(timezone.utc).astimezone().isoformat() image, *_ = docker_client.images.build( path=\"./\", tag=build_tag, dockerfile=settings['dockerfile'], rm=True,", "get_ecr_clients(settings): clients = [] for region in settings['regions']: clients.append(boto3.client('ecr', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'], region_name=region ))", "return regions.split(',') def get_repo(env): return env.get('PLUGIN_REPO', env.get('DRONE_REPO_NAME')) def get_dockerfile(env): return env.get('PLUGIN_DOCKERFILE', './Dockerfile') def", "in ecr_clients: response = client.describe_repositories( registryId=aws_account_id, repositoryNames=[settings['repo']] ) repo = response['repositories'][0] repos.append({ 'registry_id':", "= env.get('PLUGIN_TAGS') tags = [tag for tag in user_tags.split(',')] return tags def get_settings(env):", "= [] for region in settings['regions']: clients.append(boto3.client('ecr', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'], region_name=region )) return clients", "get_tags(env) } def get_ecr_login(ecr_client, registry_id): response = ecr_client.get_authorization_token(registryIds=[registry_id]) registry = response['authorizationData'][0]['proxyEndpoint'] token =", "in settings['regions']: clients.append(boto3.client('ecr', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'], region_name=region )) return clients def get_sts_client(settings): return boto3.client('sts',", "rm=True, forcerm=True, buildargs={ 'CI_BUILD_DATE': build_date, 'CI_VCS_URL': settings['repo_link'], 'CI_VCS_REF': settings['commit'] }, labels={ 'org.label-schema.schema-version': '1.0',", "ecr_client.get_authorization_token(registryIds=[registry_id]) registry = response['authorizationData'][0]['proxyEndpoint'] token = response['authorizationData'][0]['authorizationToken'] username, password = base64.b64decode(token).decode().split(':') return {", "response = ecr_client.get_authorization_token(registryIds=[registry_id]) registry = response['authorizationData'][0]['proxyEndpoint'] token = response['authorizationData'][0]['authorizationToken'] username, password = base64.b64decode(token).decode().split(':')", "'tags': get_tags(env) } def get_ecr_login(ecr_client, registry_id): response = ecr_client.get_authorization_token(registryIds=[registry_id]) registry = response['authorizationData'][0]['proxyEndpoint'] token", "image def tag_image(image, settings, repos): for tag in settings['tags']: for repo in repos:", "repository=repo['uri'], tag=tag ) def build_and_push_image(): settings = get_settings(os.environ) sts_client = get_sts_client(settings) ecr_clients =", "} def get_ecr_login(ecr_client, registry_id): response = ecr_client.get_authorization_token(registryIds=[registry_id]) registry = response['authorizationData'][0]['proxyEndpoint'] token = response['authorizationData'][0]['authorizationToken']", "registries...', flush=True) push_image(docker_client, settings, repos) print('Pushed. All done.') if __name__ == '__main__': build_and_push_image()", "import boto3 import os import sys import base64 from datetime import datetime, timezone", "across regions...', flush=True) repos = get_repos(settings, ecr_clients, aws_account_id) print('Fetched repos info.') print('Repos:') for", "response['repositories'][0] repos.append({ 'registry_id': repo['registryId'], 'name': repo['repositoryName'], 'uri': repo['repositoryUri'], 'login': get_ecr_login(client, repo['registryId']) }) return", "clients = [] for region in settings['regions']: clients.append(boto3.client('ecr', aws_access_key_id=settings['access_key_id'], aws_secret_access_key=settings['secret_access_key'], region_name=region )) return", ") def build_and_push_image(): settings = get_settings(os.environ) sts_client = get_sts_client(settings) ecr_clients = get_ecr_clients(settings) docker_client", "in e.build_log: if 'stream' in line: print(line['stream'].strip()) raise print('Build finished.') print('Tags:') for tag", "login['password'], registry=login['registry'] ) def build_image(docker_client, settings): build_tag = ':'.join((settings['repo'], settings['tags'][0])) build_date = datetime.now(timezone.utc).astimezone().isoformat()", "repo['login'] docker_client.login( login['username'], login['password'], registry=login['registry'] ) def build_image(docker_client, settings): build_tag = ':'.join((settings['repo'], settings['tags'][0]))" ]
[ "def __init__(self): super().__init__() self._aws_account_id = None @property def aws_account_id(self): return self._aws_account_id @aws_account_id.setter def", "import Context import click class LocalContext(Context): def __init__(self): super().__init__() self._aws_account_id = None @property", "super().__init__() self._aws_account_id = None @property def aws_account_id(self): return self._aws_account_id @aws_account_id.setter def aws_account_id(self, value):", "@property def aws_account_id(self): return self._aws_account_id @aws_account_id.setter def aws_account_id(self, value): self._aws_account_id = value self._refresh_session()", "samcli.cli.context import Context import click class LocalContext(Context): def __init__(self): super().__init__() self._aws_account_id = None", "aws_account_id(self): return self._aws_account_id @aws_account_id.setter def aws_account_id(self, value): self._aws_account_id = value self._refresh_session() pass_context =", "click class LocalContext(Context): def __init__(self): super().__init__() self._aws_account_id = None @property def aws_account_id(self): return", "LocalContext(Context): def __init__(self): super().__init__() self._aws_account_id = None @property def aws_account_id(self): return self._aws_account_id @aws_account_id.setter", "= None @property def aws_account_id(self): return self._aws_account_id @aws_account_id.setter def aws_account_id(self, value): self._aws_account_id =", "self._aws_account_id = None @property def aws_account_id(self): return self._aws_account_id @aws_account_id.setter def aws_account_id(self, value): self._aws_account_id", "def aws_account_id(self): return self._aws_account_id @aws_account_id.setter def aws_account_id(self, value): self._aws_account_id = value self._refresh_session() pass_context", "return self._aws_account_id @aws_account_id.setter def aws_account_id(self, value): self._aws_account_id = value self._refresh_session() pass_context = click.make_pass_decorator(LocalContext)", "None @property def aws_account_id(self): return self._aws_account_id @aws_account_id.setter def aws_account_id(self, value): self._aws_account_id = value", "class LocalContext(Context): def __init__(self): super().__init__() self._aws_account_id = None @property def aws_account_id(self): return self._aws_account_id", "__init__(self): super().__init__() self._aws_account_id = None @property def aws_account_id(self): return self._aws_account_id @aws_account_id.setter def aws_account_id(self,", "Context import click class LocalContext(Context): def __init__(self): super().__init__() self._aws_account_id = None @property def", "import click class LocalContext(Context): def __init__(self): super().__init__() self._aws_account_id = None @property def aws_account_id(self):", "from samcli.cli.context import Context import click class LocalContext(Context): def __init__(self): super().__init__() self._aws_account_id =" ]
[ "ENGINEERING, CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, <EMAIL>. #", "OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY,", "TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS, #", "# # Distributed under 3-Clause BSD license. See LICENSE file for more information.", "from .ecsw import * from .ecsw_assembly import * from .poly3 import * from", "\"\"\" Hyper reduction module \"\"\" from .ecsw import * from .ecsw_assembly import *", "# BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, <EMAIL>. # # Distributed under 3-Clause BSD", "BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, <EMAIL>. # # Distributed under 3-Clause BSD license.", "GARCHING/MUNICH, GERMANY, <EMAIL>. # # Distributed under 3-Clause BSD license. See LICENSE file", "85748 GARCHING/MUNICH, GERMANY, <EMAIL>. # # Distributed under 3-Clause BSD license. See LICENSE", "module \"\"\" from .ecsw import * from .ecsw_assembly import * from .poly3 import", "\"\"\" from .ecsw import * from .ecsw_assembly import * from .poly3 import *", "OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, <EMAIL>. # # Distributed", "See LICENSE file for more information. # \"\"\" Hyper reduction module \"\"\" from", "Distributed under 3-Clause BSD license. See LICENSE file for more information. # \"\"\"", "more information. # \"\"\" Hyper reduction module \"\"\" from .ecsw import * from", "15, 85748 GARCHING/MUNICH, GERMANY, <EMAIL>. # # Distributed under 3-Clause BSD license. See", "MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748", ".ecsw import * from .ecsw_assembly import * from .poly3 import * from .training_set_generation", "<EMAIL>. # # Distributed under 3-Clause BSD license. See LICENSE file for more", "MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, <EMAIL>.", "under 3-Clause BSD license. See LICENSE file for more information. # \"\"\" Hyper", "UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE", "DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH,", "file for more information. # \"\"\" Hyper reduction module \"\"\" from .ecsw import", "APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, <EMAIL>. # # Distributed under", "LICENSE file for more information. # \"\"\" Hyper reduction module \"\"\" from .ecsw", "import * from .ecsw_assembly import * from .poly3 import * from .training_set_generation import", "(c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED", "MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, <EMAIL>. # # Distributed under 3-Clause", "3-Clause BSD license. See LICENSE file for more information. # \"\"\" Hyper reduction", "GERMANY, <EMAIL>. # # Distributed under 3-Clause BSD license. See LICENSE file for", "license. See LICENSE file for more information. # \"\"\" Hyper reduction module \"\"\"", "# # Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING,", "OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15,", "# Distributed under 3-Clause BSD license. See LICENSE file for more information. #", "# Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR", "for more information. # \"\"\" Hyper reduction module \"\"\" from .ecsw import *", "BSD license. See LICENSE file for more information. # \"\"\" Hyper reduction module", "Hyper reduction module \"\"\" from .ecsw import * from .ecsw_assembly import * from", "information. # \"\"\" Hyper reduction module \"\"\" from .ecsw import * from .ecsw_assembly", "* from .ecsw_assembly import * from .poly3 import * from .training_set_generation import *", "CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, <EMAIL>. # #", "2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS,", "# \"\"\" Hyper reduction module \"\"\" from .ecsw import * from .ecsw_assembly import", "Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF", "reduction module \"\"\" from .ecsw import * from .ecsw_assembly import * from .poly3" ]
[ "problem_name ) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3])", "\"bimodal\", \"poisson-high-intra\", \"poisson-high-inter\", ] SCALE_FACTORS = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0,", "import sys sys.path.append(\"..\") from lib.partitioning import FMPartitioning, SpectralClustering PROBLEM_NAMES = [ \"GtsCe.graphml\", \"UsCarrier.graphml\",", "True, \"inv-cap\", SpectralClustering, 2), \"Ion.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Kdl.graphml\": (4, True,", "[] for ( (problem_name, tm_model, scale_factor), topo_and_tm_fnames, ) in GROUPED_BY_PROBLEMS.items(): for slice in", "tm_fname) ) PROBLEMS.append((problem_name, topo_fname, tm_fname)) for tm_fname in iglob( \"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format( model, problem_name )", "vals in GROUPED_BY_PROBLEMS.items(): GROUPED_BY_PROBLEMS[key] = sorted(vals) GROUPED_BY_HOLDOUT_PROBLEMS = dict(GROUPED_BY_HOLDOUT_PROBLEMS) for key, vals in", "16.0, 32.0, 64.0, 128.0] PATH_FORM_HYPERPARAMS = (4, True, \"inv-cap\") NCFLOW_HYPERPARAMS = { \"GtsCe.graphml\":", "else float(x), choices=SCALE_FACTORS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--slices\", type=int, choices=range(5), nargs=\"+\",", "\"DialtelecomCz.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Uninett2010.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Interoute.graphml\":", "(4, True, \"inv-cap\", FMPartitioning, 3), \"Deltacom.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"DialtelecomCz.graphml\": (4,", "} PROBLEM_NAMES_AND_TM_MODELS = [ (prob_name, tm_model) for prob_name in PROBLEM_NAMES for tm_model in", ") parser.add_argument( \"--topos\", type=str, choices=PROBLEM_NAMES + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--scale-factors\", type=lambda", "collections import defaultdict from glob import iglob import argparse import os import sys", "type=str, choices=TM_MODELS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--topos\", type=str, choices=PROBLEM_NAMES + [\"all\"],", "if x == \"all\" else float(x), choices=SCALE_FACTORS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument(", "True, \"inv-cap\", FMPartitioning, 3), \"Deltacom.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"DialtelecomCz.graphml\": (4, True,", "= [ (prob_name, tm_model) for prob_name in PROBLEM_NAMES for tm_model in TM_MODELS ]", "64.0, 128.0] PATH_FORM_HYPERPARAMS = (4, True, \"inv-cap\") NCFLOW_HYPERPARAMS = { \"GtsCe.graphml\": (4, True,", "= [ \"GtsCe.graphml\", \"UsCarrier.graphml\", \"Cogentco.graphml\", \"Colt.graphml\", \"TataNld.graphml\", \"Deltacom.graphml\", \"DialtelecomCz.graphml\", \"Kdl.graphml\", ] TM_MODELS =", "= vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) HOLDOUT_PROBLEMS.append((problem_name, topo_fname, tm_fname))", "\"--topos\", type=str, choices=PROBLEM_NAMES + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--scale-factors\", type=lambda x: x", "= [] GROUPED_BY_PROBLEMS = defaultdict(list) HOLDOUT_PROBLEMS = [] GROUPED_BY_HOLDOUT_PROBLEMS = defaultdict(list) for problem_name", "lib.partitioning import FMPartitioning, SpectralClustering PROBLEM_NAMES = [ \"GtsCe.graphml\", \"UsCarrier.graphml\", \"Cogentco.graphml\", \"Colt.graphml\", \"TataNld.graphml\", \"Deltacom.graphml\",", ") parser.add_argument( \"--slices\", type=int, choices=range(5), nargs=\"+\", required=True ) for additional_arg in additional_args: name_or_flags,", "[1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0] PATH_FORM_HYPERPARAMS = (4, True, \"inv-cap\")", "in args.tm_models or tm_model in args.tm_models) and (\"all\" in args.scale_factors or scale_factor in", "problems.append((problem_name, topo_fname, tm_fname)) return problems def get_args_and_problems(output_csv_template, additional_args=[]): parser = argparse.ArgumentParser() parser.add_argument(\"--dry-run\", dest=\"dry_run\",", "PROBLEMS.append((problem_name, topo_fname, tm_fname)) for tm_fname in iglob( \"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format( model, problem_name ) ): vals", "TM_MODELS: for tm_fname in iglob( \"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model, problem_name) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed,", "tm_fname) ) HOLDOUT_PROBLEMS.append((problem_name, topo_fname, tm_fname)) GROUPED_BY_PROBLEMS = dict(GROUPED_BY_PROBLEMS) for key, vals in GROUPED_BY_PROBLEMS.items():", "\"inv-cap\", FMPartitioning, 3), \"UsCarrier.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Cogentco.graphml\": (4, True, \"inv-cap\",", "for problem_name in PROBLEM_NAMES: if problem_name.endswith(\".graphml\"): topo_fname = os.path.join(\"..\", \"topologies\", \"topology-zoo\", problem_name) else:", "[\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--slices\", type=int, choices=range(5), nargs=\"+\", required=True ) for additional_arg", "os.path.join(\"..\", \"topologies\", problem_name) for model in TM_MODELS: for tm_fname in iglob( \"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model, problem_name)", "choices=range(5), nargs=\"+\", required=True ) for additional_arg in additional_args: name_or_flags, kwargs = additional_arg[0], additional_arg[1]", "3), \"Kdl.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"erdos-renyi-1260231677.json\": (4, True, \"inv-cap\", FMPartitioning, 3),", "scale_factor)].append( (topo_fname, tm_fname) ) HOLDOUT_PROBLEMS.append((problem_name, topo_fname, tm_fname)) GROUPED_BY_PROBLEMS = dict(GROUPED_BY_PROBLEMS) for key, vals", "NCFLOW_HYPERPARAMS = { \"GtsCe.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"UsCarrier.graphml\": (4, True, \"inv-cap\",", "<gh_stars>10-100 from collections import defaultdict from glob import iglob import argparse import os", "in GROUPED_BY_PROBLEMS.items(): GROUPED_BY_PROBLEMS[key] = sorted(vals) GROUPED_BY_HOLDOUT_PROBLEMS = dict(GROUPED_BY_HOLDOUT_PROBLEMS) for key, vals in GROUPED_BY_HOLDOUT_PROBLEMS.items():", "or problem_name in args.topos) and (\"all\" in args.tm_models or tm_model in args.tm_models) and", "for additional_arg in additional_args: name_or_flags, kwargs = additional_arg[0], additional_arg[1] parser.add_argument(name_or_flags, **kwargs) args =", "\"inv-cap\", FMPartitioning, 3), \"Kdl.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"erdos-renyi-1260231677.json\": (4, True, \"inv-cap\",", "\"topologies\", problem_name) for model in TM_MODELS: for tm_fname in iglob( \"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model, problem_name) ):", "\"--scale-factors\", type=lambda x: x if x == \"all\" else float(x), choices=SCALE_FACTORS + [\"all\"],", "FMPartitioning, 3), \"UsCarrier.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Cogentco.graphml\": (4, True, \"inv-cap\", FMPartitioning,", "(4, True, \"inv-cap\") NCFLOW_HYPERPARAMS = { \"GtsCe.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"UsCarrier.graphml\":", "(4, True, \"inv-cap\", FMPartitioning, 3), \"DialtelecomCz.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Uninett2010.graphml\": (4,", "True, \"inv-cap\", FMPartitioning, 3), \"erdos-renyi-1260231677.json\": (4, True, \"inv-cap\", FMPartitioning, 3), } PROBLEM_NAMES_AND_TM_MODELS =", "FMPartitioning, SpectralClustering PROBLEM_NAMES = [ \"GtsCe.graphml\", \"UsCarrier.graphml\", \"Cogentco.graphml\", \"Colt.graphml\", \"TataNld.graphml\", \"Deltacom.graphml\", \"DialtelecomCz.graphml\", \"Kdl.graphml\",", "GROUPED_BY_PROBLEMS[key] = sorted(vals) GROUPED_BY_HOLDOUT_PROBLEMS = dict(GROUPED_BY_HOLDOUT_PROBLEMS) for key, vals in GROUPED_BY_HOLDOUT_PROBLEMS.items(): GROUPED_BY_HOLDOUT_PROBLEMS[key] =", "\"TataNld.graphml\", \"Deltacom.graphml\", \"DialtelecomCz.graphml\", \"Kdl.graphml\", ] TM_MODELS = [ \"uniform\", \"gravity\", \"bimodal\", \"poisson-high-intra\", \"poisson-high-inter\",", "8.0, 16.0, 32.0, 64.0, 128.0] PATH_FORM_HYPERPARAMS = (4, True, \"inv-cap\") NCFLOW_HYPERPARAMS = {", "\"inv-cap\") NCFLOW_HYPERPARAMS = { \"GtsCe.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"UsCarrier.graphml\": (4, True,", "get_problems(args): problems = [] for ( (problem_name, tm_model, scale_factor), topo_and_tm_fnames, ) in GROUPED_BY_PROBLEMS.items():", "+ [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--topos\", type=str, choices=PROBLEM_NAMES + [\"all\"], nargs=\"+\", default=\"all\",", "problems = [] for ( (problem_name, tm_model, scale_factor), topo_and_tm_fnames, ) in GROUPED_BY_PROBLEMS.items(): for", "FMPartitioning, 3), \"Kdl.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"erdos-renyi-1260231677.json\": (4, True, \"inv-cap\", FMPartitioning,", "tm_fname in iglob( \"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model, problem_name) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor =", "tm_fname = topo_and_tm_fnames[slice] problems.append((problem_name, topo_fname, tm_fname)) return problems def get_args_and_problems(output_csv_template, additional_args=[]): parser =", "\"TataNld.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Deltacom.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"DialtelecomCz.graphml\":", "def get_args_and_problems(output_csv_template, additional_args=[]): parser = argparse.ArgumentParser() parser.add_argument(\"--dry-run\", dest=\"dry_run\", action=\"store_true\", default=False) parser.add_argument(\"--obj\", type=str, choices=[\"total_flow\",", "args.tm_models or tm_model in args.tm_models) and (\"all\" in args.scale_factors or scale_factor in args.scale_factors)", "[ \"uniform\", \"gravity\", \"bimodal\", \"poisson-high-intra\", \"poisson-high-inter\", ] SCALE_FACTORS = [1.0, 2.0, 4.0, 8.0,", ") for additional_arg in additional_args: name_or_flags, kwargs = additional_arg[0], additional_arg[1] parser.add_argument(name_or_flags, **kwargs) args", "= defaultdict(list) for problem_name in PROBLEM_NAMES: if problem_name.endswith(\".graphml\"): topo_fname = os.path.join(\"..\", \"topologies\", \"topology-zoo\",", "\"uniform\", \"gravity\", \"bimodal\", \"poisson-high-intra\", \"poisson-high-inter\", ] SCALE_FACTORS = [1.0, 2.0, 4.0, 8.0, 16.0,", "tm_model, scale_factor), topo_and_tm_fnames, ) in GROUPED_BY_PROBLEMS.items(): for slice in args.slices: if ( (\"all\"", "for key, vals in GROUPED_BY_HOLDOUT_PROBLEMS.items(): GROUPED_BY_HOLDOUT_PROBLEMS[key] = sorted(vals) def get_problems(args): problems = []", "or tm_model in args.tm_models) and (\"all\" in args.scale_factors or scale_factor in args.scale_factors) ):", "parser.add_argument( \"--scale-factors\", type=lambda x: x if x == \"all\" else float(x), choices=SCALE_FACTORS +", "parser.parse_args() slice_str = \"slice_\" + \"_\".join(str(i) for i in args.slices) output_csv = output_csv_template.format(args.obj,", "required=True) parser.add_argument( \"--tm-models\", type=str, choices=TM_MODELS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--topos\", type=str,", "slice in args.slices: if ( (\"all\" in args.topos or problem_name in args.topos) and", "{ \"GtsCe.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"UsCarrier.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3),", "[] GROUPED_BY_PROBLEMS = defaultdict(list) HOLDOUT_PROBLEMS = [] GROUPED_BY_HOLDOUT_PROBLEMS = defaultdict(list) for problem_name in", "\"Cogentco.graphml\", \"Colt.graphml\", \"TataNld.graphml\", \"Deltacom.graphml\", \"DialtelecomCz.graphml\", \"Kdl.graphml\", ] TM_MODELS = [ \"uniform\", \"gravity\", \"bimodal\",", "+ [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--slices\", type=int, choices=range(5), nargs=\"+\", required=True ) for", "topo_fname, tm_fname)) return problems def get_args_and_problems(output_csv_template, additional_args=[]): parser = argparse.ArgumentParser() parser.add_argument(\"--dry-run\", dest=\"dry_run\", action=\"store_true\",", "= { \"GtsCe.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"UsCarrier.graphml\": (4, True, \"inv-cap\", FMPartitioning,", "GROUPED_BY_PROBLEMS.items(): GROUPED_BY_PROBLEMS[key] = sorted(vals) GROUPED_BY_HOLDOUT_PROBLEMS = dict(GROUPED_BY_HOLDOUT_PROBLEMS) for key, vals in GROUPED_BY_HOLDOUT_PROBLEMS.items(): GROUPED_BY_HOLDOUT_PROBLEMS[key]", "SpectralClustering PROBLEM_NAMES = [ \"GtsCe.graphml\", \"UsCarrier.graphml\", \"Cogentco.graphml\", \"Colt.graphml\", \"TataNld.graphml\", \"Deltacom.graphml\", \"DialtelecomCz.graphml\", \"Kdl.graphml\", ]", "( (\"all\" in args.topos or problem_name in args.topos) and (\"all\" in args.tm_models or", "choices=[\"total_flow\", \"mcf\"], required=True) parser.add_argument( \"--tm-models\", type=str, choices=TM_MODELS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument(", "\"slice_\" + \"_\".join(str(i) for i in args.slices) output_csv = output_csv_template.format(args.obj, slice_str) return args,", "= \"slice_\" + \"_\".join(str(i) for i in args.slices) output_csv = output_csv_template.format(args.obj, slice_str) return", "os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname)", "\"inv-cap\", FMPartitioning, 3), \"Cogentco.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Colt.graphml\": (4, True, \"inv-cap\",", "= argparse.ArgumentParser() parser.add_argument(\"--dry-run\", dest=\"dry_run\", action=\"store_true\", default=False) parser.add_argument(\"--obj\", type=str, choices=[\"total_flow\", \"mcf\"], required=True) parser.add_argument( \"--tm-models\",", "scale_factor in args.scale_factors) ): topo_fname, tm_fname = topo_and_tm_fnames[slice] problems.append((problem_name, topo_fname, tm_fname)) return problems", "True, \"inv-cap\", FMPartitioning, 3), \"Kdl.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"erdos-renyi-1260231677.json\": (4, True,", "= parser.parse_args() slice_str = \"slice_\" + \"_\".join(str(i) for i in args.slices) output_csv =", "additional_arg in additional_args: name_or_flags, kwargs = additional_arg[0], additional_arg[1] parser.add_argument(name_or_flags, **kwargs) args = parser.parse_args()", "GROUPED_BY_HOLDOUT_PROBLEMS[key] = sorted(vals) def get_problems(args): problems = [] for ( (problem_name, tm_model, scale_factor),", "in TM_MODELS ] PROBLEMS = [] GROUPED_BY_PROBLEMS = defaultdict(list) HOLDOUT_PROBLEMS = [] GROUPED_BY_HOLDOUT_PROBLEMS", "FMPartitioning, 3), \"TataNld.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Deltacom.graphml\": (4, True, \"inv-cap\", FMPartitioning,", "x: x if x == \"all\" else float(x), choices=SCALE_FACTORS + [\"all\"], nargs=\"+\", default=\"all\",", "\"poisson-high-inter\", ] SCALE_FACTORS = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0] PATH_FORM_HYPERPARAMS", "for tm_model in TM_MODELS ] PROBLEMS = [] GROUPED_BY_PROBLEMS = defaultdict(list) HOLDOUT_PROBLEMS =", "from glob import iglob import argparse import os import sys sys.path.append(\"..\") from lib.partitioning", "\"--tm-models\", type=str, choices=TM_MODELS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--topos\", type=str, choices=PROBLEM_NAMES +", "scale_factor)].append( (topo_fname, tm_fname) ) PROBLEMS.append((problem_name, topo_fname, tm_fname)) for tm_fname in iglob( \"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format( model,", "in GROUPED_BY_PROBLEMS.items(): for slice in args.slices: if ( (\"all\" in args.topos or problem_name", "(4, True, \"inv-cap\", FMPartitioning, 3), \"Uninett2010.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Interoute.graphml\": (4,", "kwargs = additional_arg[0], additional_arg[1] parser.add_argument(name_or_flags, **kwargs) args = parser.parse_args() slice_str = \"slice_\" +", "import argparse import os import sys sys.path.append(\"..\") from lib.partitioning import FMPartitioning, SpectralClustering PROBLEM_NAMES", "nargs=\"+\", required=True ) for additional_arg in additional_args: name_or_flags, kwargs = additional_arg[0], additional_arg[1] parser.add_argument(name_or_flags,", "additional_arg[0], additional_arg[1] parser.add_argument(name_or_flags, **kwargs) args = parser.parse_args() slice_str = \"slice_\" + \"_\".join(str(i) for", "vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) HOLDOUT_PROBLEMS.append((problem_name, topo_fname, tm_fname)) GROUPED_BY_PROBLEMS", "in args.slices) output_csv = output_csv_template.format(args.obj, slice_str) return args, output_csv, get_problems(args) def print_(*args, file=None):", "problem_name.endswith(\".graphml\"): topo_fname = os.path.join(\"..\", \"topologies\", \"topology-zoo\", problem_name) else: topo_fname = os.path.join(\"..\", \"topologies\", problem_name)", "True, \"inv-cap\", FMPartitioning, 3), \"Cogentco.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Colt.graphml\": (4, True,", "type=str, choices=[\"total_flow\", \"mcf\"], required=True) parser.add_argument( \"--tm-models\", type=str, choices=TM_MODELS + [\"all\"], nargs=\"+\", default=\"all\", )", "for i in args.slices) output_csv = output_csv_template.format(args.obj, slice_str) return args, output_csv, get_problems(args) def", "\"GtsCe.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"UsCarrier.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Cogentco.graphml\":", "\"erdos-renyi-1260231677.json\": (4, True, \"inv-cap\", FMPartitioning, 3), } PROBLEM_NAMES_AND_TM_MODELS = [ (prob_name, tm_model) for", "3), \"Colt.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"TataNld.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3),", "def get_problems(args): problems = [] for ( (problem_name, tm_model, scale_factor), topo_and_tm_fnames, ) in", "True, \"inv-cap\", FMPartitioning, 3), \"Uninett2010.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Interoute.graphml\": (4, True,", "for prob_name in PROBLEM_NAMES for tm_model in TM_MODELS ] PROBLEMS = [] GROUPED_BY_PROBLEMS", "get_args_and_problems(output_csv_template, additional_args=[]): parser = argparse.ArgumentParser() parser.add_argument(\"--dry-run\", dest=\"dry_run\", action=\"store_true\", default=False) parser.add_argument(\"--obj\", type=str, choices=[\"total_flow\", \"mcf\"],", "choices=TM_MODELS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--topos\", type=str, choices=PROBLEM_NAMES + [\"all\"], nargs=\"+\",", "2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0] PATH_FORM_HYPERPARAMS = (4, True, \"inv-cap\") NCFLOW_HYPERPARAMS", "if ( (\"all\" in args.topos or problem_name in args.topos) and (\"all\" in args.tm_models", "problem_name) else: topo_fname = os.path.join(\"..\", \"topologies\", problem_name) for model in TM_MODELS: for tm_fname", "problems def get_args_and_problems(output_csv_template, additional_args=[]): parser = argparse.ArgumentParser() parser.add_argument(\"--dry-run\", dest=\"dry_run\", action=\"store_true\", default=False) parser.add_argument(\"--obj\", type=str,", "4.0, 8.0, 16.0, 32.0, 64.0, 128.0] PATH_FORM_HYPERPARAMS = (4, True, \"inv-cap\") NCFLOW_HYPERPARAMS =", "True, \"inv-cap\", FMPartitioning, 3), \"Interoute.graphml\": (4, True, \"inv-cap\", SpectralClustering, 2), \"Ion.graphml\": (4, True,", "(\"all\" in args.scale_factors or scale_factor in args.scale_factors) ): topo_fname, tm_fname = topo_and_tm_fnames[slice] problems.append((problem_name,", "): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_PROBLEMS[(problem_name, model,", "\"DialtelecomCz.graphml\", \"Kdl.graphml\", ] TM_MODELS = [ \"uniform\", \"gravity\", \"bimodal\", \"poisson-high-intra\", \"poisson-high-inter\", ] SCALE_FACTORS", "float(vals[3]) GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) HOLDOUT_PROBLEMS.append((problem_name, topo_fname, tm_fname)) GROUPED_BY_PROBLEMS = dict(GROUPED_BY_PROBLEMS)", "i in args.slices) output_csv = output_csv_template.format(args.obj, slice_str) return args, output_csv, get_problems(args) def print_(*args,", "\"poisson-high-intra\", \"poisson-high-inter\", ] SCALE_FACTORS = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0]", "\"UsCarrier.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Cogentco.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Colt.graphml\":", "defaultdict(list) for problem_name in PROBLEM_NAMES: if problem_name.endswith(\".graphml\"): topo_fname = os.path.join(\"..\", \"topologies\", \"topology-zoo\", problem_name)", "= os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname,", "args.topos) and (\"all\" in args.tm_models or tm_model in args.tm_models) and (\"all\" in args.scale_factors", "in GROUPED_BY_HOLDOUT_PROBLEMS.items(): GROUPED_BY_HOLDOUT_PROBLEMS[key] = sorted(vals) def get_problems(args): problems = [] for ( (problem_name,", "topo_and_tm_fnames[slice] problems.append((problem_name, topo_fname, tm_fname)) return problems def get_args_and_problems(output_csv_template, additional_args=[]): parser = argparse.ArgumentParser() parser.add_argument(\"--dry-run\",", "in iglob( \"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format( model, problem_name ) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor", "defaultdict(list) HOLDOUT_PROBLEMS = [] GROUPED_BY_HOLDOUT_PROBLEMS = defaultdict(list) for problem_name in PROBLEM_NAMES: if problem_name.endswith(\".graphml\"):", "tm_fname)) GROUPED_BY_PROBLEMS = dict(GROUPED_BY_PROBLEMS) for key, vals in GROUPED_BY_PROBLEMS.items(): GROUPED_BY_PROBLEMS[key] = sorted(vals) GROUPED_BY_HOLDOUT_PROBLEMS", "float(vals[3]) GROUPED_BY_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) PROBLEMS.append((problem_name, topo_fname, tm_fname)) for tm_fname in", "\"Colt.graphml\", \"TataNld.graphml\", \"Deltacom.graphml\", \"DialtelecomCz.graphml\", \"Kdl.graphml\", ] TM_MODELS = [ \"uniform\", \"gravity\", \"bimodal\", \"poisson-high-intra\",", "GROUPED_BY_HOLDOUT_PROBLEMS.items(): GROUPED_BY_HOLDOUT_PROBLEMS[key] = sorted(vals) def get_problems(args): problems = [] for ( (problem_name, tm_model,", "return args, output_csv, get_problems(args) def print_(*args, file=None): if file is None: file =", "= output_csv_template.format(args.obj, slice_str) return args, output_csv, get_problems(args) def print_(*args, file=None): if file is", "\"inv-cap\", FMPartitioning, 3), \"Interoute.graphml\": (4, True, \"inv-cap\", SpectralClustering, 2), \"Ion.graphml\": (4, True, \"inv-cap\",", "slice_str = \"slice_\" + \"_\".join(str(i) for i in args.slices) output_csv = output_csv_template.format(args.obj, slice_str)", "HOLDOUT_PROBLEMS = [] GROUPED_BY_HOLDOUT_PROBLEMS = defaultdict(list) for problem_name in PROBLEM_NAMES: if problem_name.endswith(\".graphml\"): topo_fname", "output_csv, get_problems(args) def print_(*args, file=None): if file is None: file = sys.stdout print(*args,", "args, output_csv, get_problems(args) def print_(*args, file=None): if file is None: file = sys.stdout", "32.0, 64.0, 128.0] PATH_FORM_HYPERPARAMS = (4, True, \"inv-cap\") NCFLOW_HYPERPARAMS = { \"GtsCe.graphml\": (4,", "(4, True, \"inv-cap\", FMPartitioning, 3), \"UsCarrier.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Cogentco.graphml\": (4,", "\"inv-cap\", FMPartitioning, 3), \"Uninett2010.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Interoute.graphml\": (4, True, \"inv-cap\",", "nargs=\"+\", default=\"all\", ) parser.add_argument( \"--scale-factors\", type=lambda x: x if x == \"all\" else", "default=False) parser.add_argument(\"--obj\", type=str, choices=[\"total_flow\", \"mcf\"], required=True) parser.add_argument( \"--tm-models\", type=str, choices=TM_MODELS + [\"all\"], nargs=\"+\",", "in args.scale_factors) ): topo_fname, tm_fname = topo_and_tm_fnames[slice] problems.append((problem_name, topo_fname, tm_fname)) return problems def", "3), \"Interoute.graphml\": (4, True, \"inv-cap\", SpectralClustering, 2), \"Ion.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3),", "\"inv-cap\", FMPartitioning, 3), \"Colt.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"TataNld.graphml\": (4, True, \"inv-cap\",", "= os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname,", "\"Colt.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"TataNld.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Deltacom.graphml\":", "\"Kdl.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"erdos-renyi-1260231677.json\": (4, True, \"inv-cap\", FMPartitioning, 3), }", "in args.topos or problem_name in args.topos) and (\"all\" in args.tm_models or tm_model in", "TM_MODELS = [ \"uniform\", \"gravity\", \"bimodal\", \"poisson-high-intra\", \"poisson-high-inter\", ] SCALE_FACTORS = [1.0, 2.0,", "if problem_name.endswith(\".graphml\"): topo_fname = os.path.join(\"..\", \"topologies\", \"topology-zoo\", problem_name) else: topo_fname = os.path.join(\"..\", \"topologies\",", "3), \"Deltacom.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"DialtelecomCz.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3),", "parser.add_argument(\"--dry-run\", dest=\"dry_run\", action=\"store_true\", default=False) parser.add_argument(\"--obj\", type=str, choices=[\"total_flow\", \"mcf\"], required=True) parser.add_argument( \"--tm-models\", type=str, choices=TM_MODELS", "in PROBLEM_NAMES for tm_model in TM_MODELS ] PROBLEMS = [] GROUPED_BY_PROBLEMS = defaultdict(list)", "in args.scale_factors or scale_factor in args.scale_factors) ): topo_fname, tm_fname = topo_and_tm_fnames[slice] problems.append((problem_name, topo_fname,", "(4, True, \"inv-cap\", FMPartitioning, 3), \"TataNld.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Deltacom.graphml\": (4,", "True, \"inv-cap\", FMPartitioning, 3), \"TataNld.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Deltacom.graphml\": (4, True,", "] TM_MODELS = [ \"uniform\", \"gravity\", \"bimodal\", \"poisson-high-intra\", \"poisson-high-inter\", ] SCALE_FACTORS = [1.0,", "traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) PROBLEMS.append((problem_name,", "prob_name in PROBLEM_NAMES for tm_model in TM_MODELS ] PROBLEMS = [] GROUPED_BY_PROBLEMS =", "os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname)", "FMPartitioning, 3), \"erdos-renyi-1260231677.json\": (4, True, \"inv-cap\", FMPartitioning, 3), } PROBLEM_NAMES_AND_TM_MODELS = [ (prob_name,", "3), \"erdos-renyi-1260231677.json\": (4, True, \"inv-cap\", FMPartitioning, 3), } PROBLEM_NAMES_AND_TM_MODELS = [ (prob_name, tm_model)", "in args.topos) and (\"all\" in args.tm_models or tm_model in args.tm_models) and (\"all\" in", "defaultdict from glob import iglob import argparse import os import sys sys.path.append(\"..\") from", "SpectralClustering, 2), \"Ion.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Kdl.graphml\": (4, True, \"inv-cap\", FMPartitioning,", "True, \"inv-cap\", FMPartitioning, 3), \"DialtelecomCz.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Uninett2010.graphml\": (4, True,", "in PROBLEM_NAMES: if problem_name.endswith(\".graphml\"): topo_fname = os.path.join(\"..\", \"topologies\", \"topology-zoo\", problem_name) else: topo_fname =", "slice_str) return args, output_csv, get_problems(args) def print_(*args, file=None): if file is None: file", "topo_fname = os.path.join(\"..\", \"topologies\", \"topology-zoo\", problem_name) else: topo_fname = os.path.join(\"..\", \"topologies\", problem_name) for", "parser.add_argument(\"--obj\", type=str, choices=[\"total_flow\", \"mcf\"], required=True) parser.add_argument( \"--tm-models\", type=str, choices=TM_MODELS + [\"all\"], nargs=\"+\", default=\"all\",", "parser.add_argument(name_or_flags, **kwargs) args = parser.parse_args() slice_str = \"slice_\" + \"_\".join(str(i) for i in", "3), \"TataNld.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Deltacom.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3),", "iglob( \"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format( model, problem_name ) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor =", ") ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name,", "scale_factor), topo_and_tm_fnames, ) in GROUPED_BY_PROBLEMS.items(): for slice in args.slices: if ( (\"all\" in", "FMPartitioning, 3), \"Deltacom.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"DialtelecomCz.graphml\": (4, True, \"inv-cap\", FMPartitioning,", "default=\"all\", ) parser.add_argument( \"--topos\", type=str, choices=PROBLEM_NAMES + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--scale-factors\",", "tm_model in args.tm_models) and (\"all\" in args.scale_factors or scale_factor in args.scale_factors) ): topo_fname,", "choices=PROBLEM_NAMES + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--scale-factors\", type=lambda x: x if x", "in TM_MODELS: for tm_fname in iglob( \"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model, problem_name) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _,", "FMPartitioning, 3), \"Cogentco.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Colt.graphml\": (4, True, \"inv-cap\", FMPartitioning,", "[ \"GtsCe.graphml\", \"UsCarrier.graphml\", \"Cogentco.graphml\", \"Colt.graphml\", \"TataNld.graphml\", \"Deltacom.graphml\", \"DialtelecomCz.graphml\", \"Kdl.graphml\", ] TM_MODELS = [", "key, vals in GROUPED_BY_HOLDOUT_PROBLEMS.items(): GROUPED_BY_HOLDOUT_PROBLEMS[key] = sorted(vals) def get_problems(args): problems = [] for", "nargs=\"+\", default=\"all\", ) parser.add_argument( \"--topos\", type=str, choices=PROBLEM_NAMES + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument(", "for tm_fname in iglob( \"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format( model, problem_name ) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _,", ") PROBLEMS.append((problem_name, topo_fname, tm_fname)) for tm_fname in iglob( \"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format( model, problem_name ) ):", "PROBLEMS = [] GROUPED_BY_PROBLEMS = defaultdict(list) HOLDOUT_PROBLEMS = [] GROUPED_BY_HOLDOUT_PROBLEMS = defaultdict(list) for", "iglob import argparse import os import sys sys.path.append(\"..\") from lib.partitioning import FMPartitioning, SpectralClustering", "output_csv = output_csv_template.format(args.obj, slice_str) return args, output_csv, get_problems(args) def print_(*args, file=None): if file", "\"inv-cap\", FMPartitioning, 3), \"erdos-renyi-1260231677.json\": (4, True, \"inv-cap\", FMPartitioning, 3), } PROBLEM_NAMES_AND_TM_MODELS = [", "= dict(GROUPED_BY_PROBLEMS) for key, vals in GROUPED_BY_PROBLEMS.items(): GROUPED_BY_PROBLEMS[key] = sorted(vals) GROUPED_BY_HOLDOUT_PROBLEMS = dict(GROUPED_BY_HOLDOUT_PROBLEMS)", "\"inv-cap\", FMPartitioning, 3), } PROBLEM_NAMES_AND_TM_MODELS = [ (prob_name, tm_model) for prob_name in PROBLEM_NAMES", "and (\"all\" in args.scale_factors or scale_factor in args.scale_factors) ): topo_fname, tm_fname = topo_and_tm_fnames[slice]", "required=True ) for additional_arg in additional_args: name_or_flags, kwargs = additional_arg[0], additional_arg[1] parser.add_argument(name_or_flags, **kwargs)", "\"gravity\", \"bimodal\", \"poisson-high-intra\", \"poisson-high-inter\", ] SCALE_FACTORS = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0,", "(4, True, \"inv-cap\", FMPartitioning, 3), \"erdos-renyi-1260231677.json\": (4, True, \"inv-cap\", FMPartitioning, 3), } PROBLEM_NAMES_AND_TM_MODELS", "FMPartitioning, 3), \"Colt.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"TataNld.graphml\": (4, True, \"inv-cap\", FMPartitioning,", "(4, True, \"inv-cap\", FMPartitioning, 3), \"Interoute.graphml\": (4, True, \"inv-cap\", SpectralClustering, 2), \"Ion.graphml\": (4,", "(4, True, \"inv-cap\", FMPartitioning, 3), \"Colt.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"TataNld.graphml\": (4,", "= vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) PROBLEMS.append((problem_name, topo_fname, tm_fname))", "PROBLEM_NAMES_AND_TM_MODELS = [ (prob_name, tm_model) for prob_name in PROBLEM_NAMES for tm_model in TM_MODELS", "vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) PROBLEMS.append((problem_name, topo_fname, tm_fname)) for", "(topo_fname, tm_fname) ) HOLDOUT_PROBLEMS.append((problem_name, topo_fname, tm_fname)) GROUPED_BY_PROBLEMS = dict(GROUPED_BY_PROBLEMS) for key, vals in", "\"_\".join(str(i) for i in args.slices) output_csv = output_csv_template.format(args.obj, slice_str) return args, output_csv, get_problems(args)", "] SCALE_FACTORS = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0] PATH_FORM_HYPERPARAMS =", "dict(GROUPED_BY_HOLDOUT_PROBLEMS) for key, vals in GROUPED_BY_HOLDOUT_PROBLEMS.items(): GROUPED_BY_HOLDOUT_PROBLEMS[key] = sorted(vals) def get_problems(args): problems =", "argparse import os import sys sys.path.append(\"..\") from lib.partitioning import FMPartitioning, SpectralClustering PROBLEM_NAMES =", "FMPartitioning, 3), \"Uninett2010.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Interoute.graphml\": (4, True, \"inv-cap\", SpectralClustering,", "default=\"all\", ) parser.add_argument( \"--scale-factors\", type=lambda x: x if x == \"all\" else float(x),", "x == \"all\" else float(x), choices=SCALE_FACTORS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--slices\",", "topo_fname = os.path.join(\"..\", \"topologies\", problem_name) for model in TM_MODELS: for tm_fname in iglob(", "return problems def get_args_and_problems(output_csv_template, additional_args=[]): parser = argparse.ArgumentParser() parser.add_argument(\"--dry-run\", dest=\"dry_run\", action=\"store_true\", default=False) parser.add_argument(\"--obj\",", "True, \"inv-cap\", FMPartitioning, 3), } PROBLEM_NAMES_AND_TM_MODELS = [ (prob_name, tm_model) for prob_name in", "args.slices) output_csv = output_csv_template.format(args.obj, slice_str) return args, output_csv, get_problems(args) def print_(*args, file=None): if", "problem_name) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_PROBLEMS[(problem_name,", "\"Interoute.graphml\": (4, True, \"inv-cap\", SpectralClustering, 2), \"Ion.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Kdl.graphml\":", "in additional_args: name_or_flags, kwargs = additional_arg[0], additional_arg[1] parser.add_argument(name_or_flags, **kwargs) args = parser.parse_args() slice_str", "(4, True, \"inv-cap\", FMPartitioning, 3), \"Cogentco.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Colt.graphml\": (4,", "= (4, True, \"inv-cap\") NCFLOW_HYPERPARAMS = { \"GtsCe.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3),", "key, vals in GROUPED_BY_PROBLEMS.items(): GROUPED_BY_PROBLEMS[key] = sorted(vals) GROUPED_BY_HOLDOUT_PROBLEMS = dict(GROUPED_BY_HOLDOUT_PROBLEMS) for key, vals", "vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_PROBLEMS[(problem_name, model, scale_factor)].append(", "(\"all\" in args.topos or problem_name in args.topos) and (\"all\" in args.tm_models or tm_model", "): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name, model,", "[\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--scale-factors\", type=lambda x: x if x == \"all\"", "\"Deltacom.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"DialtelecomCz.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Uninett2010.graphml\":", "3), \"UsCarrier.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Cogentco.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3),", "dict(GROUPED_BY_PROBLEMS) for key, vals in GROUPED_BY_PROBLEMS.items(): GROUPED_BY_PROBLEMS[key] = sorted(vals) GROUPED_BY_HOLDOUT_PROBLEMS = dict(GROUPED_BY_HOLDOUT_PROBLEMS) for", "args.slices: if ( (\"all\" in args.topos or problem_name in args.topos) and (\"all\" in", "+ [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--scale-factors\", type=lambda x: x if x ==", "(prob_name, tm_model) for prob_name in PROBLEM_NAMES for tm_model in TM_MODELS ] PROBLEMS =", "additional_arg[1] parser.add_argument(name_or_flags, **kwargs) args = parser.parse_args() slice_str = \"slice_\" + \"_\".join(str(i) for i", "args.scale_factors) ): topo_fname, tm_fname = topo_and_tm_fnames[slice] problems.append((problem_name, topo_fname, tm_fname)) return problems def get_args_and_problems(output_csv_template,", "else: topo_fname = os.path.join(\"..\", \"topologies\", problem_name) for model in TM_MODELS: for tm_fname in", "problem_name) for model in TM_MODELS: for tm_fname in iglob( \"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model, problem_name) ): vals", "parser.add_argument( \"--slices\", type=int, choices=range(5), nargs=\"+\", required=True ) for additional_arg in additional_args: name_or_flags, kwargs", "= [ \"uniform\", \"gravity\", \"bimodal\", \"poisson-high-intra\", \"poisson-high-inter\", ] SCALE_FACTORS = [1.0, 2.0, 4.0,", "type=int, choices=range(5), nargs=\"+\", required=True ) for additional_arg in additional_args: name_or_flags, kwargs = additional_arg[0],", "output_csv_template.format(args.obj, slice_str) return args, output_csv, get_problems(args) def print_(*args, file=None): if file is None:", "for model in TM_MODELS: for tm_fname in iglob( \"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model, problem_name) ): vals =", "+ \"_\".join(str(i) for i in args.slices) output_csv = output_csv_template.format(args.obj, slice_str) return args, output_csv,", "): topo_fname, tm_fname = topo_and_tm_fnames[slice] problems.append((problem_name, topo_fname, tm_fname)) return problems def get_args_and_problems(output_csv_template, additional_args=[]):", "for tm_fname in iglob( \"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model, problem_name) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor", "os.path.join(\"..\", \"topologies\", \"topology-zoo\", problem_name) else: topo_fname = os.path.join(\"..\", \"topologies\", problem_name) for model in", "topo_and_tm_fnames, ) in GROUPED_BY_PROBLEMS.items(): for slice in args.slices: if ( (\"all\" in args.topos", "vals in GROUPED_BY_HOLDOUT_PROBLEMS.items(): GROUPED_BY_HOLDOUT_PROBLEMS[key] = sorted(vals) def get_problems(args): problems = [] for (", "dest=\"dry_run\", action=\"store_true\", default=False) parser.add_argument(\"--obj\", type=str, choices=[\"total_flow\", \"mcf\"], required=True) parser.add_argument( \"--tm-models\", type=str, choices=TM_MODELS +", "_, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) )", "2), \"Ion.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Kdl.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3),", "\"Cogentco.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Colt.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"TataNld.graphml\":", "model, scale_factor)].append( (topo_fname, tm_fname) ) HOLDOUT_PROBLEMS.append((problem_name, topo_fname, tm_fname)) GROUPED_BY_PROBLEMS = dict(GROUPED_BY_PROBLEMS) for key,", "args.tm_models) and (\"all\" in args.scale_factors or scale_factor in args.scale_factors) ): topo_fname, tm_fname =", "choices=SCALE_FACTORS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--slices\", type=int, choices=range(5), nargs=\"+\", required=True )", "= os.path.join(\"..\", \"topologies\", problem_name) for model in TM_MODELS: for tm_fname in iglob( \"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model,", "x if x == \"all\" else float(x), choices=SCALE_FACTORS + [\"all\"], nargs=\"+\", default=\"all\", )", "[ (prob_name, tm_model) for prob_name in PROBLEM_NAMES for tm_model in TM_MODELS ] PROBLEMS", "type=str, choices=PROBLEM_NAMES + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--scale-factors\", type=lambda x: x if", "os import sys sys.path.append(\"..\") from lib.partitioning import FMPartitioning, SpectralClustering PROBLEM_NAMES = [ \"GtsCe.graphml\",", "= [] for ( (problem_name, tm_model, scale_factor), topo_and_tm_fnames, ) in GROUPED_BY_PROBLEMS.items(): for slice", "and (\"all\" in args.tm_models or tm_model in args.tm_models) and (\"all\" in args.scale_factors or", "import defaultdict from glob import iglob import argparse import os import sys sys.path.append(\"..\")", "\"inv-cap\", FMPartitioning, 3), \"TataNld.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Deltacom.graphml\": (4, True, \"inv-cap\",", ") parser.add_argument( \"--scale-factors\", type=lambda x: x if x == \"all\" else float(x), choices=SCALE_FACTORS", "TM_MODELS ] PROBLEMS = [] GROUPED_BY_PROBLEMS = defaultdict(list) HOLDOUT_PROBLEMS = [] GROUPED_BY_HOLDOUT_PROBLEMS =", "scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) PROBLEMS.append((problem_name, topo_fname,", "GROUPED_BY_PROBLEMS = dict(GROUPED_BY_PROBLEMS) for key, vals in GROUPED_BY_PROBLEMS.items(): GROUPED_BY_PROBLEMS[key] = sorted(vals) GROUPED_BY_HOLDOUT_PROBLEMS =", "or scale_factor in args.scale_factors) ): topo_fname, tm_fname = topo_and_tm_fnames[slice] problems.append((problem_name, topo_fname, tm_fname)) return", "\"topologies\", \"topology-zoo\", problem_name) else: topo_fname = os.path.join(\"..\", \"topologies\", problem_name) for model in TM_MODELS:", "3), \"Uninett2010.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Interoute.graphml\": (4, True, \"inv-cap\", SpectralClustering, 2),", "\"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model, problem_name) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3])", "(4, True, \"inv-cap\", FMPartitioning, 3), \"Kdl.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"erdos-renyi-1260231677.json\": (4,", "\"UsCarrier.graphml\", \"Cogentco.graphml\", \"Colt.graphml\", \"TataNld.graphml\", \"Deltacom.graphml\", \"DialtelecomCz.graphml\", \"Kdl.graphml\", ] TM_MODELS = [ \"uniform\", \"gravity\",", "int(vals[2]), float(vals[3]) GROUPED_BY_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) PROBLEMS.append((problem_name, topo_fname, tm_fname)) for tm_fname", "PROBLEM_NAMES: if problem_name.endswith(\".graphml\"): topo_fname = os.path.join(\"..\", \"topologies\", \"topology-zoo\", problem_name) else: topo_fname = os.path.join(\"..\",", "glob import iglob import argparse import os import sys sys.path.append(\"..\") from lib.partitioning import", "default=\"all\", ) parser.add_argument( \"--slices\", type=int, choices=range(5), nargs=\"+\", required=True ) for additional_arg in additional_args:", "model, scale_factor)].append( (topo_fname, tm_fname) ) PROBLEMS.append((problem_name, topo_fname, tm_fname)) for tm_fname in iglob( \"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format(", "topo_fname, tm_fname = topo_and_tm_fnames[slice] problems.append((problem_name, topo_fname, tm_fname)) return problems def get_args_and_problems(output_csv_template, additional_args=[]): parser", "PROBLEM_NAMES = [ \"GtsCe.graphml\", \"UsCarrier.graphml\", \"Cogentco.graphml\", \"Colt.graphml\", \"TataNld.graphml\", \"Deltacom.graphml\", \"DialtelecomCz.graphml\", \"Kdl.graphml\", ] TM_MODELS", "= [] GROUPED_BY_HOLDOUT_PROBLEMS = defaultdict(list) for problem_name in PROBLEM_NAMES: if problem_name.endswith(\".graphml\"): topo_fname =", "GROUPED_BY_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) PROBLEMS.append((problem_name, topo_fname, tm_fname)) for tm_fname in iglob(", "model, problem_name ) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]),", "parser.add_argument( \"--topos\", type=str, choices=PROBLEM_NAMES + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--scale-factors\", type=lambda x:", "traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) HOLDOUT_PROBLEMS.append((problem_name,", "GROUPED_BY_HOLDOUT_PROBLEMS = defaultdict(list) for problem_name in PROBLEM_NAMES: if problem_name.endswith(\".graphml\"): topo_fname = os.path.join(\"..\", \"topologies\",", "= additional_arg[0], additional_arg[1] parser.add_argument(name_or_flags, **kwargs) args = parser.parse_args() slice_str = \"slice_\" + \"_\".join(str(i)", "== \"all\" else float(x), choices=SCALE_FACTORS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--slices\", type=int,", "args.scale_factors or scale_factor in args.scale_factors) ): topo_fname, tm_fname = topo_and_tm_fnames[slice] problems.append((problem_name, topo_fname, tm_fname))", "= topo_and_tm_fnames[slice] problems.append((problem_name, topo_fname, tm_fname)) return problems def get_args_and_problems(output_csv_template, additional_args=[]): parser = argparse.ArgumentParser()", "[] GROUPED_BY_HOLDOUT_PROBLEMS = defaultdict(list) for problem_name in PROBLEM_NAMES: if problem_name.endswith(\".graphml\"): topo_fname = os.path.join(\"..\",", "additional_args=[]): parser = argparse.ArgumentParser() parser.add_argument(\"--dry-run\", dest=\"dry_run\", action=\"store_true\", default=False) parser.add_argument(\"--obj\", type=str, choices=[\"total_flow\", \"mcf\"], required=True)", "type=lambda x: x if x == \"all\" else float(x), choices=SCALE_FACTORS + [\"all\"], nargs=\"+\",", "argparse.ArgumentParser() parser.add_argument(\"--dry-run\", dest=\"dry_run\", action=\"store_true\", default=False) parser.add_argument(\"--obj\", type=str, choices=[\"total_flow\", \"mcf\"], required=True) parser.add_argument( \"--tm-models\", type=str,", "problem_name in PROBLEM_NAMES: if problem_name.endswith(\".graphml\"): topo_fname = os.path.join(\"..\", \"topologies\", \"topology-zoo\", problem_name) else: topo_fname", "**kwargs) args = parser.parse_args() slice_str = \"slice_\" + \"_\".join(str(i) for i in args.slices)", "True, \"inv-cap\") NCFLOW_HYPERPARAMS = { \"GtsCe.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"UsCarrier.graphml\": (4,", "FMPartitioning, 3), \"DialtelecomCz.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Uninett2010.graphml\": (4, True, \"inv-cap\", FMPartitioning,", "] PROBLEMS = [] GROUPED_BY_PROBLEMS = defaultdict(list) HOLDOUT_PROBLEMS = [] GROUPED_BY_HOLDOUT_PROBLEMS = defaultdict(list)", "action=\"store_true\", default=False) parser.add_argument(\"--obj\", type=str, choices=[\"total_flow\", \"mcf\"], required=True) parser.add_argument( \"--tm-models\", type=str, choices=TM_MODELS + [\"all\"],", "= [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0] PATH_FORM_HYPERPARAMS = (4, True,", "\"Deltacom.graphml\", \"DialtelecomCz.graphml\", \"Kdl.graphml\", ] TM_MODELS = [ \"uniform\", \"gravity\", \"bimodal\", \"poisson-high-intra\", \"poisson-high-inter\", ]", "(4, True, \"inv-cap\", SpectralClustering, 2), \"Ion.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Kdl.graphml\": (4,", "in args.slices: if ( (\"all\" in args.topos or problem_name in args.topos) and (\"all\"", "\"topology-zoo\", problem_name) else: topo_fname = os.path.join(\"..\", \"topologies\", problem_name) for model in TM_MODELS: for", "args = parser.parse_args() slice_str = \"slice_\" + \"_\".join(str(i) for i in args.slices) output_csv", "_, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) )", "\"Kdl.graphml\", ] TM_MODELS = [ \"uniform\", \"gravity\", \"bimodal\", \"poisson-high-intra\", \"poisson-high-inter\", ] SCALE_FACTORS =", "PATH_FORM_HYPERPARAMS = (4, True, \"inv-cap\") NCFLOW_HYPERPARAMS = { \"GtsCe.graphml\": (4, True, \"inv-cap\", FMPartitioning,", "float(x), choices=SCALE_FACTORS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--slices\", type=int, choices=range(5), nargs=\"+\", required=True", "for key, vals in GROUPED_BY_PROBLEMS.items(): GROUPED_BY_PROBLEMS[key] = sorted(vals) GROUPED_BY_HOLDOUT_PROBLEMS = dict(GROUPED_BY_HOLDOUT_PROBLEMS) for key,", ") HOLDOUT_PROBLEMS.append((problem_name, topo_fname, tm_fname)) GROUPED_BY_PROBLEMS = dict(GROUPED_BY_PROBLEMS) for key, vals in GROUPED_BY_PROBLEMS.items(): GROUPED_BY_PROBLEMS[key]", "from collections import defaultdict from glob import iglob import argparse import os import", "\"inv-cap\", FMPartitioning, 3), \"DialtelecomCz.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Uninett2010.graphml\": (4, True, \"inv-cap\",", "problem_name in args.topos) and (\"all\" in args.tm_models or tm_model in args.tm_models) and (\"all\"", "topo_fname, tm_fname)) GROUPED_BY_PROBLEMS = dict(GROUPED_BY_PROBLEMS) for key, vals in GROUPED_BY_PROBLEMS.items(): GROUPED_BY_PROBLEMS[key] = sorted(vals)", "= sorted(vals) GROUPED_BY_HOLDOUT_PROBLEMS = dict(GROUPED_BY_HOLDOUT_PROBLEMS) for key, vals in GROUPED_BY_HOLDOUT_PROBLEMS.items(): GROUPED_BY_HOLDOUT_PROBLEMS[key] = sorted(vals)", "(\"all\" in args.tm_models or tm_model in args.tm_models) and (\"all\" in args.scale_factors or scale_factor", "\"inv-cap\", SpectralClustering, 2), \"Ion.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Kdl.graphml\": (4, True, \"inv-cap\",", "parser = argparse.ArgumentParser() parser.add_argument(\"--dry-run\", dest=\"dry_run\", action=\"store_true\", default=False) parser.add_argument(\"--obj\", type=str, choices=[\"total_flow\", \"mcf\"], required=True) parser.add_argument(", "(topo_fname, tm_fname) ) PROBLEMS.append((problem_name, topo_fname, tm_fname)) for tm_fname in iglob( \"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format( model, problem_name", "tm_model in TM_MODELS ] PROBLEMS = [] GROUPED_BY_PROBLEMS = defaultdict(list) HOLDOUT_PROBLEMS = []", "\"Uninett2010.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Interoute.graphml\": (4, True, \"inv-cap\", SpectralClustering, 2), \"Ion.graphml\":", "\"mcf\"], required=True) parser.add_argument( \"--tm-models\", type=str, choices=TM_MODELS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--topos\",", "sorted(vals) GROUPED_BY_HOLDOUT_PROBLEMS = dict(GROUPED_BY_HOLDOUT_PROBLEMS) for key, vals in GROUPED_BY_HOLDOUT_PROBLEMS.items(): GROUPED_BY_HOLDOUT_PROBLEMS[key] = sorted(vals) def", "in iglob( \"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model, problem_name) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1],", "[\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--topos\", type=str, choices=PROBLEM_NAMES + [\"all\"], nargs=\"+\", default=\"all\", )", "\"inv-cap\", FMPartitioning, 3), \"Deltacom.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"DialtelecomCz.graphml\": (4, True, \"inv-cap\",", "in args.tm_models) and (\"all\" in args.scale_factors or scale_factor in args.scale_factors) ): topo_fname, tm_fname", "tm_fname)) return problems def get_args_and_problems(output_csv_template, additional_args=[]): parser = argparse.ArgumentParser() parser.add_argument(\"--dry-run\", dest=\"dry_run\", action=\"store_true\", default=False)", "= defaultdict(list) HOLDOUT_PROBLEMS = [] GROUPED_BY_HOLDOUT_PROBLEMS = defaultdict(list) for problem_name in PROBLEM_NAMES: if", "\"all\" else float(x), choices=SCALE_FACTORS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--slices\", type=int, choices=range(5),", "scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) HOLDOUT_PROBLEMS.append((problem_name, topo_fname,", "3), \"DialtelecomCz.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Uninett2010.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3),", "\"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format( model, problem_name ) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1],", "args.topos or problem_name in args.topos) and (\"all\" in args.tm_models or tm_model in args.tm_models)", "sys sys.path.append(\"..\") from lib.partitioning import FMPartitioning, SpectralClustering PROBLEM_NAMES = [ \"GtsCe.graphml\", \"UsCarrier.graphml\", \"Cogentco.graphml\",", ") in GROUPED_BY_PROBLEMS.items(): for slice in args.slices: if ( (\"all\" in args.topos or", "= os.path.join(\"..\", \"topologies\", \"topology-zoo\", problem_name) else: topo_fname = os.path.join(\"..\", \"topologies\", problem_name) for model", "= dict(GROUPED_BY_HOLDOUT_PROBLEMS) for key, vals in GROUPED_BY_HOLDOUT_PROBLEMS.items(): GROUPED_BY_HOLDOUT_PROBLEMS[key] = sorted(vals) def get_problems(args): problems", "sys.path.append(\"..\") from lib.partitioning import FMPartitioning, SpectralClustering PROBLEM_NAMES = [ \"GtsCe.graphml\", \"UsCarrier.graphml\", \"Cogentco.graphml\", \"Colt.graphml\",", "get_problems(args) def print_(*args, file=None): if file is None: file = sys.stdout print(*args, file=file)", "for slice in args.slices: if ( (\"all\" in args.topos or problem_name in args.topos)", "tm_fname in iglob( \"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format( model, problem_name ) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed,", "FMPartitioning, 3), } PROBLEM_NAMES_AND_TM_MODELS = [ (prob_name, tm_model) for prob_name in PROBLEM_NAMES for", "name_or_flags, kwargs = additional_arg[0], additional_arg[1] parser.add_argument(name_or_flags, **kwargs) args = parser.parse_args() slice_str = \"slice_\"", "GROUPED_BY_PROBLEMS = defaultdict(list) HOLDOUT_PROBLEMS = [] GROUPED_BY_HOLDOUT_PROBLEMS = defaultdict(list) for problem_name in PROBLEM_NAMES:", "FMPartitioning, 3), \"Interoute.graphml\": (4, True, \"inv-cap\", SpectralClustering, 2), \"Ion.graphml\": (4, True, \"inv-cap\", FMPartitioning,", "128.0] PATH_FORM_HYPERPARAMS = (4, True, \"inv-cap\") NCFLOW_HYPERPARAMS = { \"GtsCe.graphml\": (4, True, \"inv-cap\",", "HOLDOUT_PROBLEMS.append((problem_name, topo_fname, tm_fname)) GROUPED_BY_PROBLEMS = dict(GROUPED_BY_PROBLEMS) for key, vals in GROUPED_BY_PROBLEMS.items(): GROUPED_BY_PROBLEMS[key] =", "GROUPED_BY_HOLDOUT_PROBLEMS = dict(GROUPED_BY_HOLDOUT_PROBLEMS) for key, vals in GROUPED_BY_HOLDOUT_PROBLEMS.items(): GROUPED_BY_HOLDOUT_PROBLEMS[key] = sorted(vals) def get_problems(args):", "iglob( \"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model, problem_name) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]),", "\"Ion.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Kdl.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"erdos-renyi-1260231677.json\":", "model in TM_MODELS: for tm_fname in iglob( \"../traffic-matrices/{}/{}*_traffic-matrix.pkl\".format(model, problem_name) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\")", "vals = os.path.basename(tm_fname)[:-4].split(\"_\") _, traffic_seed, scale_factor = vals[1], int(vals[2]), float(vals[3]) GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name, model, scale_factor)].append(", "( (problem_name, tm_model, scale_factor), topo_and_tm_fnames, ) in GROUPED_BY_PROBLEMS.items(): for slice in args.slices: if", "GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) HOLDOUT_PROBLEMS.append((problem_name, topo_fname, tm_fname)) GROUPED_BY_PROBLEMS = dict(GROUPED_BY_PROBLEMS) for", "GROUPED_BY_PROBLEMS.items(): for slice in args.slices: if ( (\"all\" in args.topos or problem_name in", "nargs=\"+\", default=\"all\", ) parser.add_argument( \"--slices\", type=int, choices=range(5), nargs=\"+\", required=True ) for additional_arg in", "(problem_name, tm_model, scale_factor), topo_and_tm_fnames, ) in GROUPED_BY_PROBLEMS.items(): for slice in args.slices: if (", "3), } PROBLEM_NAMES_AND_TM_MODELS = [ (prob_name, tm_model) for prob_name in PROBLEM_NAMES for tm_model", "topo_fname, tm_fname)) for tm_fname in iglob( \"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format( model, problem_name ) ): vals =", "additional_args: name_or_flags, kwargs = additional_arg[0], additional_arg[1] parser.add_argument(name_or_flags, **kwargs) args = parser.parse_args() slice_str =", "from lib.partitioning import FMPartitioning, SpectralClustering PROBLEM_NAMES = [ \"GtsCe.graphml\", \"UsCarrier.graphml\", \"Cogentco.graphml\", \"Colt.graphml\", \"TataNld.graphml\",", "tm_fname)) for tm_fname in iglob( \"../traffic-matrices/holdout/{}/{}*_traffic-matrix.pkl\".format( model, problem_name ) ): vals = os.path.basename(tm_fname)[:-4].split(\"_\")", "3), \"Cogentco.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Colt.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3),", "parser.add_argument( \"--tm-models\", type=str, choices=TM_MODELS + [\"all\"], nargs=\"+\", default=\"all\", ) parser.add_argument( \"--topos\", type=str, choices=PROBLEM_NAMES", "True, \"inv-cap\", FMPartitioning, 3), \"Colt.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"TataNld.graphml\": (4, True,", "\"--slices\", type=int, choices=range(5), nargs=\"+\", required=True ) for additional_arg in additional_args: name_or_flags, kwargs =", "SCALE_FACTORS = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0] PATH_FORM_HYPERPARAMS = (4,", "(4, True, \"inv-cap\", FMPartitioning, 3), } PROBLEM_NAMES_AND_TM_MODELS = [ (prob_name, tm_model) for prob_name", "sorted(vals) def get_problems(args): problems = [] for ( (problem_name, tm_model, scale_factor), topo_and_tm_fnames, )", "\"GtsCe.graphml\", \"UsCarrier.graphml\", \"Cogentco.graphml\", \"Colt.graphml\", \"TataNld.graphml\", \"Deltacom.graphml\", \"DialtelecomCz.graphml\", \"Kdl.graphml\", ] TM_MODELS = [ \"uniform\",", "PROBLEM_NAMES for tm_model in TM_MODELS ] PROBLEMS = [] GROUPED_BY_PROBLEMS = defaultdict(list) HOLDOUT_PROBLEMS", "import os import sys sys.path.append(\"..\") from lib.partitioning import FMPartitioning, SpectralClustering PROBLEM_NAMES = [", "import FMPartitioning, SpectralClustering PROBLEM_NAMES = [ \"GtsCe.graphml\", \"UsCarrier.graphml\", \"Cogentco.graphml\", \"Colt.graphml\", \"TataNld.graphml\", \"Deltacom.graphml\", \"DialtelecomCz.graphml\",", "int(vals[2]), float(vals[3]) GROUPED_BY_HOLDOUT_PROBLEMS[(problem_name, model, scale_factor)].append( (topo_fname, tm_fname) ) HOLDOUT_PROBLEMS.append((problem_name, topo_fname, tm_fname)) GROUPED_BY_PROBLEMS =", "import iglob import argparse import os import sys sys.path.append(\"..\") from lib.partitioning import FMPartitioning,", "= sorted(vals) def get_problems(args): problems = [] for ( (problem_name, tm_model, scale_factor), topo_and_tm_fnames,", "def print_(*args, file=None): if file is None: file = sys.stdout print(*args, file=file) file.flush()", "tm_model) for prob_name in PROBLEM_NAMES for tm_model in TM_MODELS ] PROBLEMS = []", "for ( (problem_name, tm_model, scale_factor), topo_and_tm_fnames, ) in GROUPED_BY_PROBLEMS.items(): for slice in args.slices:", "True, \"inv-cap\", FMPartitioning, 3), \"UsCarrier.graphml\": (4, True, \"inv-cap\", FMPartitioning, 3), \"Cogentco.graphml\": (4, True," ]
[ "[] for datum in getFieldsInOrder(self.interface): if datum[0] in data: if data[datum[0]] != getattr(self.context,", "= '%s/edit_page.html' % folder.context.absolute_url(0) self.request.response.redirect(url) return else: retval = u'Problem creating page' assert", "# All good, so redirect to the edit page. if changed: url =", "import ZopeTwoPageTemplateFile from zope.app.form.browser import TextAreaWidget from zope.app.apidoc.interface import getFieldsInOrder from zope.schema import", "== 1: self.status = u'<p>There is an error:</p>' else: self.status = u'<p>There are", "import getFieldsInOrder from zope.schema import * import interfaces from page import GSContentPage def", "action, data): return self.set_data(data) def handle_set_action_failure(self, action, data, errors): if len(errors) == 1:", "form.Fields(interface, render_context=True, omit_readonly=True) self.form_fields['content'].custom_widget = wym_editor_widget self.form_fields['content'].field.default = u'<p>Enter content '\\ u'here.</p>' self.mode", "an error:</p>' else: self.status = u'<p>There are errors:</p>' def set_data(self, data): assert self.context", "content '\\ u'here.</p>' self.mode = 'add' @property def id(self): return self.form_fields['id'] @property def", "return self.form_fields['title'] @property def description(self): return self.form_fields['description'] @property def content(self): return self.form_fields['content'] #", "to the success handler, # \"handle_reset_action_failure\" as the failure handler, and adds the", "action, data, errors): if len(errors) == 1: self.status = u'<p>There is an error:</p>'", "is an error:</p>' else: self.status = u'<p>There are errors:</p>' def set_data(self, data): assert", "= u'%s' % folder.status['msg'] changed = form.applyChanges(folder, self.form_fields, data) # All good, so", "request): retval = TextAreaWidget(field, request) retval.cssClass = 'wymeditor' return retval class AddPageForm(AddForm): label", "redirect to the edit page. if changed: url = '%s/edit_page.html' % folder.context.absolute_url(0) self.request.response.redirect(url)", "readability. @form.action(label=u'Add', failure='handle_set_action_failure') def handle_set(self, action, data): return self.set_data(data) def handle_set_action_failure(self, action, data,", "ZopeTwoPageTemplateFile from zope.app.form.browser import TextAreaWidget from zope.app.apidoc.interface import getFieldsInOrder from zope.schema import *", "= u'<p>There are errors:</p>' def set_data(self, data): assert self.context assert self.form_fields alteredFields =", "def id(self): return self.form_fields['id'] @property def title(self): return self.form_fields['title'] @property def description(self): return", "need to explicitly state that \"Edit\" is the # label, but it helps", "= u'<p>There is an error:</p>' else: self.status = u'<p>There are errors:</p>' def set_data(self,", "the Add Page form. ''' try: from five.formlib.formbase import AddForm except ImportError: from", "def handle_set_action_failure(self, action, data, errors): if len(errors) == 1: self.status = u'<p>There is", "@property def id(self): return self.form_fields['id'] @property def title(self): return self.form_fields['title'] @property def description(self):", "\"handle_reset_action_failure\" as the failure handler, and adds the # action to the \"actions\"", "data[datum[0]] != getattr(self.context, datum[0]): alteredFields.append(datum[0]) # Create the content folder and object and", "'browser/templates/edit_page.pt' template = ZopeTwoPageTemplateFile(pageTemplateFileName) def __init__(self, context, request): self.context = context self.request =", "context, request): self.context = context self.request = request self.interface = interface = getattr(interfaces,", "ZopeTwoPageTemplateFile(pageTemplateFileName) def __init__(self, context, request): self.context = context self.request = request self.interface =", "pageTemplateFileName = 'browser/templates/edit_page.pt' template = ZopeTwoPageTemplateFile(pageTemplateFileName) def __init__(self, context, request): self.context = context", "\"Edit\" is the # label, but it helps with readability. @form.action(label=u'Add', failure='handle_set_action_failure') def", "edit page. if changed: url = '%s/edit_page.html' % folder.context.absolute_url(0) self.request.response.redirect(url) return else: retval", "= form.applyChanges(folder, self.form_fields, data) # All good, so redirect to the edit page.", "from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from zope.app.form.browser import TextAreaWidget from zope.app.apidoc.interface import getFieldsInOrder from", "failure handler, and adds the # action to the \"actions\" instance variable (creating", "to the \"actions\" instance variable (creating it if # necessary). I did not", "All good, so redirect to the edit page. if changed: url = '%s/edit_page.html'", "object and apply changes. folder = GSContentPage(self.context, mode='add', id=data['id']) if folder.status['error']: retval =", "self.mode = 'add' @property def id(self): return self.form_fields['id'] @property def title(self): return self.form_fields['title']", "return self.form_fields['id'] @property def title(self): return self.form_fields['title'] @property def description(self): return self.form_fields['description'] @property", "the # label, but it helps with readability. @form.action(label=u'Add', failure='handle_set_action_failure') def handle_set(self, action,", "the \"actions\" instance variable (creating it if # necessary). I did not need", "explicitly state that \"Edit\" is the # label, but it helps with readability.", "return retval class AddPageForm(AddForm): label = u'Add Page' pageTemplateFileName = 'browser/templates/edit_page.pt' template =", "import AddForm except ImportError: from Products.Five.formlib.formbase import AddForm # lint:ok from zope.component import", "from Products.Five.formlib.formbase import AddForm # lint:ok from zope.component import createObject from zope.formlib import", "render_context=True, omit_readonly=True) self.form_fields['content'].custom_widget = wym_editor_widget self.form_fields['content'].field.default = u'<p>Enter content '\\ u'here.</p>' self.mode =", "it if # necessary). I did not need to explicitly state that \"Edit\"", "self.form_fields['description'] @property def content(self): return self.form_fields['content'] # --=mpj17=-- # The \"form.action\" decorator creates", "is the # label, but it helps with readability. @form.action(label=u'Add', failure='handle_set_action_failure') def handle_set(self,", "if folder.status['error']: retval = u'%s' % folder.status['msg'] changed = form.applyChanges(folder, self.form_fields, data) #", "context) site_root = context.site_root() assert hasattr(site_root, 'GlobalConfiguration') self.form_fields = form.Fields(interface, render_context=True, omit_readonly=True) self.form_fields['content'].custom_widget", "of the Add Page form. ''' try: from five.formlib.formbase import AddForm except ImportError:", "omit_readonly=True) self.form_fields['content'].custom_widget = wym_editor_widget self.form_fields['content'].field.default = u'<p>Enter content '\\ u'here.</p>' self.mode = 'add'", "@property def description(self): return self.form_fields['description'] @property def content(self): return self.form_fields['content'] # --=mpj17=-- #", "\"form.action\" decorator creates an action instance, with # \"handle_reset\" set to the success", "if len(errors) == 1: self.status = u'<p>There is an error:</p>' else: self.status =", "lint:ok from zope.component import createObject from zope.formlib import form from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile", "# --=mpj17=-- # The \"form.action\" decorator creates an action instance, with # \"handle_reset\"", "handler, # \"handle_reset_action_failure\" as the failure handler, and adds the # action to", "zope.app.form.browser import TextAreaWidget from zope.app.apidoc.interface import getFieldsInOrder from zope.schema import * import interfaces", "form from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from zope.app.form.browser import TextAreaWidget from zope.app.apidoc.interface import getFieldsInOrder", "# necessary). I did not need to explicitly state that \"Edit\" is the", "TextAreaWidget(field, request) retval.cssClass = 'wymeditor' return retval class AddPageForm(AddForm): label = u'Add Page'", "import createObject from zope.formlib import form from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from zope.app.form.browser import", "data): assert self.context assert self.form_fields alteredFields = [] for datum in getFieldsInOrder(self.interface): if", "if changed: url = '%s/edit_page.html' % folder.context.absolute_url(0) self.request.response.redirect(url) return else: retval = u'Problem", "hasattr(site_root, 'GlobalConfiguration') self.form_fields = form.Fields(interface, render_context=True, omit_readonly=True) self.form_fields['content'].custom_widget = wym_editor_widget self.form_fields['content'].field.default = u'<p>Enter", "import form from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from zope.app.form.browser import TextAreaWidget from zope.app.apidoc.interface import", "form. ''' try: from five.formlib.formbase import AddForm except ImportError: from Products.Five.formlib.formbase import AddForm", "def title(self): return self.form_fields['title'] @property def description(self): return self.form_fields['description'] @property def content(self): return", "AddForm # lint:ok from zope.component import createObject from zope.formlib import form from Products.Five.browser.pagetemplatefile", "u'<p>There is an error:</p>' else: self.status = u'<p>There are errors:</p>' def set_data(self, data):", "= u'Problem creating page' assert retval assert type(retval) == unicode self.status = retval", "but it helps with readability. @form.action(label=u'Add', failure='handle_set_action_failure') def handle_set(self, action, data): return self.set_data(data)", "folder.status['error']: retval = u'%s' % folder.status['msg'] changed = form.applyChanges(folder, self.form_fields, data) # All", "from zope.schema import * import interfaces from page import GSContentPage def wym_editor_widget(field, request):", "retval class AddPageForm(AddForm): label = u'Add Page' pageTemplateFileName = 'browser/templates/edit_page.pt' template = ZopeTwoPageTemplateFile(pageTemplateFileName)", "zope.app.apidoc.interface import getFieldsInOrder from zope.schema import * import interfaces from page import GSContentPage", "with readability. @form.action(label=u'Add', failure='handle_set_action_failure') def handle_set(self, action, data): return self.set_data(data) def handle_set_action_failure(self, action,", "data): return self.set_data(data) def handle_set_action_failure(self, action, data, errors): if len(errors) == 1: self.status", "getFieldsInOrder(self.interface): if datum[0] in data: if data[datum[0]] != getattr(self.context, datum[0]): alteredFields.append(datum[0]) # Create", "retval.cssClass = 'wymeditor' return retval class AddPageForm(AddForm): label = u'Add Page' pageTemplateFileName =", "request self.interface = interface = getattr(interfaces, 'IGSContentPage') AddForm.__init__(self, context, request) self.siteInfo = createObject('groupserver.SiteInfo',", "helps with readability. @form.action(label=u'Add', failure='handle_set_action_failure') def handle_set(self, action, data): return self.set_data(data) def handle_set_action_failure(self,", "id=data['id']) if folder.status['error']: retval = u'%s' % folder.status['msg'] changed = form.applyChanges(folder, self.form_fields, data)", "self.request = request self.interface = interface = getattr(interfaces, 'IGSContentPage') AddForm.__init__(self, context, request) self.siteInfo", "TextAreaWidget from zope.app.apidoc.interface import getFieldsInOrder from zope.schema import * import interfaces from page", "assert hasattr(site_root, 'GlobalConfiguration') self.form_fields = form.Fields(interface, render_context=True, omit_readonly=True) self.form_fields['content'].custom_widget = wym_editor_widget self.form_fields['content'].field.default =", "= getattr(interfaces, 'IGSContentPage') AddForm.__init__(self, context, request) self.siteInfo = createObject('groupserver.SiteInfo', context) site_root = context.site_root()", "def description(self): return self.form_fields['description'] @property def content(self): return self.form_fields['content'] # --=mpj17=-- # The", "variable (creating it if # necessary). I did not need to explicitly state", "the success handler, # \"handle_reset_action_failure\" as the failure handler, and adds the #", "handle_set(self, action, data): return self.set_data(data) def handle_set_action_failure(self, action, data, errors): if len(errors) ==", "retval = u'%s' % folder.status['msg'] changed = form.applyChanges(folder, self.form_fields, data) # All good,", "content folder and object and apply changes. folder = GSContentPage(self.context, mode='add', id=data['id']) if", "with # \"handle_reset\" set to the success handler, # \"handle_reset_action_failure\" as the failure", "(creating it if # necessary). I did not need to explicitly state that", "changed = form.applyChanges(folder, self.form_fields, data) # All good, so redirect to the edit", "folder.status['msg'] changed = form.applyChanges(folder, self.form_fields, data) # All good, so redirect to the", "datum in getFieldsInOrder(self.interface): if datum[0] in data: if data[datum[0]] != getattr(self.context, datum[0]): alteredFields.append(datum[0])", "# \"handle_reset\" set to the success handler, # \"handle_reset_action_failure\" as the failure handler,", "action to the \"actions\" instance variable (creating it if # necessary). I did", "Create the content folder and object and apply changes. folder = GSContentPage(self.context, mode='add',", "to explicitly state that \"Edit\" is the # label, but it helps with", "the edit page. if changed: url = '%s/edit_page.html' % folder.context.absolute_url(0) self.request.response.redirect(url) return else:", "AddForm except ImportError: from Products.Five.formlib.formbase import AddForm # lint:ok from zope.component import createObject", "from zope.component import createObject from zope.formlib import form from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from", "not need to explicitly state that \"Edit\" is the # label, but it", "url = '%s/edit_page.html' % folder.context.absolute_url(0) self.request.response.redirect(url) return else: retval = u'Problem creating page'", "did not need to explicitly state that \"Edit\" is the # label, but", "def __init__(self, context, request): self.context = context self.request = request self.interface = interface", "the failure handler, and adds the # action to the \"actions\" instance variable", "zope.component import createObject from zope.formlib import form from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from zope.app.form.browser", "label = u'Add Page' pageTemplateFileName = 'browser/templates/edit_page.pt' template = ZopeTwoPageTemplateFile(pageTemplateFileName) def __init__(self, context,", "request) self.siteInfo = createObject('groupserver.SiteInfo', context) site_root = context.site_root() assert hasattr(site_root, 'GlobalConfiguration') self.form_fields =", "context.site_root() assert hasattr(site_root, 'GlobalConfiguration') self.form_fields = form.Fields(interface, render_context=True, omit_readonly=True) self.form_fields['content'].custom_widget = wym_editor_widget self.form_fields['content'].field.default", "= 'browser/templates/edit_page.pt' template = ZopeTwoPageTemplateFile(pageTemplateFileName) def __init__(self, context, request): self.context = context self.request", "failure='handle_set_action_failure') def handle_set(self, action, data): return self.set_data(data) def handle_set_action_failure(self, action, data, errors): if", "interface = getattr(interfaces, 'IGSContentPage') AddForm.__init__(self, context, request) self.siteInfo = createObject('groupserver.SiteInfo', context) site_root =", "site_root = context.site_root() assert hasattr(site_root, 'GlobalConfiguration') self.form_fields = form.Fields(interface, render_context=True, omit_readonly=True) self.form_fields['content'].custom_widget =", "content(self): return self.form_fields['content'] # --=mpj17=-- # The \"form.action\" decorator creates an action instance,", "Add Page form. ''' try: from five.formlib.formbase import AddForm except ImportError: from Products.Five.formlib.formbase", "= createObject('groupserver.SiteInfo', context) site_root = context.site_root() assert hasattr(site_root, 'GlobalConfiguration') self.form_fields = form.Fields(interface, render_context=True,", "'\\ u'here.</p>' self.mode = 'add' @property def id(self): return self.form_fields['id'] @property def title(self):", "ImportError: from Products.Five.formlib.formbase import AddForm # lint:ok from zope.component import createObject from zope.formlib", "an action instance, with # \"handle_reset\" set to the success handler, # \"handle_reset_action_failure\"", "that \"Edit\" is the # label, but it helps with readability. @form.action(label=u'Add', failure='handle_set_action_failure')", "zope.schema import * import interfaces from page import GSContentPage def wym_editor_widget(field, request): retval", "'IGSContentPage') AddForm.__init__(self, context, request) self.siteInfo = createObject('groupserver.SiteInfo', context) site_root = context.site_root() assert hasattr(site_root,", "folder and object and apply changes. folder = GSContentPage(self.context, mode='add', id=data['id']) if folder.status['error']:", "datum[0] in data: if data[datum[0]] != getattr(self.context, datum[0]): alteredFields.append(datum[0]) # Create the content", "apply changes. folder = GSContentPage(self.context, mode='add', id=data['id']) if folder.status['error']: retval = u'%s' %", "adds the # action to the \"actions\" instance variable (creating it if #", "and object and apply changes. folder = GSContentPage(self.context, mode='add', id=data['id']) if folder.status['error']: retval", "!= getattr(self.context, datum[0]): alteredFields.append(datum[0]) # Create the content folder and object and apply", "len(errors) == 1: self.status = u'<p>There is an error:</p>' else: self.status = u'<p>There", "interfaces from page import GSContentPage def wym_editor_widget(field, request): retval = TextAreaWidget(field, request) retval.cssClass", "and adds the # action to the \"actions\" instance variable (creating it if", "# The \"form.action\" decorator creates an action instance, with # \"handle_reset\" set to", "errors): if len(errors) == 1: self.status = u'<p>There is an error:</p>' else: self.status", "self.status = u'<p>There is an error:</p>' else: self.status = u'<p>There are errors:</p>' def", "Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from zope.app.form.browser import TextAreaWidget from zope.app.apidoc.interface import getFieldsInOrder from zope.schema", "and apply changes. folder = GSContentPage(self.context, mode='add', id=data['id']) if folder.status['error']: retval = u'%s'", "u'%s' % folder.status['msg'] changed = form.applyChanges(folder, self.form_fields, data) # All good, so redirect", "GSContentPage(self.context, mode='add', id=data['id']) if folder.status['error']: retval = u'%s' % folder.status['msg'] changed = form.applyChanges(folder,", "% folder.context.absolute_url(0) self.request.response.redirect(url) return else: retval = u'Problem creating page' assert retval assert", "changed: url = '%s/edit_page.html' % folder.context.absolute_url(0) self.request.response.redirect(url) return else: retval = u'Problem creating", "import * import interfaces from page import GSContentPage def wym_editor_widget(field, request): retval =", "five.formlib.formbase import AddForm except ImportError: from Products.Five.formlib.formbase import AddForm # lint:ok from zope.component", "page. if changed: url = '%s/edit_page.html' % folder.context.absolute_url(0) self.request.response.redirect(url) return else: retval =", "= [] for datum in getFieldsInOrder(self.interface): if datum[0] in data: if data[datum[0]] !=", "__init__(self, context, request): self.context = context self.request = request self.interface = interface =", "# action to the \"actions\" instance variable (creating it if # necessary). I", "I did not need to explicitly state that \"Edit\" is the # label,", "getFieldsInOrder from zope.schema import * import interfaces from page import GSContentPage def wym_editor_widget(field,", "state that \"Edit\" is the # label, but it helps with readability. @form.action(label=u'Add',", "= u'Add Page' pageTemplateFileName = 'browser/templates/edit_page.pt' template = ZopeTwoPageTemplateFile(pageTemplateFileName) def __init__(self, context, request):", "= 'add' @property def id(self): return self.form_fields['id'] @property def title(self): return self.form_fields['title'] @property", "decorator creates an action instance, with # \"handle_reset\" set to the success handler,", "assert self.form_fields alteredFields = [] for datum in getFieldsInOrder(self.interface): if datum[0] in data:", "import AddForm # lint:ok from zope.component import createObject from zope.formlib import form from", "retval = TextAreaWidget(field, request) retval.cssClass = 'wymeditor' return retval class AddPageForm(AddForm): label =", "action instance, with # \"handle_reset\" set to the success handler, # \"handle_reset_action_failure\" as", "context self.request = request self.interface = interface = getattr(interfaces, 'IGSContentPage') AddForm.__init__(self, context, request)", "self.form_fields['title'] @property def description(self): return self.form_fields['description'] @property def content(self): return self.form_fields['content'] # --=mpj17=--", "if # necessary). I did not need to explicitly state that \"Edit\" is", "set_data(self, data): assert self.context assert self.form_fields alteredFields = [] for datum in getFieldsInOrder(self.interface):", "folder = GSContentPage(self.context, mode='add', id=data['id']) if folder.status['error']: retval = u'%s' % folder.status['msg'] changed", "def wym_editor_widget(field, request): retval = TextAreaWidget(field, request) retval.cssClass = 'wymeditor' return retval class", "# coding=utf-8 '''Implementation of the Add Page form. ''' try: from five.formlib.formbase import", "# \"handle_reset_action_failure\" as the failure handler, and adds the # action to the", "the # action to the \"actions\" instance variable (creating it if # necessary).", "def set_data(self, data): assert self.context assert self.form_fields alteredFields = [] for datum in", "try: from five.formlib.formbase import AddForm except ImportError: from Products.Five.formlib.formbase import AddForm # lint:ok", "= GSContentPage(self.context, mode='add', id=data['id']) if folder.status['error']: retval = u'%s' % folder.status['msg'] changed =", "getattr(interfaces, 'IGSContentPage') AddForm.__init__(self, context, request) self.siteInfo = createObject('groupserver.SiteInfo', context) site_root = context.site_root() assert", "wym_editor_widget self.form_fields['content'].field.default = u'<p>Enter content '\\ u'here.</p>' self.mode = 'add' @property def id(self):", "u'Add Page' pageTemplateFileName = 'browser/templates/edit_page.pt' template = ZopeTwoPageTemplateFile(pageTemplateFileName) def __init__(self, context, request): self.context", "else: self.status = u'<p>There are errors:</p>' def set_data(self, data): assert self.context assert self.form_fields", "except ImportError: from Products.Five.formlib.formbase import AddForm # lint:ok from zope.component import createObject from", "request): self.context = context self.request = request self.interface = interface = getattr(interfaces, 'IGSContentPage')", "@property def title(self): return self.form_fields['title'] @property def description(self): return self.form_fields['description'] @property def content(self):", "--=mpj17=-- # The \"form.action\" decorator creates an action instance, with # \"handle_reset\" set", "= ZopeTwoPageTemplateFile(pageTemplateFileName) def __init__(self, context, request): self.context = context self.request = request self.interface", "Page form. ''' try: from five.formlib.formbase import AddForm except ImportError: from Products.Five.formlib.formbase import", "handler, and adds the # action to the \"actions\" instance variable (creating it", "from page import GSContentPage def wym_editor_widget(field, request): retval = TextAreaWidget(field, request) retval.cssClass =", "\"handle_reset\" set to the success handler, # \"handle_reset_action_failure\" as the failure handler, and", "assert self.context assert self.form_fields alteredFields = [] for datum in getFieldsInOrder(self.interface): if datum[0]", "getattr(self.context, datum[0]): alteredFields.append(datum[0]) # Create the content folder and object and apply changes.", "in getFieldsInOrder(self.interface): if datum[0] in data: if data[datum[0]] != getattr(self.context, datum[0]): alteredFields.append(datum[0]) #", "from zope.app.form.browser import TextAreaWidget from zope.app.apidoc.interface import getFieldsInOrder from zope.schema import * import", "handle_set_action_failure(self, action, data, errors): if len(errors) == 1: self.status = u'<p>There is an", "template = ZopeTwoPageTemplateFile(pageTemplateFileName) def __init__(self, context, request): self.context = context self.request = request", "in data: if data[datum[0]] != getattr(self.context, datum[0]): alteredFields.append(datum[0]) # Create the content folder", "* import interfaces from page import GSContentPage def wym_editor_widget(field, request): retval = TextAreaWidget(field,", "instance variable (creating it if # necessary). I did not need to explicitly", "# label, but it helps with readability. @form.action(label=u'Add', failure='handle_set_action_failure') def handle_set(self, action, data):", "self.form_fields['content'] # --=mpj17=-- # The \"form.action\" decorator creates an action instance, with #", "''' try: from five.formlib.formbase import AddForm except ImportError: from Products.Five.formlib.formbase import AddForm #", "for datum in getFieldsInOrder(self.interface): if datum[0] in data: if data[datum[0]] != getattr(self.context, datum[0]):", "self.context = context self.request = request self.interface = interface = getattr(interfaces, 'IGSContentPage') AddForm.__init__(self,", "set to the success handler, # \"handle_reset_action_failure\" as the failure handler, and adds", "the content folder and object and apply changes. folder = GSContentPage(self.context, mode='add', id=data['id'])", "= form.Fields(interface, render_context=True, omit_readonly=True) self.form_fields['content'].custom_widget = wym_editor_widget self.form_fields['content'].field.default = u'<p>Enter content '\\ u'here.</p>'", "u'<p>There are errors:</p>' def set_data(self, data): assert self.context assert self.form_fields alteredFields = []", "else: retval = u'Problem creating page' assert retval assert type(retval) == unicode self.status", "to the edit page. if changed: url = '%s/edit_page.html' % folder.context.absolute_url(0) self.request.response.redirect(url) return", "= request self.interface = interface = getattr(interfaces, 'IGSContentPage') AddForm.__init__(self, context, request) self.siteInfo =", "if datum[0] in data: if data[datum[0]] != getattr(self.context, datum[0]): alteredFields.append(datum[0]) # Create the", "createObject('groupserver.SiteInfo', context) site_root = context.site_root() assert hasattr(site_root, 'GlobalConfiguration') self.form_fields = form.Fields(interface, render_context=True, omit_readonly=True)", "def handle_set(self, action, data): return self.set_data(data) def handle_set_action_failure(self, action, data, errors): if len(errors)", "retval = u'Problem creating page' assert retval assert type(retval) == unicode self.status =", "'''Implementation of the Add Page form. ''' try: from five.formlib.formbase import AddForm except", "GSContentPage def wym_editor_widget(field, request): retval = TextAreaWidget(field, request) retval.cssClass = 'wymeditor' return retval", "= wym_editor_widget self.form_fields['content'].field.default = u'<p>Enter content '\\ u'here.</p>' self.mode = 'add' @property def", "self.context assert self.form_fields alteredFields = [] for datum in getFieldsInOrder(self.interface): if datum[0] in", "wym_editor_widget(field, request): retval = TextAreaWidget(field, request) retval.cssClass = 'wymeditor' return retval class AddPageForm(AddForm):", "self.form_fields['id'] @property def title(self): return self.form_fields['title'] @property def description(self): return self.form_fields['description'] @property def", "alteredFields = [] for datum in getFieldsInOrder(self.interface): if datum[0] in data: if data[datum[0]]", "= context.site_root() assert hasattr(site_root, 'GlobalConfiguration') self.form_fields = form.Fields(interface, render_context=True, omit_readonly=True) self.form_fields['content'].custom_widget = wym_editor_widget", "error:</p>' else: self.status = u'<p>There are errors:</p>' def set_data(self, data): assert self.context assert", "'add' @property def id(self): return self.form_fields['id'] @property def title(self): return self.form_fields['title'] @property def", "changes. folder = GSContentPage(self.context, mode='add', id=data['id']) if folder.status['error']: retval = u'%s' % folder.status['msg']", "import interfaces from page import GSContentPage def wym_editor_widget(field, request): retval = TextAreaWidget(field, request)", "self.form_fields['content'].field.default = u'<p>Enter content '\\ u'here.</p>' self.mode = 'add' @property def id(self): return", "self.interface = interface = getattr(interfaces, 'IGSContentPage') AddForm.__init__(self, context, request) self.siteInfo = createObject('groupserver.SiteInfo', context)", "datum[0]): alteredFields.append(datum[0]) # Create the content folder and object and apply changes. folder", "data) # All good, so redirect to the edit page. if changed: url", "Products.Five.formlib.formbase import AddForm # lint:ok from zope.component import createObject from zope.formlib import form", "AddForm.__init__(self, context, request) self.siteInfo = createObject('groupserver.SiteInfo', context) site_root = context.site_root() assert hasattr(site_root, 'GlobalConfiguration')", "context, request) self.siteInfo = createObject('groupserver.SiteInfo', context) site_root = context.site_root() assert hasattr(site_root, 'GlobalConfiguration') self.form_fields", "import GSContentPage def wym_editor_widget(field, request): retval = TextAreaWidget(field, request) retval.cssClass = 'wymeditor' return", "= TextAreaWidget(field, request) retval.cssClass = 'wymeditor' return retval class AddPageForm(AddForm): label = u'Add", "return self.form_fields['description'] @property def content(self): return self.form_fields['content'] # --=mpj17=-- # The \"form.action\" decorator", "from zope.formlib import form from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from zope.app.form.browser import TextAreaWidget from", "self.set_data(data) def handle_set_action_failure(self, action, data, errors): if len(errors) == 1: self.status = u'<p>There", "coding=utf-8 '''Implementation of the Add Page form. ''' try: from five.formlib.formbase import AddForm", "self.status = u'<p>There are errors:</p>' def set_data(self, data): assert self.context assert self.form_fields alteredFields", "self.form_fields alteredFields = [] for datum in getFieldsInOrder(self.interface): if datum[0] in data: if", "if data[datum[0]] != getattr(self.context, datum[0]): alteredFields.append(datum[0]) # Create the content folder and object", "form.applyChanges(folder, self.form_fields, data) # All good, so redirect to the edit page. if", "page import GSContentPage def wym_editor_widget(field, request): retval = TextAreaWidget(field, request) retval.cssClass = 'wymeditor'", "= context self.request = request self.interface = interface = getattr(interfaces, 'IGSContentPage') AddForm.__init__(self, context,", "Page' pageTemplateFileName = 'browser/templates/edit_page.pt' template = ZopeTwoPageTemplateFile(pageTemplateFileName) def __init__(self, context, request): self.context =", "self.form_fields, data) # All good, so redirect to the edit page. if changed:", "as the failure handler, and adds the # action to the \"actions\" instance", "self.form_fields = form.Fields(interface, render_context=True, omit_readonly=True) self.form_fields['content'].custom_widget = wym_editor_widget self.form_fields['content'].field.default = u'<p>Enter content '\\", "success handler, # \"handle_reset_action_failure\" as the failure handler, and adds the # action", "it helps with readability. @form.action(label=u'Add', failure='handle_set_action_failure') def handle_set(self, action, data): return self.set_data(data) def", "def content(self): return self.form_fields['content'] # --=mpj17=-- # The \"form.action\" decorator creates an action", "@form.action(label=u'Add', failure='handle_set_action_failure') def handle_set(self, action, data): return self.set_data(data) def handle_set_action_failure(self, action, data, errors):", "data: if data[datum[0]] != getattr(self.context, datum[0]): alteredFields.append(datum[0]) # Create the content folder and", "zope.formlib import form from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from zope.app.form.browser import TextAreaWidget from zope.app.apidoc.interface", "errors:</p>' def set_data(self, data): assert self.context assert self.form_fields alteredFields = [] for datum", "instance, with # \"handle_reset\" set to the success handler, # \"handle_reset_action_failure\" as the", "folder.context.absolute_url(0) self.request.response.redirect(url) return else: retval = u'Problem creating page' assert retval assert type(retval)", "@property def content(self): return self.form_fields['content'] # --=mpj17=-- # The \"form.action\" decorator creates an", "1: self.status = u'<p>There is an error:</p>' else: self.status = u'<p>There are errors:</p>'", "= u'<p>Enter content '\\ u'here.</p>' self.mode = 'add' @property def id(self): return self.form_fields['id']", "creates an action instance, with # \"handle_reset\" set to the success handler, #", "\"actions\" instance variable (creating it if # necessary). I did not need to", "= 'wymeditor' return retval class AddPageForm(AddForm): label = u'Add Page' pageTemplateFileName = 'browser/templates/edit_page.pt'", "description(self): return self.form_fields['description'] @property def content(self): return self.form_fields['content'] # --=mpj17=-- # The \"form.action\"", "# lint:ok from zope.component import createObject from zope.formlib import form from Products.Five.browser.pagetemplatefile import", "class AddPageForm(AddForm): label = u'Add Page' pageTemplateFileName = 'browser/templates/edit_page.pt' template = ZopeTwoPageTemplateFile(pageTemplateFileName) def", "'GlobalConfiguration') self.form_fields = form.Fields(interface, render_context=True, omit_readonly=True) self.form_fields['content'].custom_widget = wym_editor_widget self.form_fields['content'].field.default = u'<p>Enter content", "data, errors): if len(errors) == 1: self.status = u'<p>There is an error:</p>' else:", "# Create the content folder and object and apply changes. folder = GSContentPage(self.context,", "'wymeditor' return retval class AddPageForm(AddForm): label = u'Add Page' pageTemplateFileName = 'browser/templates/edit_page.pt' template", "AddPageForm(AddForm): label = u'Add Page' pageTemplateFileName = 'browser/templates/edit_page.pt' template = ZopeTwoPageTemplateFile(pageTemplateFileName) def __init__(self,", "return self.set_data(data) def handle_set_action_failure(self, action, data, errors): if len(errors) == 1: self.status =", "'%s/edit_page.html' % folder.context.absolute_url(0) self.request.response.redirect(url) return else: retval = u'Problem creating page' assert retval", "return self.form_fields['content'] # --=mpj17=-- # The \"form.action\" decorator creates an action instance, with", "createObject from zope.formlib import form from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from zope.app.form.browser import TextAreaWidget", "from zope.app.apidoc.interface import getFieldsInOrder from zope.schema import * import interfaces from page import", "mode='add', id=data['id']) if folder.status['error']: retval = u'%s' % folder.status['msg'] changed = form.applyChanges(folder, self.form_fields,", "request) retval.cssClass = 'wymeditor' return retval class AddPageForm(AddForm): label = u'Add Page' pageTemplateFileName", "self.siteInfo = createObject('groupserver.SiteInfo', context) site_root = context.site_root() assert hasattr(site_root, 'GlobalConfiguration') self.form_fields = form.Fields(interface,", "u'here.</p>' self.mode = 'add' @property def id(self): return self.form_fields['id'] @property def title(self): return", "import TextAreaWidget from zope.app.apidoc.interface import getFieldsInOrder from zope.schema import * import interfaces from", "label, but it helps with readability. @form.action(label=u'Add', failure='handle_set_action_failure') def handle_set(self, action, data): return", "are errors:</p>' def set_data(self, data): assert self.context assert self.form_fields alteredFields = [] for", "title(self): return self.form_fields['title'] @property def description(self): return self.form_fields['description'] @property def content(self): return self.form_fields['content']", "= interface = getattr(interfaces, 'IGSContentPage') AddForm.__init__(self, context, request) self.siteInfo = createObject('groupserver.SiteInfo', context) site_root", "return else: retval = u'Problem creating page' assert retval assert type(retval) == unicode", "self.form_fields['content'].custom_widget = wym_editor_widget self.form_fields['content'].field.default = u'<p>Enter content '\\ u'here.</p>' self.mode = 'add' @property", "necessary). I did not need to explicitly state that \"Edit\" is the #", "The \"form.action\" decorator creates an action instance, with # \"handle_reset\" set to the", "from five.formlib.formbase import AddForm except ImportError: from Products.Five.formlib.formbase import AddForm # lint:ok from", "so redirect to the edit page. if changed: url = '%s/edit_page.html' % folder.context.absolute_url(0)", "id(self): return self.form_fields['id'] @property def title(self): return self.form_fields['title'] @property def description(self): return self.form_fields['description']", "self.request.response.redirect(url) return else: retval = u'Problem creating page' assert retval assert type(retval) ==", "good, so redirect to the edit page. if changed: url = '%s/edit_page.html' %", "alteredFields.append(datum[0]) # Create the content folder and object and apply changes. folder =", "% folder.status['msg'] changed = form.applyChanges(folder, self.form_fields, data) # All good, so redirect to", "u'<p>Enter content '\\ u'here.</p>' self.mode = 'add' @property def id(self): return self.form_fields['id'] @property" ]
[ "x): # self.val = x # self.next = None class Solution: # @param", "# while cur.next: # if cur.next.val >= x: # cur = cur.next #", "lower.next = None else: higher.next = head head = head.next higher = higher.next", "= None lower.next = head2.next return head1.next # if not head: return None", "example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5. ''' # Definition for", "# lower.next = tmp # lower = lower.next # return dummy.next # #", "For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5. ''' # Definition", "= None else: higher.next = head head = head.next higher = higher.next higher.next", "ListNode(0) head2 = ListNode(0) lower = head1 higher = head2 while head: if", "if not head: return None # dummy = ListNode(0) # dummy.next = head", "= cur.next.next # tmp.next = lower.next # lower.next = tmp # lower =", "higher = higher.next higher.next = None lower.next = head2.next return head1.next # if", "= lower.next # lower.next = tmp # lower = lower.next # return dummy.next", "order of the nodes in each of the two partitions. For example, Given", "= cur.next # cur.next = cur.next.next # tmp.next = lower.next # lower.next =", "# dummy = ListNode(0) # dummy.next = head # lower = cur =", "# @param {ListNode} head # @param {integer} x # @return {ListNode} def partition(self,", "x: lower.next = head head = head.next lower = lower.next lower.next = None", "ListNode(0) lower = head1 higher = head2 while head: if head.val < x:", "# return dummy.next # # The above method does not work # #", "None head1 = ListNode(0) head2 = ListNode(0) lower = head1 higher = head2", "# self.next = None class Solution: # @param {ListNode} head # @param {integer}", "lower = cur = dummy # while cur.next: # if cur.next.val >= x:", "# cur.next = cur.next.next # tmp.next = lower.next # lower.next = tmp #", "head = head.next higher = higher.next higher.next = None lower.next = head2.next return", "lower.next = head2.next return head1.next # if not head: return None # dummy", "# cur = cur.next # else: # tmp = cur.next # cur.next =", "Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val", "cur.next.val >= x: # cur = cur.next # else: # tmp = cur.next", "than x come before nodes greater than or equal to x. You should", "greater than or equal to x. You should preserve the original relative order", "# if cur.next.val >= x: # cur = cur.next # else: # tmp", "such that all nodes less than x come before nodes greater than or", "cur = cur.next # else: # tmp = cur.next # cur.next = cur.next.next", "head1 = ListNode(0) head2 = ListNode(0) lower = head1 higher = head2 while", "# else: # tmp = cur.next # cur.next = cur.next.next # tmp.next =", "the nodes in each of the two partitions. For example, Given 1->4->3->2->5->2 and", "head2.next return head1.next # if not head: return None # dummy = ListNode(0)", "and x = 3, return 1->2->2->4->3->5. ''' # Definition for singly-linked list. #", "class ListNode: # def __init__(self, x): # self.val = x # self.next =", "equal to x. You should preserve the original relative order of the nodes", "head # lower = cur = dummy # while cur.next: # if cur.next.val", "each of the two partitions. For example, Given 1->4->3->2->5->2 and x = 3,", "dummy.next = head # lower = cur = dummy # while cur.next: #", "not head: return None head1 = ListNode(0) head2 = ListNode(0) lower = head1", "None # dummy = ListNode(0) # dummy.next = head # lower = cur", "dummy = ListNode(0) # dummy.next = head # lower = cur = dummy", "# class ListNode: # def __init__(self, x): # self.val = x # self.next", "the original relative order of the nodes in each of the two partitions.", "x # self.next = None class Solution: # @param {ListNode} head # @param", "that all nodes less than x come before nodes greater than or equal", "head head = head.next higher = higher.next higher.next = None lower.next = head2.next", "# tmp.next = lower.next # lower.next = tmp # lower = lower.next #", "all nodes less than x come before nodes greater than or equal to", "and a value x, partition it such that all nodes less than x", "= lower.next # return dummy.next # # The above method does not work", "come before nodes greater than or equal to x. You should preserve the", "higher.next = None lower.next = head2.next return head1.next # if not head: return", "a value x, partition it such that all nodes less than x come", "higher.next higher.next = None lower.next = head2.next return head1.next # if not head:", "return 1->2->2->4->3->5. ''' # Definition for singly-linked list. # class ListNode: # def", "{integer} x # @return {ListNode} def partition(self, head, x): if not head: return", "= head # lower = cur = dummy # while cur.next: # if", "of the nodes in each of the two partitions. For example, Given 1->4->3->2->5->2", "= head head = head.next higher = higher.next higher.next = None lower.next =", "lower.next # lower.next = tmp # lower = lower.next # return dummy.next #", "= head1 higher = head2 while head: if head.val < x: lower.next =", "# @return {ListNode} def partition(self, head, x): if not head: return None head1", "not work # # Test Case: 1) [2,1], 2; [1], 2; [1,3,2], 3", "Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5. ''' # Definition for singly-linked", "to x. You should preserve the original relative order of the nodes in", "= None class Solution: # @param {ListNode} head # @param {integer} x #", "@return {ListNode} def partition(self, head, x): if not head: return None head1 =", "None else: higher.next = head head = head.next higher = higher.next higher.next =", "return head1.next # if not head: return None # dummy = ListNode(0) #", "head: if head.val < x: lower.next = head head = head.next lower =", "in each of the two partitions. For example, Given 1->4->3->2->5->2 and x =", "it such that all nodes less than x come before nodes greater than", "head.next higher = higher.next higher.next = None lower.next = head2.next return head1.next #", "singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x", "def __init__(self, x): # self.val = x # self.next = None class Solution:", "@param {ListNode} head # @param {integer} x # @return {ListNode} def partition(self, head,", "x # @return {ListNode} def partition(self, head, x): if not head: return None", "@param {integer} x # @return {ListNode} def partition(self, head, x): if not head:", "than or equal to x. You should preserve the original relative order of", "partition it such that all nodes less than x come before nodes greater", "ListNode: # def __init__(self, x): # self.val = x # self.next = None", "lower.next = head head = head.next lower = lower.next lower.next = None else:", "= head head = head.next lower = lower.next lower.next = None else: higher.next", "# lower = cur = dummy # while cur.next: # if cur.next.val >=", "lower = lower.next # return dummy.next # # The above method does not", "list. # class ListNode: # def __init__(self, x): # self.val = x #", "for singly-linked list. # class ListNode: # def __init__(self, x): # self.val =", "# Definition for singly-linked list. # class ListNode: # def __init__(self, x): #", "# self.val = x # self.next = None class Solution: # @param {ListNode}", "None lower.next = head2.next return head1.next # if not head: return None #", "higher = head2 while head: if head.val < x: lower.next = head head", "not head: return None # dummy = ListNode(0) # dummy.next = head #", "cur.next: # if cur.next.val >= x: # cur = cur.next # else: #", "# tmp = cur.next # cur.next = cur.next.next # tmp.next = lower.next #", "# The above method does not work # # Test Case: 1) [2,1],", "= dummy # while cur.next: # if cur.next.val >= x: # cur =", "= higher.next higher.next = None lower.next = head2.next return head1.next # if not", "before nodes greater than or equal to x. You should preserve the original", "or equal to x. You should preserve the original relative order of the", "while head: if head.val < x: lower.next = head head = head.next lower", "head: return None # dummy = ListNode(0) # dummy.next = head # lower", "# @param {integer} x # @return {ListNode} def partition(self, head, x): if not", "cur.next.next # tmp.next = lower.next # lower.next = tmp # lower = lower.next", "self.next = None class Solution: # @param {ListNode} head # @param {integer} x", "= head2 while head: if head.val < x: lower.next = head head =", "if head.val < x: lower.next = head head = head.next lower = lower.next", "head # @param {integer} x # @return {ListNode} def partition(self, head, x): if", "self.val = x # self.next = None class Solution: # @param {ListNode} head", "dummy # while cur.next: # if cur.next.val >= x: # cur = cur.next", "method does not work # # Test Case: 1) [2,1], 2; [1], 2;", "head1 higher = head2 while head: if head.val < x: lower.next = head", "= head2.next return head1.next # if not head: return None # dummy =", "while cur.next: # if cur.next.val >= x: # cur = cur.next # else:", "class Solution: # @param {ListNode} head # @param {integer} x # @return {ListNode}", "if cur.next.val >= x: # cur = cur.next # else: # tmp =", "lower.next lower.next = None else: higher.next = head head = head.next higher =", "cur.next # else: # tmp = cur.next # cur.next = cur.next.next # tmp.next", "preserve the original relative order of the nodes in each of the two", "else: # tmp = cur.next # cur.next = cur.next.next # tmp.next = lower.next", "tmp.next = lower.next # lower.next = tmp # lower = lower.next # return", "# def __init__(self, x): # self.val = x # self.next = None class", "nodes in each of the two partitions. For example, Given 1->4->3->2->5->2 and x", "partition(self, head, x): if not head: return None head1 = ListNode(0) head2 =", "= ListNode(0) head2 = ListNode(0) lower = head1 higher = head2 while head:", "return dummy.next # # The above method does not work # # Test", "''' Given a linked list and a value x, partition it such that", "return None # dummy = ListNode(0) # dummy.next = head # lower =", "lower = head1 higher = head2 while head: if head.val < x: lower.next", "head, x): if not head: return None head1 = ListNode(0) head2 = ListNode(0)", "value x, partition it such that all nodes less than x come before", "x. You should preserve the original relative order of the nodes in each", "head.next lower = lower.next lower.next = None else: higher.next = head head =", "__init__(self, x): # self.val = x # self.next = None class Solution: #", "Given a linked list and a value x, partition it such that all", "lower.next # return dummy.next # # The above method does not work #", "a linked list and a value x, partition it such that all nodes", "{ListNode} def partition(self, head, x): if not head: return None head1 = ListNode(0)", "# lower = lower.next # return dummy.next # # The above method does", "{ListNode} head # @param {integer} x # @return {ListNode} def partition(self, head, x):", "above method does not work # # Test Case: 1) [2,1], 2; [1],", "head.val < x: lower.next = head head = head.next lower = lower.next lower.next", "# dummy.next = head # lower = cur = dummy # while cur.next:", "less than x come before nodes greater than or equal to x. You", "cur.next # cur.next = cur.next.next # tmp.next = lower.next # lower.next = tmp", "nodes less than x come before nodes greater than or equal to x.", "x: # cur = cur.next # else: # tmp = cur.next # cur.next", "higher.next = head head = head.next higher = higher.next higher.next = None lower.next", "= 3, return 1->2->2->4->3->5. ''' # Definition for singly-linked list. # class ListNode:", "= ListNode(0) lower = head1 higher = head2 while head: if head.val <", "head2 while head: if head.val < x: lower.next = head head = head.next", "= cur.next # else: # tmp = cur.next # cur.next = cur.next.next #", "linked list and a value x, partition it such that all nodes less", "x, partition it such that all nodes less than x come before nodes", "= x # self.next = None class Solution: # @param {ListNode} head #", "head = head.next lower = lower.next lower.next = None else: higher.next = head", "of the two partitions. For example, Given 1->4->3->2->5->2 and x = 3, return", "tmp = cur.next # cur.next = cur.next.next # tmp.next = lower.next # lower.next", "head head = head.next lower = lower.next lower.next = None else: higher.next =", "lower.next = tmp # lower = lower.next # return dummy.next # # The", "does not work # # Test Case: 1) [2,1], 2; [1], 2; [1,3,2],", "x come before nodes greater than or equal to x. You should preserve", "1->2->2->4->3->5. ''' # Definition for singly-linked list. # class ListNode: # def __init__(self,", "3, return 1->2->2->4->3->5. ''' # Definition for singly-linked list. # class ListNode: #", "None class Solution: # @param {ListNode} head # @param {integer} x # @return", "cur = dummy # while cur.next: # if cur.next.val >= x: # cur", "head2 = ListNode(0) lower = head1 higher = head2 while head: if head.val", ">= x: # cur = cur.next # else: # tmp = cur.next #", "else: higher.next = head head = head.next higher = higher.next higher.next = None", "partitions. For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5. ''' #", "return None head1 = ListNode(0) head2 = ListNode(0) lower = head1 higher =", "Solution: # @param {ListNode} head # @param {integer} x # @return {ListNode} def", "You should preserve the original relative order of the nodes in each of", "original relative order of the nodes in each of the two partitions. For", "if not head: return None head1 = ListNode(0) head2 = ListNode(0) lower =", "''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x):", "# # The above method does not work # # Test Case: 1)", "= head.next lower = lower.next lower.next = None else: higher.next = head head", "list and a value x, partition it such that all nodes less than", "head1.next # if not head: return None # dummy = ListNode(0) # dummy.next", "tmp # lower = lower.next # return dummy.next # # The above method", "1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5. ''' # Definition for singly-linked list.", "nodes greater than or equal to x. You should preserve the original relative", "< x: lower.next = head head = head.next lower = lower.next lower.next =", "= lower.next lower.next = None else: higher.next = head head = head.next higher", "The above method does not work # # Test Case: 1) [2,1], 2;", "x = 3, return 1->2->2->4->3->5. ''' # Definition for singly-linked list. # class", "= head.next higher = higher.next higher.next = None lower.next = head2.next return head1.next", "two partitions. For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5. '''", "def partition(self, head, x): if not head: return None head1 = ListNode(0) head2", "ListNode(0) # dummy.next = head # lower = cur = dummy # while", "the two partitions. For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.", "relative order of the nodes in each of the two partitions. For example,", "= tmp # lower = lower.next # return dummy.next # # The above", "= cur = dummy # while cur.next: # if cur.next.val >= x: #", "# if not head: return None # dummy = ListNode(0) # dummy.next =", "lower = lower.next lower.next = None else: higher.next = head head = head.next", "= ListNode(0) # dummy.next = head # lower = cur = dummy #", "dummy.next # # The above method does not work # # Test Case:", "x): if not head: return None head1 = ListNode(0) head2 = ListNode(0) lower", "should preserve the original relative order of the nodes in each of the", "head: return None head1 = ListNode(0) head2 = ListNode(0) lower = head1 higher", "cur.next = cur.next.next # tmp.next = lower.next # lower.next = tmp # lower" ]